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
@@ -1,8 +1,43 @@
1
1
  import { strict as assert } from "node:assert";
2
+ import { spawnSync } from "node:child_process";
2
3
  import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { test } from "node:test";
5
- import { expandHome, runGh } from "./gh-run.mjs";
6
+ import { copyFileSync, mkdtempSync, rmSync } from "node:fs";
7
+ import { expandHome, parseApiList, parsePages, runGh, runGhResult } from "./gh-run.mjs";
8
+
9
+ test("parsePages reads two array pages printed back to back", () => {
10
+ const first = [{ body: 'braces } [ and "quoted"', path: "a\\b" }];
11
+ assert.deepEqual(parsePages(`${JSON.stringify(first)}\n[2]`), [first, [2]]);
12
+ });
13
+
14
+ test("parsePages reads two object pages printed back to back", () => {
15
+ assert.deepEqual(parsePages('{"check_runs":[1]}{"check_runs":[2]}'), [{ check_runs: [1] }, { check_runs: [2] }]);
16
+ });
17
+
18
+ test("parsePages returns null for a torn page", () => {
19
+ for (const text of [null, "", " ", "not JSON", '[1]\n[{"body":"unfinished', "[1]{}junk", "[1,]", "{]"]) {
20
+ assert.equal(parsePages(text), null);
21
+ }
22
+ });
23
+
24
+ test("runGh captures a failed-run log larger than one MB", () => {
25
+ const cwd = mkdtempSync(path.join(os.tmpdir(), "qc-gh-large-"));
26
+ try {
27
+ copyFileSync(process.execPath, path.join(cwd, process.platform === "win32" ? "gh.exe" : "gh"));
28
+ const result = runGhResult(["-e", "process.stdout.write('x'.repeat(2 * 1024 * 1024))"], { cwd, env: { PATH: cwd } });
29
+ assert.equal(result.status, 0);
30
+ assert.equal(result.stdout.length, 2 * 1024 * 1024);
31
+ } finally {
32
+ rmSync(cwd, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
33
+ }
34
+ });
35
+
36
+ test("parseApiList combines every page and rejects incomplete or malformed pages", () => {
37
+ assert.deepEqual(parseApiList('{"check_runs":[1]}\n{"check_runs":[2]}', "check_runs"), [1, 2]);
38
+ assert.deepEqual(parseApiList('{"workflow_runs":[]}', "workflow_runs"), []);
39
+ for (const text of [null, "not JSON", "{}", '{"check_runs":[]}\n{}']) assert.equal(parseApiList(text, "check_runs"), null);
40
+ });
6
41
 
7
42
  test("expandHome expands a leading ~ the way the shell would, and leaves every other value", () => {
8
43
  assert.deepEqual(expandHome({ GH_CONFIG_DIR: "~/.config/gh-personal", GH_HOST: "ghe.example.com" }), {
@@ -20,3 +55,33 @@ test("expandHome expands a leading ~ the way the shell would, and leaves every o
20
55
  test("runGh answers null when gh fails or is missing", () => {
21
56
  assert.equal(runGh(["no-such-command-for-qc"]), null);
22
57
  });
58
+
59
+ test("runGhResult returns stdout and stderr with the exit status", (t) => {
60
+ const success = runGhResult(["--version"]);
61
+ if (success.error?.code === "ENOENT") return t.skip("gh is not on PATH");
62
+ assert.equal(success.status, 0);
63
+ assert.match(success.stdout, /gh version/);
64
+ assert.equal(success.stderr, "");
65
+ const failure = runGhResult(["no-such-command-for-qc"]);
66
+ assert.notEqual(failure.status, 0);
67
+ assert.match(failure.stderr, /unknown command/);
68
+ });
69
+
70
+ test("runGhResult preserves spawn errors", () => {
71
+ const result = runGhResult(["--version"], { cwd: path.join(os.tmpdir(), "qc-gh-missing", "missing") });
72
+ assert.equal(result.status, null);
73
+ assert.equal(result.error.code, "ENOENT");
74
+ });
75
+
76
+ test("the real gh test skips with a reason when gh is absent from PATH", () => {
77
+ const cwd = mkdtempSync(path.join(os.tmpdir(), "qc-gh-absent-"));
78
+ try {
79
+ const result = spawnSync(process.execPath, ["--test", "--test-reporter=tap", "--test-name-pattern=^runGhResult returns stdout", import.meta.filename], {
80
+ encoding: "utf8", env: { ...process.env, PATH: cwd, NODE_TEST_CONTEXT: undefined },
81
+ });
82
+ assert.equal(result.status, 0, result.stdout + result.stderr);
83
+ assert.match(result.stdout, /# SKIP gh is not on PATH/);
84
+ } finally {
85
+ rmSync(cwd, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
86
+ }
87
+ });
@@ -1,6 +1,6 @@
1
1
  import { strict as assert } from "node:assert";
2
- import { execFileSync } from "node:child_process";
3
- import { copyFileSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { test } from "node:test";
@@ -11,6 +11,28 @@ import { hookDrift } from "./git-hooks.mjs";
11
11
  const TEMPLATES = fileURLToPath(new URL("../../templates/githooks/", import.meta.url));
12
12
  const REQUIRED = { "pre-commit": ["qc work-order-check"], "pre-push": ["qc check"] };
13
13
 
14
+ test("pre-push reruns each pushed branch before qc check and stops on failure", (t) => {
15
+ const r = repo(t);
16
+ const script = readFileSync(path.join(TEMPLATES, "pre-push"), "utf8");
17
+ const bin = path.join(r.root, "bin");
18
+ mkdirSync(bin);
19
+ writeFileSync(path.join(bin, "npx"), '#!/bin/sh\necho "$*" >> "$CI_CALLS"\ncase "$*" in *ci-failures*) exit "${CI_RERUN_STATUS:-0}";; esac\n', { mode: 0o755 });
20
+ const hook = path.join(r.root, "pre-push");
21
+ writeFileSync(hook, script);
22
+ const bash = process.platform === "win32" ? "C:/Program Files/Git/bin/bash.exe" : "bash";
23
+ const calls = path.join(r.root, "calls.txt");
24
+ const env = { ...process.env, PATH: `${bin}${path.delimiter}${process.env.PATH}`, CI_CALLS: calls, CI_RERUN_STATUS: "9" };
25
+ const input = `refs/heads/feat/ci ${"a".repeat(40)} refs/heads/feat/ci ${"0".repeat(40)}\n`;
26
+ const failed = spawnSync(bash, [hook], { cwd: r.root, env, input, encoding: "utf8" });
27
+ assert.equal(failed.status, 9, failed.stderr);
28
+ assert.match(readFileSync(calls, "utf8"), /qc ci-failures --rerun --branch feat\/ci/);
29
+ assert.doesNotMatch(readFileSync(calls, "utf8"), /qc check/);
30
+ writeFileSync(calls, "");
31
+ const passed = spawnSync(bash, [hook], { cwd: r.root, env: { ...env, CI_RERUN_STATUS: "0" }, input, encoding: "utf8" });
32
+ assert.equal(passed.status, 0, passed.stderr);
33
+ assert.match(readFileSync(calls, "utf8"), /ci-failures[\s\S]*qc check/);
34
+ });
35
+
14
36
  function repo(t) {
15
37
  const root = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-git-hooks-")));
16
38
  t.after(() => rmSync(root, { recursive: true, force: true }));
@@ -37,7 +59,7 @@ test("the kit's template hooks, installed through core.hooksPath, carry every re
37
59
  assert.deepEqual(hookDrift(r.root, REQUIRED).problems, []);
38
60
  });
39
61
 
40
- test("a pre-commit that never calls qc work-order-check fails, as quality-control-mono's did", (t) => {
62
+ test("a pre-commit that never calls qc work-order-check fails, as example-app's did", (t) => {
41
63
  const r = repo(t);
42
64
  r.hook(".githooks", "pre-commit", "#!/usr/bin/env bash\nset -euo pipefail\nnpx eslint $STAGED --max-warnings 0\n");
43
65
  r.hook(".githooks", "pre-push", "#!/usr/bin/env bash\nnpx qc check\n");
@@ -20,7 +20,8 @@ export function gitOutWithin(timeoutMs, cwd, ...args) {
20
20
  */
21
21
  export function gitStatusWithin(timeoutMs, cwd, ...args) {
22
22
  const env = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
23
- const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, timeout: timeoutMs, env });
23
+ // A diff against an old base can pass the 1 MB default buffer.
24
+ const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, timeout: timeoutMs, env, maxBuffer: 1 << 26 });
24
25
  if (result.error) return { error: result.error.code === "ETIMEDOUT" ? `git timed out after ${timeoutMs} ms` : result.error.message };
25
26
  if (result.signal) return { error: `git ended on ${result.signal}` };
26
27
  return { status: result.status, stdout: (result.stdout ?? "").trim() };
@@ -0,0 +1,47 @@
1
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+ import { globMatcher } from "../glob.mjs";
5
+ import { posixDir, renumber } from "./migrations.mjs";
6
+
7
+ /** Replay each unreviewed merge from its parents, using the integration transformations only. */
8
+ export function checkMergeTrees(root, commits, config, git) {
9
+ if (!commits.length) return null;
10
+ const scratch = mkdtempSync(path.join(tmpdir(), "qc-merge-tree-"));
11
+ const read = (cwd, ...args) => {
12
+ const out = git(cwd, ...args);
13
+ if (out === null) throw new Error("cannot reconstruct the expected merge tree within the lane budget");
14
+ return out;
15
+ };
16
+ const options = ["-c", "rerere.enabled=false", "-c", "user.name=qc", "-c", "user.email=qc@localhost"];
17
+ const replay = (...args) => read(scratch, ...options, ...args);
18
+ try {
19
+ const objects = path.resolve(root, read(root, "rev-parse", "--git-path", "objects"));
20
+ const objectFormat = read(root, "rev-parse", "--show-object-format");
21
+ read(scratch, "init", "-q", "--template=", `--object-format=${objectFormat}`);
22
+ mkdirSync(path.join(scratch, ".git", "objects", "info"), { recursive: true });
23
+ writeFileSync(path.join(scratch, ".git", "objects", "info", "alternates"), `${objects}\n`);
24
+ const generated = globMatcher(config.generated?.globs ?? []);
25
+ for (const commit of commits) {
26
+ const parents = read(root, "show", "-s", "--format=%P", commit).split(" ");
27
+ if (parents.length !== 2) return `merge ${commit} is not a two-parent merge`;
28
+ replay("reset", "--hard", parents[0]);
29
+ const merged = git(scratch, ...options, "merge", "--no-ff", "--no-commit", parents[1]);
30
+ if (merged === null) {
31
+ const conflicts = read(scratch, "diff", "--name-only", "--diff-filter=U").split("\n").filter(Boolean);
32
+ if (!conflicts.length || conflicts.some((file) => !generated(file))) return `merge ${commit} cannot be reconstructed without hand-resolved changes`;
33
+ replay("checkout", "--ours", "--", ...conflicts);
34
+ replay("add", "--", ...conflicts);
35
+ }
36
+ const dir = posixDir(config.paths?.migrations);
37
+ if (dir) renumber(scratch, dir, { onto: parents[0], branch: parents[1] });
38
+ const expected = replay("write-tree");
39
+ if (expected !== read(root, "rev-parse", `${commit}^{tree}`)) return `merge ${commit} was hand-resolved after review: differs from the expected merge tree`;
40
+ }
41
+ return null;
42
+ } catch (error) {
43
+ return error.message;
44
+ } finally {
45
+ rmSync(scratch, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
46
+ }
47
+ }
@@ -1,33 +1,41 @@
1
- // `qc integrate`: one integration branch for a batch of branches, so the batch runs one CI and merges once.
1
+ // `qc integrate`: one integration branch for a batch of branches, with pushes at the configured CI cadence.
2
2
  // Each merge renumbers its migrations, and a conflict in generated files is settled by the generator.
3
3
 
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { parseArgs } from "node:util";
6
6
  import { globMatcher } from "../glob.mjs";
7
+ import { runGh } from "./gh-run.mjs";
8
+ import { postBody, redactOutput } from "./output-redaction.mjs";
9
+ import { pauseRefusal } from "./pause.mjs";
7
10
  import { posixDir, renumber } from "./migrations.mjs";
8
11
 
9
12
  export const USAGE = `qc integrate — one integration branch for a batch of branches
10
13
 
11
- qc integrate --issue <n> [--type <type>] [--slug <slug>] [--from <ref>] <branch>...
14
+ qc integrate --issue <n> [--type <type>] [--slug <slug>] [--from <ref>] [--pr] <branch>...
12
15
  make <type>/<n>-<slug> from <ref> (worktree.base by default), or continue it when it exists;
13
16
  merge each branch in order, renumber its migrations after the last one before it, and commit;
14
- then run generated.command and commit what it changes. A conflict stops the run and lists the
15
- files. Resolve it, commit, and run the same command again: a branch already merged is skipped.`;
17
+ run generated.command, commit its output, and push to origin every integrate.ciEvery merges
18
+ (3 by default), then settle and push any remaining changes. Set integrate.push to false for
19
+ manual pushes. An absent origin skips pushes. A conflict stops the run and lists the files.
20
+ Resolve it, commit, and run the same command again: a branch already merged is skipped.
21
+ --pr opens a draft pull request after the first push; it requires pushes and an origin remote.
22
+ It refuses each branch with an author email other than the effective Git author email.
23
+ It returns exit 5 when an operator pause blocks integration.`;
16
24
 
17
- function tryGit(cwd, args) {
25
+ export function tryGit(cwd, args) {
18
26
  const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true });
19
27
  return { ok: result.status === 0, out: result.stdout ?? "", err: (result.stderr ?? "").trim() };
20
28
  }
21
29
 
22
- function git(cwd, args) {
30
+ export function git(cwd, args) {
23
31
  const result = tryGit(cwd, args);
24
32
  if (!result.ok) throw new Error(`git ${args.join(" ")}: ${result.err || "failed"}`);
25
33
  return result.out;
26
34
  }
27
35
 
28
- const lines = (text) => text.split(/\r?\n/).filter(Boolean);
36
+ export const lines = (text) => text.split(/\r?\n/).filter(Boolean);
29
37
 
30
- function runShell(command, cwd) {
38
+ export function runShell(command, cwd) {
31
39
  return spawnSync(command, { cwd, shell: true, stdio: "inherit", windowsHide: true }).status ?? 1;
32
40
  }
33
41
 
@@ -42,7 +50,7 @@ export function integrationBranch({ issue, type = "feat", slug = "integration" }
42
50
  function parse(argv) {
43
51
  const { values, positionals } = parseArgs({
44
52
  args: argv,
45
- options: { issue: { type: "string" }, type: { type: "string" }, slug: { type: "string" }, from: { type: "string" } },
53
+ options: { issue: { type: "string" }, type: { type: "string" }, slug: { type: "string" }, from: { type: "string" }, pr: { type: "boolean" } },
46
54
  allowPositionals: true,
47
55
  strict: true,
48
56
  });
@@ -58,8 +66,63 @@ const conflictReport = (branch, files) =>
58
66
  "Resolve them, run `qc migrations renumber --onto HEAD --branch MERGE_HEAD`, commit, and run qc integrate again.",
59
67
  ].join("\n");
60
68
 
69
+ /** Branch: derive the pull request base from a local or remote branch ref. */
70
+ function pullRequestBase(root, ref) {
71
+ if (typeof ref === "string") {
72
+ const local = ref.replace(/^refs\/heads\//, "");
73
+ if (tryGit(root, ["show-ref", "--verify", "--quiet", `refs/heads/${local}`]).ok) return local;
74
+ const remoteRef = ref.replace(/^refs\/remotes\//, "");
75
+ const remote = lines(git(root, ["remote"])).find((name) => remoteRef.startsWith(`${name}/`));
76
+ if (remote && tryGit(root, ["show-ref", "--verify", "--quiet", `refs/remotes/${remoteRef}`]).ok) {
77
+ const branch = remoteRef.slice(remote.length + 1);
78
+ if (tryGit(root, ["check-ref-format", "--branch", branch]).ok) return branch;
79
+ }
80
+ }
81
+ throw new Error(`the pull request base must name a branch, got ${JSON.stringify(ref)}`);
82
+ }
83
+
84
+ /** Branch: read a Git identity and require its email. */
85
+ export function identityEmail(root, role) {
86
+ const variable = `GIT_${role.toUpperCase()}_IDENT`;
87
+ const identity = git(root, ["var", variable]).trim();
88
+ const email = /<([^<>]+)> \d+ [+-]\d{4}$/.exec(identity)?.[1];
89
+ if (!email) throw new Error(`git var ${variable} returned no ${role} email`);
90
+ return email;
91
+ }
92
+
93
+ /** Merge one branch without pushing or regenerating; leave conflicts for the caller to handle. */
94
+ export function mergeStep(config, branch, { base, email = identityEmail(config.root, "author"), say = () => {} } = {}) {
95
+ const root = config.root;
96
+ const dir = posixDir(config.paths?.migrations);
97
+ const generated = globMatcher(config.generated?.globs ?? []);
98
+ const others = [...new Set(lines(git(root, ["log", "--format=%ae", `${base}..${branch}`, "--"])))].filter((author) => author !== email);
99
+ if (others.length > 0) throw new Error(`refuse branch ${branch}: authors differ from effective Git author email ${email}: ${others.join(", ")}`);
100
+ if (tryGit(root, ["merge-base", "--is-ancestor", branch, "HEAD"]).ok) {
101
+ say(`skip ${branch}: already merged`);
102
+ return { skipped: true };
103
+ }
104
+ const merged = tryGit(root, ["merge", "--no-ff", "--no-commit", branch]);
105
+ if (!merged.ok) {
106
+ const conflicts = lines(git(root, ["diff", "--name-only", "--diff-filter=U"]));
107
+ if (conflicts.length === 0) throw new Error(`git merge ${branch}: ${merged.err}`);
108
+ const byHand = conflicts.filter((file) => !generated(file));
109
+ if (byHand.length > 0) {
110
+ say(conflictReport(branch, byHand));
111
+ return { conflict: byHand };
112
+ }
113
+ git(root, ["checkout", "--ours", "--", ...conflicts]);
114
+ git(root, ["add", "--", ...conflicts]);
115
+ }
116
+ if (dir) {
117
+ for (const { from, to } of renumber(root, dir, { onto: "HEAD", branch: "MERGE_HEAD" }).plan) say(`rename ${dir}/${from} -> ${to}`);
118
+ }
119
+ git(root, ["commit", "-q", "--no-edit"]);
120
+ say(`merge ${branch}`);
121
+ return { merged: true };
122
+ }
123
+
61
124
  /** `qc integrate`. @returns the exit code */
62
- export async function runIntegrate(config, argv, { say = (line) => console.log(line), run = runShell } = {}) {
125
+ export async function runIntegrate(config, argv, { say = (line) => console.log(line), run = runShell, gh = runGh } = {}) {
63
126
  let options;
64
127
  try {
65
128
  options = parse(argv);
@@ -69,51 +132,91 @@ export async function runIntegrate(config, argv, { say = (line) => console.log(l
69
132
  }
70
133
  const root = config.root;
71
134
  try {
135
+ const refusal = pauseRefusal(root);
136
+ if (refusal) {
137
+ say(`qc integrate: ${refusal}`);
138
+ return 5;
139
+ }
72
140
  const name = integrationBranch(options);
73
141
  const pattern = config.branches?.pattern;
74
142
  if (pattern && !new RegExp(pattern).test(name)) throw new Error(`${name} does not match branches.pattern ${pattern}`);
143
+ const canPush = config.integrate?.push !== false && tryGit(root, ["remote", "get-url", "origin"]).ok;
144
+ if (options.pr && !canPush) throw new Error("a pull request needs a pushed branch: enable integrate.push and configure origin");
75
145
  if (tryGit(root, ["rev-parse", "-q", "--verify", "MERGE_HEAD"]).ok) throw new Error("a merge is in progress: resolve it, commit it, then run qc integrate again");
76
146
  if (git(root, ["status", "--porcelain"]).trim() !== "") throw new Error("the working tree has changes: commit or stash them first");
147
+ const email = identityEmail(root, "author");
148
+ identityEmail(root, "committer");
77
149
  tryGit(root, ["fetch", "--quiet", "origin"]);
150
+ const base = options.from ?? config.worktree?.base ?? "origin/main";
151
+ const prBase = options.pr
152
+ ? pullRequestBase(root, options.from && /^[0-9a-f]{7,64}$/i.test(options.from) ? config.integrate?.base ?? "main" : base)
153
+ : null;
78
154
  if (git(root, ["branch", "--show-current"]).trim() !== name) {
79
155
  if (tryGit(root, ["rev-parse", "-q", "--verify", `refs/heads/${name}`]).ok) git(root, ["switch", "-q", name]);
80
- else git(root, ["switch", "-q", "-c", name, options.from ?? config.worktree?.base ?? "origin/main"]);
156
+ else git(root, ["switch", "-q", "-c", name, base]);
81
157
  }
82
- const dir = posixDir(config.paths?.migrations);
83
- const generated = globMatcher(config.generated?.globs ?? []);
84
- for (const branch of options.branches) {
85
- if (tryGit(root, ["merge-base", "--is-ancestor", branch, "HEAD"]).ok) {
86
- say(`skip ${branch}: already merged`);
87
- continue;
158
+ const ciEvery = config.integrate?.ciEvery ?? 3;
159
+ let merges = 0;
160
+ let pushed = false;
161
+ let opened = false;
162
+
163
+ /** Pipeline: ensure the published integration branch has a pull request. */
164
+ function ensurePullRequest() {
165
+ if (!options.pr || opened) return;
166
+ if (gh(["pr", "view", name, "--json", "number"], { cwd: root }) !== null) {
167
+ say("pr exists");
168
+ } else {
169
+ const result = gh([
170
+ "pr", "create", "--draft", "--head", name, "--base", prBase,
171
+ "--title", redactOutput(`${options.type ?? "feat"}: integrate the batch for #${options.issue}`),
172
+ "--body", postBody(`Refs #${options.issue}`, config),
173
+ ], { cwd: root });
174
+ if (result === null) throw new Error("gh pr create failed");
175
+ say(`pr ${result.trim()}`);
88
176
  }
89
- const merged = tryGit(root, ["merge", "--no-ff", "--no-commit", branch]);
90
- if (!merged.ok) {
91
- const conflicts = lines(git(root, ["diff", "--name-only", "--diff-filter=U"]));
92
- if (conflicts.length === 0) throw new Error(`git merge ${branch}: ${merged.err}`);
93
- const byHand = conflicts.filter((file) => !generated(file));
94
- if (byHand.length > 0) {
95
- say(conflictReport(branch, byHand));
96
- return 1;
177
+ opened = true;
178
+ }
179
+
180
+ /** Pipeline: regenerate and commit the integration branch before a push. */
181
+ function settle() {
182
+ const command = config.generated?.command;
183
+ if (command) {
184
+ if (run(command, root) !== 0) throw new Error(`${command} failed; fix it, commit, and run qc integrate again`);
185
+ if (git(root, ["status", "--porcelain"]).trim() !== "") {
186
+ git(root, ["add", "-A"]);
187
+ git(root, ["commit", "-q", "-m", "chore: regenerate the generated files", "-m", `Refs #${options.issue}`]);
188
+ say(`commit the output of ${command}`);
97
189
  }
98
- git(root, ["checkout", "--ours", "--", ...conflicts]);
99
- git(root, ["add", "--", ...conflicts]);
100
190
  }
101
- if (dir) {
102
- for (const { from, to } of renumber(root, dir, { onto: "HEAD", branch: "MERGE_HEAD" }).plan) say(`rename ${dir}/${from} -> ${to}`);
103
- }
104
- git(root, ["commit", "-q", "--no-edit"]);
105
- say(`merge ${branch}`);
106
191
  }
107
- const command = config.generated?.command;
108
- if (command) {
109
- if (run(command, root) !== 0) throw new Error(`${command} failed; fix it, commit, and run qc integrate again`);
110
- if (git(root, ["status", "--porcelain"]).trim() !== "") {
111
- git(root, ["add", "-A"]);
112
- git(root, ["commit", "-q", "-m", "chore: regenerate the generated files", "-m", `Refs #${options.issue}`]);
113
- say(`commit the output of ${command}`);
192
+
193
+ /** Branch: publish the integration branch when its remote tracking ref differs. */
194
+ function pushIfAhead() {
195
+ if (!canPush) return;
196
+ const remote = tryGit(root, ["rev-parse", "--verify", `refs/remotes/origin/${name}`]);
197
+ if (git(root, ["rev-parse", "HEAD"]).trim() === remote.out.trim()) return;
198
+ git(root, ["push", "-u", "origin", name]);
199
+ say(`push ${name}`);
200
+ pushed = true;
201
+ ensurePullRequest();
202
+ }
203
+
204
+ for (const branch of options.branches) {
205
+ const result = mergeStep(config, branch, { base, email, say });
206
+ if (result.conflict) return 1;
207
+ if (result.skipped) continue;
208
+ merges += 1;
209
+ if (merges === ciEvery) {
210
+ settle();
211
+ pushIfAhead();
212
+ merges = 0;
114
213
  }
115
214
  }
116
- say(`OK ${name} holds ${options.branches.length} branch(es). Push it: git push -u origin ${name}`);
215
+ settle();
216
+ pushIfAhead();
217
+ if (options.pr && tryGit(root, ["rev-parse", "--verify", `refs/remotes/origin/${name}`]).ok) ensurePullRequest();
218
+ const hint = pushed ? "" : ` Push it: git push -u origin ${name}`;
219
+ say(`OK ${name} holds ${options.branches.length} branch(es).${hint}`);
117
220
  return 0;
118
221
  } catch (error) {
119
222
  console.error(`qc integrate: ${error.message}`);