architecture-harness 0.23.0 → 0.25.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 (71) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +20 -5
  3. package/src/cli/bash-command-guard.mjs +44 -5
  4. package/src/cli/bash-command-guard.test.mjs +35 -1
  5. package/src/cli/budget-guard.mjs +1 -0
  6. package/src/cli/budget-guard.test.mjs +7 -1
  7. package/src/cli/budget.mjs +3 -4
  8. package/src/cli/budget.test.mjs +5 -5
  9. package/src/cli/check-commands.mjs +82 -0
  10. package/src/cli/check-commands.test.mjs +190 -0
  11. package/src/cli/check.mjs +34 -13
  12. package/src/cli/ci-template.test.mjs +17 -15
  13. package/src/cli/cli.test.mjs +33 -2
  14. package/src/cli/commit-msg.mjs +12 -12
  15. package/src/cli/commit-msg.test.mjs +22 -7
  16. package/src/cli/generated-file-guard.mjs +11 -2
  17. package/src/cli/generated-file-guard.test.mjs +14 -2
  18. package/src/cli/init.mjs +70 -25
  19. package/src/cli/lint-changed.mjs +157 -0
  20. package/src/cli/lint-changed.test.mjs +102 -0
  21. package/src/cli/plugin-agents.test.mjs +1 -1
  22. package/src/cli/post-edit-gate.test.mjs +12 -3
  23. package/src/cli/pr-check.mjs +15 -2
  24. package/src/cli/pr-check.test.mjs +19 -9
  25. package/src/cli/qc.mjs +38 -7
  26. package/src/cli/scaffold.mjs +23 -2
  27. package/src/cli/scaffold.test.mjs +51 -0
  28. package/src/cli/shell-command.mjs +3 -1
  29. package/src/cli/stop-gate.test.mjs +49 -128
  30. package/src/cli/typecheck.mjs +46 -0
  31. package/src/cli/typecheck.test.mjs +43 -0
  32. package/src/cli/user-config-package.mjs +16 -0
  33. package/src/cli/user-config-toml.mjs +144 -0
  34. package/src/cli/user-config.mjs +155 -0
  35. package/src/cli/user-config.test.mjs +274 -0
  36. package/src/cli/work-order-guard.mjs +2 -2
  37. package/src/cli/worktree-gate.mjs +11 -12
  38. package/src/cli/worktree-gate.test.mjs +28 -29
  39. package/src/cli/worktree-isolation.mjs +3 -3
  40. package/src/cli/worktree-isolation.test.mjs +1 -1
  41. package/src/cli/worktree.mjs +9 -1
  42. package/src/cli/worktree.test.mjs +16 -1
  43. package/src/config.mjs +28 -11
  44. package/src/config.test.mjs +33 -1
  45. package/src/eslint/preset.mjs +8 -3
  46. package/src/eslint/preset.test.mjs +15 -8
  47. package/src/eslint/rules/no-raw-fetch.mjs +42 -2
  48. package/src/eslint/rules.test.mjs +15 -0
  49. package/src/gates/audit-append-only.mjs +18 -4
  50. package/src/gates/audit-append-only.test.mjs +19 -0
  51. package/src/gates/tenant-predicate.mjs +147 -7
  52. package/src/gates/tenant-predicate.test.mjs +55 -0
  53. package/src/gates/tenant-tables.mjs +5 -2
  54. package/src/gates/tenant-tables.test.mjs +8 -0
  55. package/src/gates/threshold-ratchet.mjs +12 -9
  56. package/src/gates/threshold-ratchet.test.mjs +16 -0
  57. package/src/plugin.test.mjs +28 -0
  58. package/src/screens/auth-run.test.mjs +20 -17
  59. package/src/screens/capture-idle.test.mjs +2 -1
  60. package/src/screens/catalog.test.mjs +3 -3
  61. package/src/screens/chrome.mjs +21 -0
  62. package/src/vale-style.test.mjs +5 -5
  63. package/templates/CLAUDE.md +2 -2
  64. package/templates/githooks/pre-commit +7 -10
  65. package/templates/github/workflows/ci.yml +25 -84
  66. package/templates/github/workflows/pr-policy.yml +36 -0
  67. package/user-config/claude/settings.shared.json +74 -0
  68. package/user-config/claude/statusline.js +323 -0
  69. package/user-config/codex/config.shared.toml +19 -0
  70. package/src/cli/edit-batch-guard.mjs +0 -77
  71. package/src/cli/edit-batch-guard.test.mjs +0 -131
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 shawrylk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -47,9 +47,11 @@
47
47
  "files": [
48
48
  "src",
49
49
  "templates",
50
+ "user-config",
50
51
  "README.md"
51
52
  ],
52
53
  "scripts": {
54
+ "prepack": "node src/cli/user-config-package.mjs",
53
55
  "test": "node src/eslint/rules.test.mjs && node --test \"src/**/*.test.mjs\"",
54
56
  "test:browser": "node --test \"src/**/*.browser-test.mjs\""
55
57
  },
@@ -62,7 +64,10 @@
62
64
  "@commitlint/lint": ">=19",
63
65
  "@commitlint/config-conventional": ">=19",
64
66
  "yaml": ">=2",
65
- "typescript": ">=5"
67
+ "typescript": ">=5",
68
+ "pixelmatch": ">=8",
69
+ "playwright": ">=1.64",
70
+ "pngjs": ">=7"
66
71
  },
67
72
  "peerDependenciesMeta": {
68
73
  "@typescript-eslint/eslint-plugin": {
@@ -88,6 +93,15 @@
88
93
  },
89
94
  "typescript": {
90
95
  "optional": true
96
+ },
97
+ "pixelmatch": {
98
+ "optional": true
99
+ },
100
+ "playwright": {
101
+ "optional": true
102
+ },
103
+ "pngjs": {
104
+ "optional": true
91
105
  }
92
106
  },
93
107
  "devDependencies": {
@@ -98,12 +112,13 @@
98
112
  "eslint": "^9",
99
113
  "eslint-plugin-boundaries": "^5",
100
114
  "eslint-plugin-sonarjs": "^3",
115
+ "pixelmatch": "^8.0.0",
116
+ "playwright": "^1.64.1",
117
+ "pngjs": "^7.0.0",
101
118
  "typescript": "^5",
102
119
  "yaml": "^2.9.1"
103
120
  },
104
121
  "dependencies": {
105
- "pixelmatch": "^8.0.0",
106
- "playwright": "^1.64.1",
107
- "pngjs": "^7.0.0"
122
+ "cross-spawn": "7.0.6"
108
123
  }
109
124
  }
@@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url";
9
9
  import { CONFIG_FILE } from "../config.mjs";
10
10
  import { checkoutRootOf } from "./checkout-root.mjs";
11
11
  import { locationTarget, powershellSegments } from "./powershell-command.mjs";
12
- import { cdTarget, commandWords, gitCall, segmentsOf } from "./shell-command.mjs";
12
+ import { cdTarget, commandEnv, commandWords, gitCall, segmentsOf } from "./shell-command.mjs";
13
13
  import { nativePath } from "./workflow-place.mjs";
14
14
  import { keyOf } from "./worktree.mjs";
15
15
  import { worktreeRuleAt } from "./worktree-settings.mjs";
@@ -54,9 +54,12 @@ const WORKTREE_ADD = /\bworktree\s+add\b/i;
54
54
  const EXPLICIT_DIR = /--git-dir|--work-tree|GIT_DIR|GIT_COMMON_DIR|GIT_WORK_TREE|core\.worktree|core\.bare/i;
55
55
  const isNoVerify = (arg) => arg.length >= NO_VERIFY_MIN && NO_VERIFY.startsWith(arg);
56
56
 
57
- /** True when a commit or push names `--no-verify`, or a commit names `-n` alone or in a flag cluster. */
57
+ /** The subcommands whose `--no-verify` skips a hook. Only `commit` also reads `-n` as it: `merge` and `rebase` read it as `--no-stat`. */
58
+ const SKIPS_WITH_NO_VERIFY = new Set(["commit", "push", "merge", "rebase", "am"]);
59
+
60
+ /** True when a commit, push, merge, rebase or am names `--no-verify`, or a commit names `-n` alone or in a flag cluster. */
58
61
  function skipsHooks({ sub, args }) {
59
- if (sub !== "commit" && sub !== "push") return false;
62
+ if (!SKIPS_WITH_NO_VERIFY.has(sub)) return false;
60
63
  for (let i = 0; i < args.length; i++) {
61
64
  const arg = args[i];
62
65
  if (arg === "--") return false;
@@ -76,7 +79,41 @@ function skipsHooks({ sub, args }) {
76
79
  return false;
77
80
  }
78
81
 
79
- const setsHooksPath = ({ configs }) => configs.some((setting) => /^core\.hookspath=/i.test(setting ?? ""));
82
+ /** The `git config` words that write or remove a setting, whatever follows the key. */
83
+ const CONFIG_WRITES = new Set(["--add", "--replace-all", "--unset", "--unset-all", "set", "unset"]);
84
+ /** The `git config` words that only read, so a word after the key is a pattern or a default, never a value. */
85
+ const CONFIG_READS = new Set(["--get", "--get-all", "--get-regexp", "--list", "-l", "get", "list"]);
86
+
87
+ /** True when `git config` writes or removes `core.hooksPath`. A bare key, as in `git config core.hooksPath`, only reads it. */
88
+ function configWritesHooksPath(args) {
89
+ const key = args.findIndex((arg) => /^core\.hookspath$/i.test(arg));
90
+ if (key < 0) return false;
91
+ if (args.some((arg) => CONFIG_WRITES.has(arg))) return true;
92
+ if (args.some((arg) => CONFIG_READS.has(arg))) return false;
93
+ return args.slice(key + 1).some((arg) => !arg.startsWith("-"));
94
+ }
95
+
96
+ /** True when the call sets `core.hooksPath` for itself with `-c`, or writes or removes it with `git config`. */
97
+ const setsHooksPath = ({ sub, configs, args }) =>
98
+ configs.some((setting) => /^core\.hookspath=/i.test(setting ?? "")) || (sub === "config" && configWritesHooksPath(args));
99
+
100
+ /** Git reads settings from these variables, so one that names `core.hooksPath` points git away from the hooks. */
101
+ const CONFIG_VARIABLE = /^(?:\$env:)?GIT_CONFIG_(?:PARAMETERS|KEY_\d+)(?:=|$)/i;
102
+ const HOOKS_PATH_WORD = /core\.hookspath/i;
103
+ const EXPORTS = new Set(["export", "declare", "typeset", "set"]);
104
+
105
+ /**
106
+ * True when the segment sets a `GIT_CONFIG_*` variable to a value that names `core.hooksPath`: before its command,
107
+ * through `export`, or as a PowerShell `$env:` assignment. Only the segment's own settings count, so a heredoc or a
108
+ * message that quotes such a line passes.
109
+ */
110
+ function setsHooksPathVariable(segment) {
111
+ const settings = Object.entries(commandEnv(segment)).map(([name, value]) => `${name}=${value}`);
112
+ const [program, ...args] = commandWords(segment);
113
+ if (EXPORTS.has(program ?? "")) settings.push(...args);
114
+ if (CONFIG_VARIABLE.test(program ?? "") && args[0] === "=") settings.push(`${program}=${args.slice(1).join(" ")}`);
115
+ return settings.some((setting) => CONFIG_VARIABLE.test(setting) && HOOKS_PATH_WORD.test(setting));
116
+ }
80
117
 
81
118
  const namesHookScript = (word) => HOOK_SCRIPTS.some((name) => word.toLowerCase().endsWith(name));
82
119
 
@@ -143,7 +180,8 @@ const REASONS = {
143
180
  "the command skips the git hooks. The pre-commit and pre-push hooks are the gates: run the command " +
144
181
  "without `--no-verify` or `-n`, and fix what the hook names.",
145
182
  hooksPath:
146
- "`-c core.hooksPath=` points git away from the installed hooks, so the gates never run. Remove it.",
183
+ "`core.hooksPath` points git away from the installed hooks, so the gates never run. This guard refuses it in `-c`, in " +
184
+ "`git config`, and in `GIT_CONFIG_PARAMETERS` or `GIT_CONFIG_KEY_<n>`. To restore the hooks, run `npx qc install-hooks`.",
147
185
  script:
148
186
  "a hand run of a hook script writes a lease or a ledger record under a made-up session id, and that lease blocks later " +
149
187
  "edits in the worktree for hours. Test a hook only through its own suite (`node --test`), in temporary folders.",
@@ -217,6 +255,7 @@ export function violations(command, parse = segmentsOf, place = null, refused =
217
255
  const nested = nestedCommand(segment);
218
256
  if (nested) for (const key of violations(nested.command, nested.parse, place && { ...place, cwd, scoped, unknown }, refused)) found.add(key);
219
257
  }
258
+ if (segments.some(setsHooksPathVariable)) found.add("hooksPath");
220
259
  if (!segments.some(runsTests) && segments.some(runsHookScript)) found.add("script");
221
260
  return Object.keys(REASONS).filter((key) => found.has(key));
222
261
  }
@@ -37,6 +37,9 @@ test("a commit or push that skips the git hooks is denied", (t) => {
37
37
  "git commit -nm x",
38
38
  "git commit -anm x",
39
39
  "cd repo && git add -A && GIT_PAGER=cat git -C repo commit --no-verify -F -",
40
+ "git merge --no-verify feat/x",
41
+ "git rebase --no-verify main",
42
+ "git am --no-verify < fix.patch",
40
43
  ]) {
41
44
  assert.match(reasonOf(decide(bash(ws.adopted, command))) ?? "", /skips the git hooks/, command);
42
45
  }
@@ -69,11 +72,40 @@ test("git commit --no-verify inside bash -lc, env, sudo, and an if block is refu
69
72
 
70
73
  test("a git call that points core.hooksPath elsewhere is denied", (t) => {
71
74
  const ws = workspace(t);
72
- for (const command of ["git -c core.hooksPath=/dev/null commit -m x", "git -c core.hookspath= push"]) {
75
+ for (const command of [
76
+ "git -c core.hooksPath=/dev/null commit -m x",
77
+ "git -c core.hookspath= push",
78
+ "git config core.hooksPath /tmp/x && git commit -m x",
79
+ "git config --local core.hooksPath /tmp/x",
80
+ "git config set core.hooksPath /tmp/x",
81
+ "git config --unset core.hooksPath",
82
+ "git config --global core.hooksPath ''",
83
+ "git --config-env=core.hooksPath=HOOKS commit -m x",
84
+ "git --config-env core.hooksPath=HOOKS push",
85
+ "GIT_CONFIG_PARAMETERS=\"'core.hooksPath=/x'\" git commit -m x",
86
+ "export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=core.hooksPath GIT_CONFIG_VALUE_0=/x; git commit -m x",
87
+ ]) {
73
88
  assert.match(reasonOf(decide(bash(ws.adopted, command))) ?? "", /core\.hooksPath/, command);
74
89
  }
75
90
  });
76
91
 
92
+ test("a read of core.hooksPath, another setting, and a quoted mention pass", (t) => {
93
+ const ws = workspace(t);
94
+ for (const command of [
95
+ "git config --get core.hooksPath",
96
+ "git config core.hooksPath",
97
+ "git config --show-origin core.hooksPath",
98
+ "git config get core.hooksPath",
99
+ "git config get core.hooksPath --default .githooks",
100
+ "git config --get core.hooksPath githooks",
101
+ "git config core.autocrlf false",
102
+ "cat > notes.md <<'EOF'\nGIT_CONFIG_PARAMETERS sets core.hooksPath\nEOF",
103
+ "echo 'GIT_CONFIG_KEY_0=core.hooksPath' > fixture.txt",
104
+ ]) {
105
+ assert.equal(decide(bash(ws.adopted, command)), null, command);
106
+ }
107
+ });
108
+
77
109
  test("a hand run of a hook script is denied, and the reason names the lease", (t) => {
78
110
  const ws = workspace(t);
79
111
  for (const command of [
@@ -108,6 +140,8 @@ test("a message, a dry run, a test run and a read pass", (t) => {
108
140
  "npx vitest run src/work-order-guard.mjs",
109
141
  "cat packages/qc-harness/src/cli/work-order-guard.mjs",
110
142
  "git -c core.autocrlf=false commit -m x",
143
+ "git merge -n feat/x",
144
+ "git rebase -n main",
111
145
  ]) {
112
146
  assert.equal(decide(bash(ws.adopted, command)), null, command);
113
147
  }
@@ -33,6 +33,7 @@ export function decide(call, tmp = os.tmpdir()) {
33
33
  // A config typo must not stop every agent; the agent sees the error and reports it.
34
34
  return context(`Tool-call budget is off: ${error.message}`);
35
35
  }
36
+ if (budget === null) return null;
36
37
  let count;
37
38
  try {
38
39
  count = bumpCount(counterFileOf(call.session_id ?? "session", agentId, tmp));
@@ -81,8 +81,14 @@ test("in a linked worktree, the budget from qc.config.json denies the call that
81
81
  assert.equal(runGuard(ws, callOf(ws.linked, "agent-1", "Bash", { command: "git push" })), null);
82
82
  });
83
83
 
84
- test("the default budget reminds at its seventieth call", (t) => {
84
+ test("with no budget set, the guard counts nothing and stays silent", (t) => {
85
85
  const ws = workspace(t, {});
86
+ assert.equal(runGuard(ws, callOf(ws.linked, "agent-1")), null);
87
+ assert.equal(existsSync(ws.counters), false);
88
+ });
89
+
90
+ test("a budget of one hundred reminds at its seventieth call", (t) => {
91
+ const ws = workspace(t, { toolCallBudget: 100 });
86
92
  mkdirSync(ws.counters, { recursive: true });
87
93
  writeFileSync(path.join(ws.counters, "session-aaaa-agent-1.json"), JSON.stringify({ count: 69 }));
88
94
  const output = runGuard(ws, callOf(ws.linked, "agent-1"));
@@ -2,18 +2,17 @@
2
2
  // An agent does not count its own calls, and each call re-sends its whole transcript, so the hook
3
3
  // counts for it and closes every tool except the hand-off once the budget is spent.
4
4
 
5
- import { defaults } from "../config.mjs";
6
5
  import { gitCall, isReadOnly, segmentsOf, writesRedirect } from "./shell-command.mjs";
7
6
 
8
- export const DEFAULT_BUDGET = defaults.swarm.toolCallBudget;
9
7
  const REMIND_PERCENT = 70;
10
8
  const REMIND_EVERY = 10;
11
9
  const KEY = "swarm.toolCallBudget";
12
10
  const HANDOFF_GIT = new Set(["status", "diff", "log", "add", "commit", "push"]);
13
11
 
14
- /** @returns the budget from the `swarm` config section, or throws naming the key a repository got wrong. */
12
+ /** @returns the budget from the `swarm` config section, null when it is off, or throws naming the key a repository got wrong. */
15
13
  export function budgetOf(swarm = {}) {
16
- const budget = swarm.toolCallBudget ?? DEFAULT_BUDGET;
14
+ const budget = swarm.toolCallBudget ?? null;
15
+ if (budget === null) return null;
17
16
  if (!Number.isInteger(budget) || budget < 1) {
18
17
  throw new Error(`${KEY} in qc.config.json must be a positive whole number, got ${JSON.stringify(swarm.toolCallBudget)}`);
19
18
  }
@@ -1,16 +1,16 @@
1
1
  import { strict as assert } from "node:assert";
2
2
  import { test } from "node:test";
3
- import { DEFAULT_BUDGET, budgetOf, budgetVerdict, isHandoffCall } from "./budget.mjs";
3
+ import { budgetOf, budgetVerdict, isHandoffCall } from "./budget.mjs";
4
4
 
5
5
  const bash = (command) => ({ tool_name: "Bash", tool_input: { command } });
6
6
  const write = (file_path) => ({ tool_name: "Write", tool_input: { file_path, content: "x" } });
7
7
  const edit = (file_path) => ({ tool_name: "Edit", tool_input: { file_path, old_string: "a", new_string: "b" } });
8
8
  const verdict = (count, call = bash("npm test"), budget = 100) => budgetVerdict({ count, budget, call });
9
9
 
10
- test("the budget is swarm.toolCallBudget, and one hundred calls without it", () => {
11
- assert.equal(DEFAULT_BUDGET, 100);
12
- assert.equal(budgetOf(), 100);
13
- assert.equal(budgetOf({}), 100);
10
+ test("the budget is swarm.toolCallBudget, and off without it", () => {
11
+ assert.equal(budgetOf(), null);
12
+ assert.equal(budgetOf({}), null);
13
+ assert.equal(budgetOf({ toolCallBudget: null }), null);
14
14
  assert.equal(budgetOf({ toolCallBudget: 40 }), 40);
15
15
  });
16
16
 
@@ -0,0 +1,82 @@
1
+ // A pipeline that runs repository commands after the architecture checks pass.
2
+
3
+ import { execFileSync } from "node:child_process";
4
+ import spawn from "cross-spawn";
5
+
6
+ // Quotes group arguments; shell expansion stays off, and Windows path separators stay literal.
7
+ function commandWords(command) {
8
+ const words = [];
9
+ let word = "";
10
+ let quote = null;
11
+ let started = false;
12
+ for (let i = 0; i < command.length; i += 1) {
13
+ const char = command[i];
14
+ if (quote === "'") {
15
+ if (char === quote) quote = null;
16
+ else word += char;
17
+ } else if (char === "\\" && /[\\"'\s]/.test(command[i + 1] ?? "") && (quote === null || /[\\"]/.test(command[i + 1]))) {
18
+ word += command[++i];
19
+ started = true;
20
+ } else if (quote !== null) {
21
+ if (char === quote) quote = null;
22
+ else word += char;
23
+ } else if (char === '"' || char === "'") {
24
+ quote = char;
25
+ started = true;
26
+ } else if (/\s/.test(char)) {
27
+ if (started) words.push(word);
28
+ word = "";
29
+ started = false;
30
+ } else {
31
+ word += char;
32
+ started = true;
33
+ }
34
+ }
35
+ if (quote !== null) throw new Error("check command has an unterminated quote");
36
+ if (started) words.push(word);
37
+ if (!words[0]) throw new Error("check command must name an executable");
38
+ return words;
39
+ }
40
+
41
+ function changedFiles(root, base) {
42
+ const git = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
43
+ let mergeBase;
44
+ try {
45
+ mergeBase = git("merge-base", "--", "HEAD", base).trim();
46
+ } catch {
47
+ console.log(`WARN merge base with ${base} is unavailable; running related tests without file arguments`);
48
+ return null;
49
+ }
50
+ return git("diff", "--cached", "--name-only", "-z", "--no-renames", "--diff-filter=d", mergeBase, "--").split("\0").filter(Boolean);
51
+ }
52
+
53
+ async function runCommand(root, command, files = []) {
54
+ console.log(`RUN ${command.replace(/[\r\n]+/g, " ")}`);
55
+ try {
56
+ const [bin, ...args] = commandWords(command);
57
+ return await new Promise((resolve, reject) => {
58
+ const child = spawn(bin, [...args, ...files], { cwd: root, shell: false, stdio: "inherit", windowsHide: true });
59
+ child.on("error", reject);
60
+ child.on("close", (code) => resolve(code ?? 1));
61
+ });
62
+ } catch (error) {
63
+ console.error(`FAIL ${command}: ${error.message}`);
64
+ return 1;
65
+ }
66
+ }
67
+
68
+ export async function runCheckCommands(config) {
69
+ const { related, commands, base } = config.check;
70
+ if (related !== null) {
71
+ const files = changedFiles(config.root, base);
72
+ if (files === null || files.length > 0) {
73
+ const code = await runCommand(config.root, related, files ?? []);
74
+ if (code !== 0) return code;
75
+ }
76
+ }
77
+ for (const command of commands) {
78
+ const code = await runCommand(config.root, command);
79
+ if (code !== 0) return code;
80
+ }
81
+ return 0;
82
+ }
@@ -0,0 +1,190 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFileSync, spawnSync } from "node:child_process";
4
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { defaults } from "../config.mjs";
9
+
10
+ const qc = fileURLToPath(new URL("./qc.mjs", import.meta.url));
11
+ const node = (source) => `"${process.execPath}" -e '${source}'`;
12
+ const record = node('require("node:fs").writeFileSync("args.json", JSON.stringify(process.argv.slice(1)))');
13
+ const git = (root, ...args) => execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: "pipe" });
14
+
15
+ function fixture(t, check = {}) {
16
+ const root = mkdtempSync(path.join(tmpdir(), "qc-check-commands-"));
17
+ t.after(() => rmSync(root, { recursive: true, force: true }));
18
+ git(root, "init", "-q", "-b", "main");
19
+ git(root, "config", "user.name", "QC test");
20
+ git(root, "config", "user.email", "qc@example.test");
21
+ const config = {
22
+ featureRoots: [],
23
+ gates: Object.fromEntries(Object.keys(defaults.gates).map((key) => [key, false])),
24
+ check: { base: "main", ...check },
25
+ };
26
+ writeFileSync(path.join(root, "qc.config.json"), JSON.stringify(config));
27
+ writeFileSync(path.join(root, "committed.mjs"), "export const value = 1;\n");
28
+ writeFileSync(path.join(root, "unstaged.mjs"), "export {};\n");
29
+ git(root, "add", ".");
30
+ git(root, "commit", "-q", "-m", "test(qc): seed fixture");
31
+ git(root, "checkout", "-q", "-b", "feat/170-related");
32
+ return root;
33
+ }
34
+
35
+ function check(root, args = [], input, env = process.env) {
36
+ return spawnSync(process.execPath, [qc, "check", ...args], { cwd: root, encoding: "utf8", input, env });
37
+ }
38
+
39
+ test("related receives committed and staged paths once, without unstaged or untracked files", (t) => {
40
+ const root = fixture(t, { related: record });
41
+ writeFileSync(path.join(root, "committed.mjs"), "export const value = 2;\n");
42
+ git(root, "add", "committed.mjs");
43
+ git(root, "commit", "-q", "-m", "test(qc): change shared module");
44
+ const staged = "staged file; literal.mjs";
45
+ writeFileSync(path.join(root, staged), "export {};\n");
46
+ writeFileSync(path.join(root, "unstaged.mjs"), "export const unstaged = true;\n");
47
+ writeFileSync(path.join(root, "untracked.mjs"), "export {};\n");
48
+ git(root, "add", staged, "committed.mjs");
49
+ const run = check(root);
50
+ assert.equal(run.status, 0, run.stderr);
51
+ assert.deepEqual(JSON.parse(readFileSync(path.join(root, "args.json"), "utf8")), ["committed.mjs", staged]);
52
+ assert.equal(run.stdout.split("\n").filter((line) => line.startsWith("RUN ")).length, 1);
53
+ });
54
+
55
+ test("a failing related command streams output and preserves its exit code", (t) => {
56
+ const root = fixture(t, { related: node('console.log("related output"); console.error("related error"); process.exit(7)'), commands: [record] });
57
+ writeFileSync(path.join(root, "changed.mjs"), "export {};\n");
58
+ git(root, "add", "changed.mjs");
59
+ const run = check(root);
60
+ assert.equal(run.status, 7, run.stderr);
61
+ assert.match(run.stdout, /related output/);
62
+ assert.match(run.stderr, /related error/);
63
+ assert.equal(existsSync(path.join(root, "args.json")), false);
64
+ });
65
+
66
+ test("default check settings run no extra command or merge-base lookup", (t) => {
67
+ const root = fixture(t, { related: null, commands: [], base: "missing-ref" });
68
+ const run = check(root);
69
+ assert.equal(run.status, 0, run.stderr);
70
+ assert.doesNotMatch(run.stdout + run.stderr, /RUN |merge base/);
71
+ });
72
+
73
+ test("related skips an empty diff while repository commands run without file arguments", (t) => {
74
+ const root = fixture(t, { related: node("process.exit(9)"), commands: [record] });
75
+ const run = check(root);
76
+ assert.equal(run.status, 0, run.stderr);
77
+ assert.deepEqual(JSON.parse(readFileSync(path.join(root, "args.json"), "utf8")), []);
78
+ assert.equal(run.stdout.split("\n").filter((line) => line.startsWith("RUN ")).length, 1);
79
+ });
80
+
81
+ test("no merge base prints one reason and runs related without file arguments", (t) => {
82
+ const root = fixture(t, { related: record, base: "missing-ref" });
83
+ const run = check(root);
84
+ assert.equal(run.status, 0, run.stderr);
85
+ assert.deepEqual(JSON.parse(readFileSync(path.join(root, "args.json"), "utf8")), []);
86
+ const reasons = (run.stdout + run.stderr).split("\n").filter((line) => /merge base/.test(line));
87
+ assert.equal(reasons.length, 1);
88
+ assert.match(reasons[0], /missing-ref/);
89
+ });
90
+
91
+ test("repository commands run in order and stop with the failing command's exit code", (t) => {
92
+ const root = fixture(t, { commands: [node('console.log("first command")'), node("process.exit(8)"), record] });
93
+ const run = check(root);
94
+ assert.equal(run.status, 8, run.stderr);
95
+ assert.match(run.stdout, /first command/);
96
+ assert.equal(run.stdout.split("\n").filter((line) => line.startsWith("RUN ")).length, 2);
97
+ assert.equal(existsSync(path.join(root, "args.json")), false);
98
+ });
99
+
100
+ test("commands resolve PATH shims and preserve literal arguments and exit codes", (t) => {
101
+ const bin = mkdtempSync(path.join(tmpdir(), "qc command shims "));
102
+ t.after(() => rmSync(bin, { recursive: true, force: true }));
103
+ const source = 'require("node:fs").writeFileSync("args.json", JSON.stringify(process.argv.slice(3))); console.log("shim output"); process.exit(Number(process.argv[2]));\n';
104
+ if (process.platform === "win32") {
105
+ writeFileSync(path.join(bin, "shim.cjs"), source);
106
+ writeFileSync(path.join(bin, "qc-command-shim.cmd"), `@echo off\r\n"${process.execPath}" "%~dp0shim.cjs" %*\r\nexit /b %errorlevel%\r\n`);
107
+ } else {
108
+ writeFileSync(path.join(bin, "qc-command-shim"), `#!/usr/bin/env node\n${source}`, { mode: 0o755 });
109
+ }
110
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toLowerCase() !== "path"));
111
+ env.PATH = `${bin}${path.delimiter}${process.env.PATH ?? process.env.Path ?? ""}`;
112
+ for (const code of [0, 6]) {
113
+ const root = fixture(t, { commands: [`qc-command-shim ${code} "literal && $HOME $(echo hi)" "" escaped\\ space`] });
114
+ const run = check(root, [], undefined, env);
115
+ assert.equal(run.status, code, run.stderr);
116
+ assert.match(run.stdout, /shim output/);
117
+ assert.deepEqual(JSON.parse(readFileSync(path.join(root, "args.json"), "utf8")), ["literal && $HOME $(echo hi)", "", "escaped space"]);
118
+ }
119
+ });
120
+
121
+ test("a failed architecture check prevents repository commands", (t) => {
122
+ const root = fixture(t, { related: record, commands: [record] });
123
+ const config = JSON.parse(readFileSync(path.join(root, "qc.config.json"), "utf8"));
124
+ config.featureRoots = ["missing-root"];
125
+ writeFileSync(path.join(root, "qc.config.json"), JSON.stringify(config));
126
+ const run = check(root);
127
+ assert.equal(run.status, 1);
128
+ assert.match(run.stderr, /unfound-root/);
129
+ assert.equal(existsSync(path.join(root, "args.json")), false);
130
+ });
131
+
132
+ test("a missing command fails the check", (t) => {
133
+ const root = fixture(t, { commands: ["qc-missing-command-170"] });
134
+ const run = check(root);
135
+ assert.equal(run.status, 1);
136
+ assert.match(run.stderr, /qc-missing-command-170/);
137
+ });
138
+
139
+ test("an empty explicit file list still runs repository commands", (t) => {
140
+ const root = fixture(t, { commands: [record] });
141
+ const run = check(root, ["--files-from", "-"], "");
142
+ assert.equal(run.status, 0, run.stderr);
143
+ assert.deepEqual(JSON.parse(readFileSync(path.join(root, "args.json"), "utf8")), []);
144
+ });
145
+
146
+ test("quoted arguments and shell syntax reach the command as literal values", (t) => {
147
+ const root = fixture(t, { commands: [`${record} "literal && $HOME $(echo hi)" "" escaped\\ space`] });
148
+ const run = check(root);
149
+ assert.equal(run.status, 0, run.stderr);
150
+ assert.deepEqual(JSON.parse(readFileSync(path.join(root, "args.json"), "utf8")), ["literal && $HOME $(echo hi)", "", "escaped space"]);
151
+ });
152
+
153
+ test("double quotes and escaped quotes preserve inline node source", (t) => {
154
+ const command = `${JSON.stringify(process.execPath)} -e ${JSON.stringify('process.stdout.write("quoted output")')}`;
155
+ const root = fixture(t, { commands: [command] });
156
+ const run = check(root);
157
+ assert.equal(run.status, 0, run.stderr);
158
+ assert.match(run.stdout, /quoted output/);
159
+ });
160
+
161
+ test("an unterminated quote fails the check", (t) => {
162
+ const root = fixture(t, { commands: ['node "unterminated'] });
163
+ const run = check(root);
164
+ assert.equal(run.status, 1);
165
+ assert.match(run.stderr, /quote/i);
166
+ });
167
+
168
+ test("related uses the merge base instead of changes on the base branch", (t) => {
169
+ const root = fixture(t, { related: record });
170
+ writeFileSync(path.join(root, "feature.mjs"), "export {};\n");
171
+ git(root, "add", "feature.mjs");
172
+ git(root, "commit", "-q", "-m", "test(qc): change feature");
173
+ git(root, "checkout", "-q", "main");
174
+ writeFileSync(path.join(root, "base-only.mjs"), "export {};\n");
175
+ git(root, "add", "base-only.mjs");
176
+ git(root, "commit", "-q", "-m", "test(qc): advance base");
177
+ git(root, "checkout", "-q", "feat/170-related");
178
+ const run = check(root);
179
+ assert.equal(run.status, 0, run.stderr);
180
+ assert.deepEqual(JSON.parse(readFileSync(path.join(root, "args.json"), "utf8")), ["feature.mjs"]);
181
+ });
182
+
183
+ test("related excludes staged deletions and receives the new path of a staged rename", (t) => {
184
+ const root = fixture(t, { related: record });
185
+ git(root, "rm", "committed.mjs");
186
+ git(root, "mv", "unstaged.mjs", "renamed file.mjs");
187
+ const run = check(root);
188
+ assert.equal(run.status, 0, run.stderr);
189
+ assert.deepEqual(JSON.parse(readFileSync(path.join(root, "args.json"), "utf8")), ["renamed file.mjs"]);
190
+ });