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
@@ -5,7 +5,7 @@ import { appendFileSync, closeSync, mkdirSync, openSync, readFileSync, readSync,
5
5
  import path from "node:path";
6
6
  import { checkoutRootOf } from "./checkout-root.mjs";
7
7
 
8
- export const RECORD_TYPES = ["dispatch", "stop", "verdict", "merge", "issue-update", "cost"];
8
+ export const RECORD_TYPES = ["dispatch", "stop", "verdict", "merge", "issue-update", "cost", "ci-failure", "ci-resolution"];
9
9
  const MIN_SHA = 7;
10
10
  const HEX = /^[0-9a-f]+$/;
11
11
 
@@ -128,6 +128,8 @@ export const lastTaskDispatchOn = (records, branch) =>
128
128
  const short = (sha) => (typeof sha === "string" ? sha.slice(0, MIN_SHA) : "");
129
129
 
130
130
  const SUMMARIES = {
131
+ "ci-failure": (r) => `${r.branch} ${short(r.head)} ${r.os} ${r.file ?? r.job} ${r.test}: ${r.error}`,
132
+ "ci-resolution": (r) => `${r.branch} ${short(r.head)} resolved ${r.ids.length} CI failures`,
131
133
  dispatch: (r) =>
132
134
  `${r.agentType} ${r.task ? `${r.branch} ${short(r.head)}` : "(no task)"}${r.resumeReason ? ` NO-RESUME: ${r.resumeReason}` : ""}${r.fix ? ` FIX: ${r.fix}` : ""}${
133
135
  r.ciPass ? ` CI-PASS: ${short(r.ciPass.sha)} ${r.ciPass.reason}` : ""
@@ -153,7 +155,7 @@ const COST_KEYS = ["input", "output", "cacheRead", "cacheCreation", "toolCalls"]
153
155
  const emptyTotal = () => ({ agents: 0, input: 0, output: 0, cacheRead: 0, cacheCreation: 0, toolCalls: 0 });
154
156
 
155
157
  /** The cost records, one per agent: a resumed agent stops again with its whole transcript, so its newest record replaces the older. */
156
- function latestCosts(records) {
158
+ export function latestCosts(records) {
157
159
  const latest = new Map();
158
160
  for (const record of records) if (record.type === "cost") latest.set(`${record.session}/${record.agentId}`, record);
159
161
  return [...latest.values()];
@@ -24,7 +24,7 @@ const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", en
24
24
  /** A primary checkout with one commit, and a linked worktree of it on feat/1-x. */
25
25
  function repo(t) {
26
26
  const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-ledger-")));
27
- t.after(() => rmSync(base, { recursive: true, force: true }));
27
+ t.after(() => rmSync(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
28
28
  const main = path.join(base, "main");
29
29
  git(base, "init", "-q", "-b", "main", main);
30
30
  for (const [key, value] of [["user.name", "qc"], ["user.email", "qc@example.com"], ["commit.gpgsign", "false"]]) {
@@ -48,7 +48,7 @@ test("a linked worktree and its primary checkout share one ledger", (t) => {
48
48
 
49
49
  test("a folder with no .git has no ledger", (t) => {
50
50
  const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-ledger-none-")));
51
- t.after(() => rmSync(base, { recursive: true, force: true }));
51
+ t.after(() => rmSync(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
52
52
  assert.equal(commonDirOf(base), null);
53
53
  assert.equal(ledgerFileOf(base), null);
54
54
  });
@@ -118,7 +118,7 @@ test("qc ledger prints one line per record, and a branch keeps only its own", (t
118
118
 
119
119
  test("an append after a torn last line keeps the new record whole", (t) => {
120
120
  const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-ledger-torn-")));
121
- t.after(() => rmSync(base, { recursive: true, force: true }));
121
+ t.after(() => rmSync(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
122
122
  const file = path.join(base, "ledger.jsonl");
123
123
  appendRecord(file, { type: "stop", role: "implementer" });
124
124
  appendFileSync(file, '{"type":"stop","role":"tor');
@@ -194,3 +194,12 @@ test("the deciding verdict on a sha is a CHANGES_REQUIRED that is the newest of
194
194
  assert.equal(decidingVerdictFor([v("CHANGES_REQUIRED", "y"), v("APPROVED", "y")], sha, ["branch"]).verdict, "APPROVED");
195
195
  assert.equal(decidingVerdictFor([v("APPROVED")], sha, ["task"]), null);
196
196
  });
197
+
198
+ test("Codex verdicts share the worktree ledger and only count when selected", (t) => {
199
+ const { main, linked } = repo(t);
200
+ const sha = git(linked, "rev-parse", "HEAD");
201
+ appendRecord(ledgerFileOf(linked), { type: "verdict", kind: "codex", verdict: "CHANGES_REQUIRED", sha, branch: "feat/1-x" });
202
+ const records = readLedger(ledgerFileOf(main));
203
+ assert.equal(decidingVerdictFor(records, sha, ["branch"]), null);
204
+ assert.equal(decidingVerdictFor(records, sha, ["branch", "codex"]).verdict, "CHANGES_REQUIRED");
205
+ });
@@ -0,0 +1,53 @@
1
+ // The ledger resource for passing platform legs and preview reservations.
2
+ import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { execFileSync } from "node:child_process";
5
+ import { load } from "../config.mjs";
6
+ import { ledgerFileOf } from "./ledger.mjs";
7
+ import { platformRisk } from "./platform-risk.mjs";
8
+
9
+ export const hostOS = (platform = process.platform) => platform === "win32" ? "windows" : platform;
10
+ export const gitText = (root, ...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
11
+
12
+ export function legRecords(root) {
13
+ const file = ledgerFileOf(root);
14
+ if (!file) throw new Error("platform legs need a git worktree");
15
+ let contents;
16
+ try { contents = readFileSync(file, "utf8"); }
17
+ catch (error) { if (error.code === "ENOENT") return []; throw error; }
18
+ return contents.split(/\r?\n/).flatMap((line) => {
19
+ try { const record = JSON.parse(line); return ["leg", "leg-preview"].includes(record.type) ? [record] : []; }
20
+ catch { return []; }
21
+ });
22
+ }
23
+
24
+ export function appendLeg(root, record) {
25
+ if (record.type !== undefined && !["leg", "leg-preview"].includes(record.type)) throw new Error("invalid platform leg type");
26
+ if (!["linux", "windows"].includes(record.os)) throw new Error("unknown platform for leg");
27
+ if (!record.head || !["local", "preview"].includes(record.source)) throw new Error("invalid platform leg");
28
+ const file = ledgerFileOf(root);
29
+ if (!file) throw new Error("platform legs need a git worktree");
30
+ mkdirSync(path.dirname(file), { recursive: true });
31
+ // A leading newline separates a record from a torn write by another ledger producer.
32
+ appendFileSync(file, `\n${JSON.stringify({ ...record, type: record.type ?? "leg", at: new Date().toISOString() })}\n`);
33
+ }
34
+
35
+ export function readyProblems(root, head) {
36
+ const config = load(root);
37
+ const hits = platformRisk(root, config.check.base, head);
38
+ const passed = new Set(legRecords(root).filter((record) => record.type === "leg" && record.head === head && ["linux", "windows"].includes(record.os) && ["local", "preview"].includes(record.source)).map((record) => record.os));
39
+ const missing = hits.length > 0 || passed.size === 0 ? config.ready.platforms.filter((os) => !passed.has(os)) : [];
40
+ return { missing, hits };
41
+ }
42
+
43
+ export function readyLines({ missing, hits }) {
44
+ return missing.length === 0 ? [] : [`Missing platform legs: ${missing.join(", ")}`, ...hits.slice(0, 3).map((hit) => `${hit.file}:${hit.line}: ${hit.reason}`)];
45
+ }
46
+
47
+ export function runReadyCheck(root, write = console.error) {
48
+ try {
49
+ const problems = readyProblems(root, gitText(root, "rev-parse", "HEAD"));
50
+ for (const line of readyLines(problems)) write(line);
51
+ return problems.missing.length > 0 ? 1 : 0;
52
+ } catch (error) { write(`ready-check: ${error.message.split("\n")[0]}`); return 1; }
53
+ }
@@ -0,0 +1,70 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { execFileSync } from "node:child_process";
7
+ import { runAffectedCheck } from "./check.mjs";
8
+ import { appendLeg, legRecords, readyProblems, readyLines, runReadyCheck } from "./legs.mjs";
9
+
10
+ export function legFixture(t) {
11
+ const root = mkdtempSync(path.join(tmpdir(), "qc-legs-"));
12
+ t.after(() => rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));
13
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' }).trim();
14
+ git('init', '-q');
15
+ git('config', 'user.email', 'test@example.com');
16
+ git('config', 'user.name', 'Test');
17
+ writeFileSync(path.join(root, 'a.mjs'), 'export const value = 1;\n');
18
+ git('add', '.');
19
+ git('commit', '-qm', 'base');
20
+ git('branch', 'base');
21
+ writeFileSync(path.join(root, 'qc.config.json'), JSON.stringify({ check: { base: 'base' }, ready: { platforms: ['linux', 'windows'] } }));
22
+ return { root, git };
23
+ }
24
+
25
+ test('a safe head needs one current passing leg; risk needs every configured platform', async (t) => {
26
+ const { root, git } = legFixture(t);
27
+ git('add', '.'); git('commit', '-qm', 'config');
28
+ const affected = (platform) => runAffectedCheck({ root }, {}, { platform, gates: async () => ({ problems: [], lines: [] }), commands: async () => 0 });
29
+ const head = git('rev-parse', 'HEAD');
30
+ assert.equal(readyProblems(root, head).missing.length, 2);
31
+ const output = [];
32
+ assert.equal(runReadyCheck(root, (line) => output.push(line)), 1);
33
+ assert.equal(output.length, 1);
34
+ appendLeg(root, { os: 'linux', head: 'old', source: 'local' });
35
+ assert.equal(readyProblems(root, head).missing.length, 2);
36
+ assert.equal(await affected('linux'), 0);
37
+ assert.deepEqual(readyProblems(root, head).missing, []);
38
+ assert.equal(runReadyCheck(root, () => assert.fail('a pass must be silent')), 0);
39
+ writeFileSync(path.join(root, 'a.mjs'), 'process.platform;\nEPERM;\nlisten(3000);\n"\\r\\n";\n');
40
+ git('add', 'a.mjs'); git('commit', '-qm', 'risk');
41
+ const risky = git('rev-parse', 'HEAD');
42
+ appendLeg(root, { os: 'linux', head: risky, source: 'preview' });
43
+ const problems = readyProblems(root, risky);
44
+ assert.deepEqual(problems.missing, ['windows']);
45
+ assert.equal(readyLines(problems).length, 4);
46
+ assert.match(readyLines(problems)[1], /a\.mjs:1/);
47
+ assert.equal(await affected('win32'), 0);
48
+ assert.deepEqual(readyLines(readyProblems(root, risky)), []);
49
+ });
50
+
51
+ test('a linked worktree reads legs from the common ledger', async (t) => {
52
+ const { root, git } = legFixture(t);
53
+ git('add', '.'); git('commit', '-qm', 'config');
54
+ const linked = path.join(root, 'linked');
55
+ git('worktree', 'add', '-qb', 'linked', linked);
56
+ const head = git('rev-parse', 'HEAD');
57
+ assert.equal(await runAffectedCheck({ root: linked }, {}, { platform: 'win32', gates: async () => ({ problems: [], lines: [] }), commands: async () => 0 }), 0);
58
+ assert.equal(legRecords(root)[0].head, head);
59
+ });
60
+
61
+ test('leg records share the common ledger and tolerate torn lines', (t) => {
62
+ const { root, git } = legFixture(t);
63
+ mkdirSync(path.join(root, '.git', 'qc'), { recursive: true });
64
+ writeFileSync(path.join(root, '.git', 'qc', 'ledger.jsonl'), '{torn');
65
+ appendLeg(root, { os: 'linux', head: git('rev-parse', 'HEAD'), source: 'local' });
66
+ assert.equal(legRecords(root).length, 1);
67
+ assert.throws(() => appendLeg(root, { os: 'linux', head: 'x', source: 'affected' }), /invalid platform leg/);
68
+ assert.throws(() => appendLeg(root, { os: 'linux', head: 'x', source: 'local', type: 'affected' }), /invalid platform leg type/);
69
+ assert.throws(() => appendLeg(root, { os: 'darwin', head: 'x', source: 'local' }), /platform/);
70
+ });
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { spawnSync } from "node:child_process";
6
6
  import { createRequire } from "node:module";
7
- import { existsSync } from "node:fs";
7
+ import { existsSync, readFileSync } from "node:fs";
8
8
  import path from "node:path";
9
9
  import { pathToFileURL } from "node:url";
10
10
  import { gitOut, gitStatusWithin } from "./git-read.mjs";
@@ -114,10 +114,55 @@ function parseArgs(args) {
114
114
  return options;
115
115
  }
116
116
 
117
- /** @returns the exit code: 1 when an error sits on a changed line, else 0. Warnings print and pass. */
117
+ function lintBaseline(root, staged) {
118
+ const file = "eslint-suppressions.json";
119
+ const text = staged ? stagedText(root, file) : existsSync(path.join(root, file)) ? readFileSync(path.join(root, file), "utf8") : null;
120
+ const baseline = text === null ? {} : JSON.parse(text);
121
+ if (!baseline || typeof baseline !== "object" || Array.isArray(baseline)) throw new Error(`${file} must hold an object`);
122
+ for (const [rel, rules] of Object.entries(baseline)) {
123
+ const resolved = path.relative(root, path.resolve(root, rel));
124
+ if (!rel || path.isAbsolute(rel) || resolved.startsWith("..") || !rules || typeof rules !== "object" || Array.isArray(rules)) {
125
+ throw new Error(`invalid file entry in ${file}: ${rel}`);
126
+ }
127
+ for (const [rule, entry] of Object.entries(rules)) {
128
+ if (!entry || !Number.isSafeInteger(entry.count) || entry.count < 0) throw new Error(`invalid count in ${file}: ${rel} (${rule})`);
129
+ }
130
+ }
131
+ return baseline;
132
+ }
133
+
134
+ function applyBaseline(results, baseline, root, checkStale) {
135
+ const byFile = new Map(results.map((result) => [path.relative(root, result.filePath).split(path.sep).join("/"), result]));
136
+ let stale = false;
137
+ for (const [file, rules] of baseline) {
138
+ const result = byFile.get(file);
139
+ const counts = new Map();
140
+ for (const message of result?.messages ?? []) {
141
+ if (message.severity === 2 && message.ruleId) counts.set(message.ruleId, (counts.get(message.ruleId) ?? 0) + 1);
142
+ }
143
+ for (const [rule, { count }] of Object.entries(rules)) {
144
+ const actual = counts.get(rule) ?? 0;
145
+ if (checkStale && actual < count) {
146
+ console.error(`${file}: ${count - actual} suppressions left that do not occur anymore (${rule}); prune eslint-suppressions.json`);
147
+ stale = true;
148
+ }
149
+ if (result && actual > 0 && actual <= count) result.messages = result.messages.filter((message) => message.ruleId !== rule);
150
+ }
151
+ }
152
+ return stale;
153
+ }
154
+
155
+ /** Warnings pass; changed-line errors and invalid or stale baselines return failure codes. */
118
156
  export async function runLintChanged(config, args) {
119
157
  const root = config.root;
120
158
  const options = parseArgs(args);
159
+ let baseline;
160
+ try {
161
+ baseline = lintBaseline(root, options.staged);
162
+ } catch (error) {
163
+ console.error(`lint baseline error: ${error.message}`);
164
+ return 2;
165
+ }
121
166
  const ESLint = await loadEslint(root);
122
167
  if (ESLint === null) {
123
168
  console.log("lint skipped: eslint is not installed in this repository");
@@ -125,24 +170,28 @@ export async function runLintChanged(config, args) {
125
170
  }
126
171
  const base = options.staged ? null : baseOf(root, options.base ?? config.check.base);
127
172
  const changed = changedLines(root, { staged: options.staged, base });
128
- const wanted = options.files.map((file) => path.relative(root, path.resolve(file)).split(path.sep).join("/"));
173
+ const wanted = new Set(options.files.map((file) => path.relative(root, path.resolve(file)).split(path.sep).join("/")));
129
174
  const eslint = new ESLint({ cwd: root });
130
175
  const files = [];
131
- for (const file of changed.keys()) {
132
- if (!LINTABLE.test(file) || (wanted.length > 0 && !wanted.includes(file))) continue;
133
- if (!existsSync(path.join(root, file)) || (await eslint.isPathIgnored(path.join(root, file)))) continue;
176
+ const applicableBaseline = new Map();
177
+ for (const file of new Set([...changed.keys(), ...Object.keys(baseline)])) {
178
+ if (!LINTABLE.test(file) || (wanted.size > 0 && !wanted.has(file))) continue;
179
+ if (await eslint.isPathIgnored(path.join(root, file))) continue;
180
+ if (Object.hasOwn(baseline, file)) applicableBaseline.set(file, baseline[file]);
181
+ if (!options.staged && !existsSync(path.join(root, file))) continue;
134
182
  files.push(file);
135
183
  }
136
- if (files.length === 0) return 0;
137
-
138
184
  const results = [];
139
185
  for (const file of files) {
140
186
  const filePath = path.join(root, file);
141
187
  // A staged commit is judged as it will be stored, not as the working tree holds it now.
142
188
  const staged = options.staged ? stagedText(root, file) : null;
189
+ if (options.staged && staged === null) continue;
143
190
  results.push(...(staged === null ? await eslint.lintFiles([filePath]) : await eslint.lintText(staged, { filePath })));
144
191
  }
145
- const { kept, skipped } = onChangedLines(results, changed, root);
192
+ const stale = applyBaseline(results, applicableBaseline, root, wanted.size === 0);
193
+ const selected = wanted.size > 0 ? new Map([...changed].filter(([file]) => wanted.has(file))) : changed;
194
+ const { kept, skipped } = onChangedLines(results.filter((result) => selected.has(path.relative(root, result.filePath).split(path.sep).join("/"))), selected, root);
146
195
  const errors = kept.filter(({ message }) => message.fatal || message.severity === 2);
147
196
  for (const { file, message } of kept) {
148
197
  const kind = message.fatal || message.severity === 2 ? "error" : "warning";
@@ -153,5 +202,5 @@ export async function runLintChanged(config, args) {
153
202
  }
154
203
  // Said once, so a reader knows the gate saw them and chose not to count them.
155
204
  if (skipped > 0) console.error(`${skipped} older problem(s) on lines this change leaves alone are not counted. Leave them alone.`);
156
- return errors.length > 0 ? 1 : 0;
205
+ return stale ? 2 : errors.length > 0 ? 1 : 0;
157
206
  }
@@ -5,7 +5,7 @@ import { createRequire } from "node:module";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
7
  import { test } from "node:test";
8
- import { fileURLToPath } from "node:url";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
9
  import { onChangedLines, parseDiff } from "./lint-changed.mjs";
10
10
 
11
11
  const QC = path.join(path.dirname(fileURLToPath(import.meta.url)), "qc.mjs");
@@ -100,3 +100,114 @@ test("a repository without ESLint skips the lint", (t) => {
100
100
  assert.equal(result.status, 0);
101
101
  assert.match(result.stdout, /lint skipped/);
102
102
  });
103
+
104
+ test("qc lint applies the baseline per file and rule up to the recorded count", (t) => {
105
+ const { root, qc } = repo(t);
106
+ writeFileSync(path.join(root, "eslint-suppressions.json"), JSON.stringify({ "src/old.mjs": { "no-var": { count: 1 } } }));
107
+ writeFileSync(path.join(root, "src", "old.mjs"), "var legacy = 2;\nexport const kept = legacy;\n");
108
+ const suppressed = qc();
109
+ assert.equal(suppressed.status, 0, suppressed.stderr);
110
+ writeFileSync(path.join(root, "src", "old.mjs"), "var legacy = 2;\nexport const kept = legacy;\nvar added = 3;\n");
111
+ assert.equal(qc().status, 1, "a count over the baseline still fails");
112
+ writeFileSync(path.join(root, "src", "new.mjs"), "var fresh = 1;\n");
113
+ const otherFile = qc();
114
+ assert.equal(otherFile.status, 1, otherFile.stderr);
115
+ assert.match(otherFile.stderr, /src\/new\.mjs:1:1.*no-var/);
116
+ });
117
+
118
+ for (const staged of [false, true]) {
119
+ test(`named files apply their baseline without linting other files or checking stale entries (staged=${staged})`, (t) => {
120
+ const { root, git, qc } = repo(t);
121
+ writeFileSync(path.join(root, "eslint.config.mjs"), `export default [{
122
+ files: ["**/*.mjs"],
123
+ plugins: { probe: { rules: { selected: { create(context) {
124
+ if (context.filename.endsWith("old.mjs")) throw new Error("unselected file was linted");
125
+ return {};
126
+ } } } } },
127
+ rules: { "no-var": "error", "probe/selected": "error" },
128
+ }];\n`);
129
+ writeFileSync(path.join(root, "eslint-suppressions.json"), JSON.stringify({
130
+ "src/old.mjs": { "no-var": { count: 2 } },
131
+ "src/new.mjs": { "no-var": { count: 1 } },
132
+ }));
133
+ const source = path.join(root, "src", "new.mjs");
134
+ const run = () => {
135
+ if (staged) git("add", "-A");
136
+ return qc(...(staged ? ["--staged"] : []), "src/new.mjs");
137
+ };
138
+ writeFileSync(source, "var fresh = 1;\n");
139
+ const suppressed = run();
140
+ assert.equal(suppressed.status, 0, suppressed.stderr);
141
+ writeFileSync(source, "const fresh = 1;\n");
142
+ const stale = run();
143
+ assert.equal(stale.status, 0, stale.stderr);
144
+ assert.doesNotMatch(stale.stderr, /suppressions left/);
145
+ writeFileSync(source, "var fresh = 1;\nvar added = 2;\n");
146
+ const increased = run();
147
+ assert.equal(increased.status, 1, increased.stderr);
148
+ assert.match(increased.stderr, /src\/new\.mjs:1:1.*no-var/);
149
+ });
150
+ }
151
+
152
+ for (const staged of [false, true]) {
153
+ for (const file of ["src/notes.md", "src/ignored.mjs"]) {
154
+ test(`qc lint skips a baseline for an unsupported or ignored file: ${file} (staged=${staged})`, (t) => {
155
+ const { root, git, qc } = repo(t);
156
+ writeFileSync(path.join(root, "eslint.config.mjs"), 'export default [{ ignores: ["src/ignored.mjs"] }, { files: ["**/*.mjs"], rules: { "no-var": "error" } }];\n');
157
+ writeFileSync(path.join(root, file), "var skipped = 1;\n");
158
+ writeFileSync(path.join(root, "eslint-suppressions.json"), JSON.stringify({ [file]: { "no-var": { count: 1 } } }));
159
+ if (staged) git("add", "eslint-suppressions.json", file);
160
+ const result = qc(...(staged ? ["--staged"] : []));
161
+ assert.equal(result.status, 0, result.stderr);
162
+ assert.doesNotMatch(result.stderr, /suppressions left/);
163
+ });
164
+ }
165
+ }
166
+
167
+ test("qc lint fails stale baseline entries, including untouched and deleted files", (t) => {
168
+ const { root, qc } = repo(t);
169
+ const baseline = path.join(root, "eslint-suppressions.json");
170
+ writeFileSync(baseline, JSON.stringify({ "src/old.mjs": { "no-var": { count: 2 } } }));
171
+ assert.equal(qc().status, 2, "an untouched file with fewer findings fails");
172
+ writeFileSync(baseline, JSON.stringify({ "src/gone.mjs": { "no-var": { count: 1 } } }));
173
+ assert.equal(qc().status, 2, "a deleted file leaves a stale entry");
174
+ writeFileSync(baseline, JSON.stringify({ "src/old.mjs": { "no-console": { count: 1 } } }));
175
+ assert.equal(qc().status, 2, "a different rule cannot consume the count");
176
+ });
177
+
178
+ test("a staged baseline and source survive unstaged edits and deletion", (t) => {
179
+ const { root, git, qc } = repo(t);
180
+ const source = path.join(root, "src", "old.mjs");
181
+ const baseline = path.join(root, "eslint-suppressions.json");
182
+ writeFileSync(source, "var legacy = 2;\nexport const kept = legacy;\n");
183
+ writeFileSync(baseline, JSON.stringify({ "src/old.mjs": { "no-var": { count: 1 } } }));
184
+ git("add", "src/old.mjs", "eslint-suppressions.json");
185
+ writeFileSync(source, "const legacy = 3;\nexport const kept = legacy;\n");
186
+ writeFileSync(baseline, JSON.stringify({ "src/old.mjs": { "no-var": { count: 2 } } }));
187
+ const edited = qc("--staged");
188
+ assert.equal(edited.status, 0, edited.stderr);
189
+ rmSync(source);
190
+ const deleted = qc("--staged");
191
+ assert.equal(deleted.status, 0, deleted.stderr);
192
+ });
193
+
194
+ test("qc lint catches a component inserted above an unchanged component", (t) => {
195
+ const { root, git, qc } = repo(t);
196
+ const require = createRequire(import.meta.url);
197
+ const parser = pathToFileURL(require.resolve("@typescript-eslint/parser")).href;
198
+ const plugin = new URL("../eslint/index.mjs", import.meta.url).href;
199
+ writeFileSync(path.join(root, "eslint.config.mjs"), `
200
+ import parser from ${JSON.stringify(parser)};
201
+ import { rules } from ${JSON.stringify(plugin)};
202
+ export default [{ files: ["**/*.tsx"], languageOptions: { parser }, plugins: { qc: { rules } }, rules: { "qc/one-component-per-file": "error" } }];
203
+ `);
204
+ const original = "export function Existing() { return <li />; }\n";
205
+ writeFileSync(path.join(root, "src/view.tsx"), original);
206
+ git("add", "eslint.config.mjs", "src/view.tsx");
207
+ const commit = git("-c", "user.email=t@example.com", "-c", "user.name=t", "commit", "-q", "-m", "test(qc): seed component");
208
+ assert.equal(commit.status, 0, commit.stderr);
209
+ writeFileSync(path.join(root, "src/view.tsx"), "const Added = () => <i />;\n" + original);
210
+ const result = qc();
211
+ assert.equal(result.status, 1, result.stderr);
212
+ assert.match(result.stderr, /src\/view\.tsx:1:7.*qc\/one-component-per-file/);
213
+ });
@@ -0,0 +1,134 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { spawnCommand } from "./spawn-command.mjs";
7
+
8
+ const cleanup = { recursive: true, force: true, maxRetries: 5, retryDelay: 100 };
9
+ const git = (worktree, ...args) => execFileSync("git", ["--literal-pathspecs", ...args], {
10
+ cwd: worktree, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024,
11
+ });
12
+ const names = (text) => text.split("\0").filter(Boolean);
13
+ const normalize = (file) => file.replace(/\\/g, "/");
14
+ const testFile = (file) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(file) || /(^|\/)(__tests__|tests?|spec)\/.*\.[cm]?[jt]sx?$/.test(file);
15
+ const registration = /^\s*(test|it)(\.only|\.skip)?\(/;
16
+
17
+ /** Rejects unsafe lock paths and symlinks before reading or copying files. */
18
+ function safeFile(worktree, file) {
19
+ const name = normalize(file);
20
+ if (!name || path.posix.isAbsolute(name) || /^[A-Za-z]:/.test(name) || name.split("/").some((part) => !part || part === "." || part === ".." || part.toLowerCase() === ".git")) throw new Error(`unsafe locked test path: ${file}`);
21
+ const target = path.resolve(worktree, name);
22
+ const relative = path.relative(realpathSync(worktree), realpathSync(target));
23
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative) || !lstatSync(target).isFile()) throw new Error(`unsafe locked test path: ${file}`);
24
+ return target;
25
+ }
26
+
27
+ /** The common directory shares locks between the main checkout and linked worktrees. */
28
+ export function lockedTestsFile(worktree) {
29
+ const common = git(worktree, "rev-parse", "--path-format=absolute", "--git-common-dir").trim();
30
+ const branch = git(worktree, "symbolic-ref", "--quiet", "--short", "HEAD").trim();
31
+ return path.join(common, "qc", "locked-tests", `${encodeURIComponent(branch)}.json`);
32
+ }
33
+
34
+ export function readLockedTests(worktree) {
35
+ const file = lockedTestsFile(worktree);
36
+ if (!existsSync(file)) return null;
37
+ const locked = JSON.parse(readFileSync(file, "utf8"));
38
+ if (!locked || typeof locked !== "object" || Array.isArray(locked) || Object.entries(locked).some(([name, hash]) => !name || typeof hash !== "string" || !/^[a-f0-9]{64}$/.test(hash))) throw new Error("invalid locked-tests file");
39
+ return locked;
40
+ }
41
+
42
+ const hashFile = (worktree, file) => createHash("sha256").update(readFileSync(safeFile(worktree, file))).digest("hex");
43
+
44
+ /** Atomically publishes the exact path-to-hash map after a successful tests run. */
45
+ export function lockTests(worktree, files) {
46
+ const locked = Object.fromEntries([...new Set(files.map(normalize))].sort().map((file) => [file, hashFile(worktree, file)]));
47
+ const destination = lockedTestsFile(worktree);
48
+ mkdirSync(path.dirname(destination), { recursive: true });
49
+ const temporary = `${destination}.${randomUUID()}.tmp`;
50
+ try {
51
+ writeFileSync(temporary, `${JSON.stringify(locked, null, 2)}\n`, { flag: "wx" });
52
+ renameSync(temporary, destination);
53
+ } finally { rmSync(temporary, cleanup); }
54
+ return locked;
55
+ }
56
+
57
+ /** A frozen map also catches deletion and rename, even if the child rewrites its lock. */
58
+ export function checkLockedTests(worktree, locked = readLockedTests(worktree)) {
59
+ const problems = [];
60
+ for (const [file, hash] of Object.entries(locked ?? {})) {
61
+ try {
62
+ if (hashFile(worktree, file) !== hash) problems.push(`locked test changed: ${file}`);
63
+ } catch { problems.push(`locked test missing or unsafe: ${file}`); }
64
+ }
65
+ return { problems };
66
+ }
67
+
68
+ /** Counts only added registration lines, using the final tree rather than summing Git layers. */
69
+ export function addedTestCases(worktree, base) {
70
+ const boundary = base || git(worktree, "hash-object", "-w", "-t", "tree", "--stdin").trim();
71
+ const tracked = names(git(worktree, "diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-only", "-z", boundary, "--"));
72
+ const untracked = names(git(worktree, "ls-files", "--others", "--exclude-standard", "-z"));
73
+ const cases = [];
74
+ for (const file of new Set([...tracked, ...untracked])) {
75
+ if (!testFile(file) || !existsSync(path.join(worktree, file))) continue;
76
+ const text = untracked.includes(file) ? readFileSync(safeFile(worktree, file), "utf8") : git(worktree, "diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--unified=0", boundary, "--", file).split("\n").filter((line) => line.startsWith("+") && !line.startsWith("+++")).map((line) => line.slice(1)).join("\n");
77
+ for (const line of text.split(/\r?\n/)) {
78
+ if (!registration.test(line)) continue;
79
+ const name = /\(\s*(['"`])(.*?)\1/.exec(line)?.[2] ?? line.trim();
80
+ cases.push({ path: normalize(file), name });
81
+ }
82
+ }
83
+ return cases;
84
+ }
85
+
86
+ /** Runs literal argv through the shared Windows shim resolver. */
87
+ export function runTestCommand(command, cwd) {
88
+ return new Promise((resolve, reject) => {
89
+ let child;
90
+ const env = { ...process.env };
91
+ delete env.NODE_TEST_CONTEXT;
92
+ try { child = spawnCommand(command[0], command.slice(1), { cwd, env, stdio: "inherit", windowsHide: true }); }
93
+ catch (error) { reject(error); return; }
94
+ child.once("error", reject);
95
+ child.once("close", (status) => resolve(status ?? 1));
96
+ });
97
+ }
98
+
99
+ /** Each new test file must be red on the frozen merge base; every nonzero status is red. */
100
+ export async function verifyBaseTests(worktree, base, cases, command = ["node", "--test"]) {
101
+ const problems = [];
102
+ if (!cases.length) return { problems };
103
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-base-tests-"));
104
+ const checkout = path.join(root, "base");
105
+ try {
106
+ git(worktree, "worktree", "add", "--detach", checkout, base);
107
+ const baseRoot = realpathSync(checkout);
108
+ // Validate all existing parents before creating any destination directories.
109
+ const targets = [...new Set(cases.map((entry) => entry.path))].map((file) => {
110
+ const source = safeFile(worktree, file);
111
+ const destination = path.resolve(checkout, file);
112
+ for (let parent = path.dirname(destination); parent !== checkout; parent = path.dirname(parent)) {
113
+ if (!lstatSync(parent, { throwIfNoEntry: false })) continue;
114
+ const relative = path.relative(baseRoot, realpathSync(parent));
115
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw new Error(`unsafe base test path: ${file}`);
116
+ }
117
+ if (lstatSync(destination, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error(`unsafe base test path: ${file}`);
118
+ return { file, source, destination };
119
+ });
120
+ for (const { source, destination } of targets) {
121
+ mkdirSync(path.dirname(destination), { recursive: true });
122
+ copyFileSync(source, destination);
123
+ }
124
+ for (const { file, destination } of targets) {
125
+ if (await runTestCommand([...command, destination], checkout) === 0) {
126
+ problems.push(`${file}: passes on the base: ${cases.filter((entry) => entry.path === file).map((entry) => entry.name).join(", ")}`);
127
+ }
128
+ }
129
+ return { problems };
130
+ } finally {
131
+ try { git(worktree, "worktree", "remove", "--force", checkout); }
132
+ finally { rmSync(root, cleanup); }
133
+ }
134
+ }