architecture-harness 0.8.0 → 0.9.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -0,0 +1,129 @@
1
+ #!/usr/bin/env node
2
+ // The PreToolUse trigger that refuses a Bash command which skips the git hooks, or which runs a hook
3
+ // script by hand. It reads the command through shell-command.mjs and never runs it.
4
+
5
+ import { existsSync } from "node:fs";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { CONFIG_FILE } from "../config.mjs";
9
+ import { checkoutRootOf } from "./checkout-root.mjs";
10
+ import { commandWords, gitCall, segmentsOf } from "./shell-command.mjs";
11
+
12
+ const HOOK_SCRIPTS = [
13
+ "work-order-guard.mjs", "budget-guard.mjs", "bash-edit-guard.mjs", "worktree-isolation.mjs", "pre-edit-guard.sh",
14
+ ];
15
+ const NO_VERIFY = "--no-verify";
16
+ // The shortest prefix git could still expand to `--no-verify`.
17
+ const NO_VERIFY_MIN = "--no-ver".length;
18
+ /** The long options of commit and push whose value is the next word, so that word is no flag. */
19
+ const VALUE_OPTIONS = new Set([
20
+ "--message", "--file", "--author", "--date", "--template", "--reuse-message", "--reedit-message",
21
+ "--fixup", "--squash", "--trailer", "--cleanup", "--pathspec-from-file", "--push-option", "--repo",
22
+ "--receive-pack", "--exec",
23
+ ]);
24
+ /** The short options of commit whose value is the rest of the cluster, or the next word. */
25
+ const COMMIT_VALUE_FLAGS = new Set(["m", "F", "C", "c", "t"]);
26
+
27
+ const programName = (word) => path.basename(word ?? "").toLowerCase().replace(/\.exe$/, "");
28
+ const isNoVerify = (arg) => arg.length >= NO_VERIFY_MIN && NO_VERIFY.startsWith(arg);
29
+
30
+ /** True when a commit or push names `--no-verify`, or a commit names `-n` alone or in a flag cluster. */
31
+ function skipsHooks({ sub, args }) {
32
+ if (sub !== "commit" && sub !== "push") return false;
33
+ for (let i = 0; i < args.length; i++) {
34
+ const arg = args[i];
35
+ if (arg === "--") return false;
36
+ if (isNoVerify(arg)) return true;
37
+ if (VALUE_OPTIONS.has(arg)) i++;
38
+ if (sub !== "commit" || !/^-[A-Za-z]/.test(arg)) continue;
39
+ for (let at = 1; at < arg.length; at++) {
40
+ if (arg[at] === "n") return true;
41
+ // `-u` and `-S` take an optional value in the same cluster, as in `-uno`.
42
+ if (arg[at] === "u" || arg[at] === "S") break;
43
+ if (COMMIT_VALUE_FLAGS.has(arg[at])) {
44
+ if (at === arg.length - 1) i++;
45
+ break;
46
+ }
47
+ }
48
+ }
49
+ return false;
50
+ }
51
+
52
+ const setsHooksPath = ({ configs }) => configs.some((setting) => /^core\.hookspath=/i.test(setting ?? ""));
53
+
54
+ const namesHookScript = (word) => HOOK_SCRIPTS.some((name) => word.toLowerCase().endsWith(name));
55
+
56
+ /** True when the segment runs a hook script: through node, through a shell, or as the program itself. */
57
+ function runsHookScript(segment) {
58
+ const [program, ...args] = commandWords(segment);
59
+ if (program === undefined) return false;
60
+ if (namesHookScript(program)) return true;
61
+ const name = programName(program);
62
+ return ["node", "bash", "sh"].includes(name) && args.some((arg) => !arg.startsWith("-") && namesHookScript(arg));
63
+ }
64
+
65
+ /** True when the segment runs a test runner, which may load a hook script on purpose. */
66
+ function runsTests(segment) {
67
+ const [program, ...args] = commandWords(segment);
68
+ if (programName(program) === "node" && args.includes("--test")) return true;
69
+ return [program, ...args].some((word) => programName(word) === "vitest");
70
+ }
71
+
72
+ const REASONS = {
73
+ hooks:
74
+ "the command skips the git hooks. The pre-commit and pre-push hooks are the gates: run the command " +
75
+ "without `--no-verify` or `-n`, and fix what the hook names.",
76
+ hooksPath:
77
+ "`-c core.hooksPath=` points git away from the installed hooks, so the gates never run. Remove it.",
78
+ script:
79
+ "a hand run of a hook script writes a lease under a made-up session id, and that lease blocks later " +
80
+ "edits in the worktree for hours. Test a hook only through its own suite (`node --test`), in temporary folders.",
81
+ };
82
+
83
+ /** @returns the reasons the command breaks a rule, in a stable order. */
84
+ export function violations(command) {
85
+ const segments = segmentsOf(command);
86
+ const found = new Set();
87
+ for (const segment of segments) {
88
+ const git = gitCall(segment);
89
+ if (git && skipsHooks(git)) found.add("hooks");
90
+ if (git && setsHooksPath(git)) found.add("hooksPath");
91
+ }
92
+ if (!segments.some(runsTests) && segments.some(runsHookScript)) found.add("script");
93
+ return Object.keys(REASONS).filter((key) => found.has(key));
94
+ }
95
+
96
+ /** The verdict on one Bash call. @returns the hook output, or null to let the call run with no message. */
97
+ export function decide(call) {
98
+ const command = call.tool_input?.command;
99
+ if (call.tool_name !== "Bash" || typeof command !== "string") return null;
100
+ const root = checkoutRootOf(call.cwd ?? process.cwd());
101
+ if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
102
+ const found = violations(command);
103
+ if (found.length === 0) return null;
104
+ return {
105
+ hookSpecificOutput: {
106
+ hookEventName: "PreToolUse",
107
+ permissionDecision: "deny",
108
+ permissionDecisionReason: `Bash command guard: ${found.map((key) => REASONS[key]).join(" Also, ")}`,
109
+ },
110
+ };
111
+ }
112
+
113
+ async function readStdin() {
114
+ let data = "";
115
+ for await (const chunk of process.stdin) data += chunk;
116
+ return data;
117
+ }
118
+
119
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
120
+ if (isEntryPoint) {
121
+ let call = null;
122
+ try {
123
+ call = JSON.parse(await readStdin());
124
+ } catch {
125
+ // Not hook input, so there is no command to judge.
126
+ }
127
+ const output = call ? decide(call) : null;
128
+ if (output) process.stdout.write(JSON.stringify(output));
129
+ }
@@ -0,0 +1,96 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+ import { decide } from "./bash-command-guard.mjs";
9
+
10
+ const GUARD = fileURLToPath(new URL("./bash-command-guard.mjs", import.meta.url));
11
+
12
+ /** An adopted checkout and a checkout with no config. */
13
+ function workspace(t) {
14
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-bash-command-")));
15
+ t.after(() => rmSync(base, { recursive: true, force: true }));
16
+ const adopted = path.join(base, "adopted");
17
+ const plain = path.join(base, "plain");
18
+ for (const dir of [adopted, plain]) {
19
+ mkdirSync(dir);
20
+ execFileSync("git", ["init", "-q"], { cwd: dir, stdio: "pipe" });
21
+ }
22
+ writeFileSync(path.join(adopted, "qc.config.json"), "{}");
23
+ return { adopted, plain };
24
+ }
25
+
26
+ const bash = (cwd, command) => ({ hook_event_name: "PreToolUse", tool_name: "Bash", cwd, tool_input: { command } });
27
+ const reasonOf = (output) => (output?.hookSpecificOutput?.permissionDecision === "deny" ? output.hookSpecificOutput.permissionDecisionReason : null);
28
+
29
+ test("a commit or push that skips the git hooks is denied", (t) => {
30
+ const ws = workspace(t);
31
+ for (const command of [
32
+ "git commit --no-verify -m x",
33
+ "git commit --no-veri -m x",
34
+ "git push --no-verify",
35
+ "git push origin feat/x --no-verify",
36
+ "git commit -n -m x",
37
+ "git commit -nm x",
38
+ "git commit -anm x",
39
+ "cd repo && git add -A && GIT_PAGER=cat git -C repo commit --no-verify -F -",
40
+ ]) {
41
+ assert.match(reasonOf(decide(bash(ws.adopted, command))) ?? "", /skips the git hooks/, command);
42
+ }
43
+ });
44
+
45
+ test("a git call that points core.hooksPath elsewhere is denied", (t) => {
46
+ const ws = workspace(t);
47
+ for (const command of ["git -c core.hooksPath=/dev/null commit -m x", "git -c core.hookspath= push"]) {
48
+ assert.match(reasonOf(decide(bash(ws.adopted, command))) ?? "", /core\.hooksPath/, command);
49
+ }
50
+ });
51
+
52
+ test("a hand run of a hook script is denied, and the reason names the lease", (t) => {
53
+ const ws = workspace(t);
54
+ for (const command of [
55
+ "node packages/qc-harness/src/cli/work-order-guard.mjs < input.json",
56
+ `echo '{}' | node "C:/kit/packages/qc-harness/src/cli/budget-guard.mjs"`,
57
+ "node ./bash-edit-guard.mjs",
58
+ "node.exe src/cli/worktree-isolation.mjs",
59
+ "bash hooks/pre-edit-guard.sh",
60
+ "./hooks/pre-edit-guard.sh < input.json",
61
+ ]) {
62
+ assert.match(reasonOf(decide(bash(ws.adopted, command))) ?? "", /writes a lease/, command);
63
+ }
64
+ });
65
+
66
+ test("a message, a dry run, a test run and a read pass", (t) => {
67
+ const ws = workspace(t);
68
+ for (const command of [
69
+ 'git commit -m "-n is fine"',
70
+ 'git commit -m "handle --no-verify" --author "a <a@b.c>"',
71
+ "git commit -mn",
72
+ "git commit -uno -m x",
73
+ "git push -n",
74
+ "git log --oneline -n 5",
75
+ "node --test packages/qc-harness/src/cli/work-order-guard.test.mjs",
76
+ "node --test src/cli && node src/cli/budget-guard.mjs < stub.json",
77
+ "npx vitest run src/work-order-guard.mjs",
78
+ "cat packages/qc-harness/src/cli/work-order-guard.mjs",
79
+ "git -c core.autocrlf=false commit -m x",
80
+ ]) {
81
+ assert.equal(decide(bash(ws.adopted, command)), null, command);
82
+ }
83
+ });
84
+
85
+ test("a repository with no qc.config.json is never guarded", (t) => {
86
+ const ws = workspace(t);
87
+ assert.equal(decide(bash(ws.plain, "git commit --no-verify -m x")), null);
88
+ });
89
+
90
+ test("the hook process prints the deny", (t) => {
91
+ const ws = workspace(t);
92
+ const input = JSON.stringify(bash(ws.adopted, "git push --no-verify"));
93
+ const result = spawnSync(process.execPath, [GUARD], { input, encoding: "utf8" });
94
+ assert.equal(result.status, 0, result.stderr);
95
+ assert.equal(JSON.parse(result.stdout).hookSpecificOutput.permissionDecision, "deny");
96
+ });
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- // The PostToolUse trigger that holds a Bash command to the rules the edit guard holds Write and Edit
3
- // to: the work order's declared paths, and no change on a protected branch. A shell write through
4
- // sed, a script or a codemod never reaches the edit guard. This one warns and never reverts.
2
+ // The PostToolUse trigger that holds a Bash or PowerShell command to the rules the edit guard holds
3
+ // Write and Edit to: the work order's declared paths, and no change on a protected branch. A shell
4
+ // write through sed, a script or a codemod never reaches the edit guard. This one warns and never reverts.
5
5
 
6
6
  import { execFile } from "node:child_process";
7
7
  import { existsSync, realpathSync } from "node:fs";
@@ -12,7 +12,8 @@ import { promisify } from "node:util";
12
12
  import { load } from "../config.mjs";
13
13
  import { checkoutRootOf } from "./checkout-root.mjs";
14
14
  import { ignoredPaths } from "./ignored-paths.mjs";
15
- import { checkoutDirs, mayWrite } from "./shell-command.mjs";
15
+ import * as powershell from "./powershell-command.mjs";
16
+ import * as posix from "./shell-command.mjs";
16
17
  import { isAllowed } from "./work-order-guard.mjs";
17
18
  import { MANIFEST_FILE, readManifest } from "./work-order-manifest.mjs";
18
19
  import { OFF, isolationSettings } from "./worktree-isolation.mjs";
@@ -52,9 +53,9 @@ function resolveDir(cwd, dir) {
52
53
  }
53
54
 
54
55
  /** Every distinct checkout the command could have changed: its cwd, and each `cd` and `git -C` directory. */
55
- function checkoutsOf(cwd, command) {
56
+ function checkoutsOf(cwd, command, dialect) {
56
57
  const roots = new Set();
57
- for (const dir of [cwd, ...checkoutDirs(command).map((d) => resolveDir(cwd, d))]) {
58
+ for (const dir of [cwd, ...dialect.checkoutDirs(command).map((d) => resolveDir(cwd, d))]) {
58
59
  const root = dir && checkoutRootOf(dir);
59
60
  const real = root && native(root);
60
61
  if (real) roots.add(real);
@@ -113,7 +114,8 @@ async function findingsIn(root, manifest, projectRoot) {
113
114
  */
114
115
  export async function report(call, projectRoot) {
115
116
  const command = call.tool_input?.command;
116
- if (typeof command !== "string" || !mayWrite(command)) return null;
117
+ const dialect = call.tool_name === "PowerShell" ? powershell : posix;
118
+ if (typeof command !== "string" || !dialect.mayWrite(command)) return null;
117
119
  const cwd = call.cwd ?? process.cwd();
118
120
  const project = native(projectRoot) ?? projectRoot;
119
121
 
@@ -124,7 +126,7 @@ export async function report(call, projectRoot) {
124
126
  // The edit guard names a manifest that does not parse.
125
127
  }
126
128
  const findings = [];
127
- for (const root of checkoutsOf(cwd, command)) findings.push(...(await findingsIn(root, manifest, project)));
129
+ for (const root of checkoutsOf(cwd, command, dialect)) findings.push(...(await findingsIn(root, manifest, project)));
128
130
  if (findings.length === 0) return null;
129
131
 
130
132
  const listed = findings.slice(0, MAX_LISTED).map((line) => `- ${line}`);
@@ -37,6 +37,22 @@ function workspace(t) {
37
37
 
38
38
  const bash = (cwd, command) => ({ hook_event_name: "PostToolUse", tool_name: "Bash", cwd, tool_input: { command } });
39
39
  const contextOf = (output) => output?.hookSpecificOutput?.additionalContext ?? "";
40
+ const powershell = (cwd, command) => ({ ...bash(cwd, command), tool_name: "PowerShell" });
41
+
42
+ test("a PowerShell write outside the declared paths is reported, and a read-only verb skips the check", async (t) => {
43
+ const ws = workspace(t);
44
+ ws.put(ws.linked, "docs/b.md");
45
+ const output = await report(powershell(ws.linked, "Set-Content -Path docs\\b.md -Value changed"), ws.linked);
46
+ assert.match(contextOf(output), /docs\/b\.md: outside the work order's declared paths/);
47
+ assert.equal(await report(powershell(ws.linked, "Get-ChildItem docs | Select-String changed"), ws.linked), null);
48
+ });
49
+
50
+ test("a PowerShell location change names the checkout to inspect", async (t) => {
51
+ const ws = workspace(t);
52
+ ws.put(ws.linked, "docs/b.md");
53
+ const output = await report(powershell(ws.outside, `Set-Location '${ws.linked}'; New-Item docs\\b.md`), ws.linked);
54
+ assert.match(contextOf(output), /docs\/b\.md/);
55
+ });
40
56
 
41
57
  test("a write inside the work order's declared paths is silent", async (t) => {
42
58
  const ws = workspace(t);
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env node
2
+ // The trigger for swarm.md's one edit per file per parallel block. PreToolUse claims the file for the
3
+ // batch and denies a second claim. PostToolBatch ends the batch, and a claim expires as a last resort.
4
+
5
+ import { existsSync } from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { CONFIG_FILE } from "../config.mjs";
10
+ import { checkoutRootOf } from "./checkout-root.mjs";
11
+ import { batchDirOf, claimPath, endBatch, isBatchAware, releasePath } from "./edit-batch-state.mjs";
12
+
13
+ const EDIT_TOOLS = new Set(["Write", "Edit", "MultiEdit"]);
14
+ export const CLAIM_TTL_MS = 60_000;
15
+
16
+ /** One file as one key: absolute, forward slashes, and lowercase on Windows. */
17
+ export function pathKey(file, cwd, platform = process.platform) {
18
+ const paths = platform === "win32" ? path.win32 : path.posix;
19
+ const slashed = paths.resolve(cwd, file).split(paths.sep).join("/");
20
+ return platform === "win32" ? slashed.toLowerCase() : slashed;
21
+ }
22
+
23
+ const deny = (file) => ({
24
+ hookSpecificOutput: {
25
+ hookEventName: "PreToolUse",
26
+ permissionDecision: "deny",
27
+ permissionDecisionReason:
28
+ `Edit batch guard: one edit per file per parallel block: send it after this result. Another edit ` +
29
+ `of ${file} is in this block, and two edits of one file race and lose all but the last.`,
30
+ },
31
+ });
32
+
33
+ /** The verdict on one hook event. @returns the hook output, or null to let the call run with no message. */
34
+ export function decide(call, tmp = os.tmpdir(), now = Date.now()) {
35
+ const agentKey = typeof call.agent_id === "string" && call.agent_id !== "" ? call.agent_id : "main";
36
+ const dir = batchDirOf(call.session_id ?? "session", agentKey, tmp);
37
+ try {
38
+ if (call.hook_event_name === "PostToolBatch") {
39
+ // Only a claim makes the folder, so a repository with no config gets no file here.
40
+ if (existsSync(dir)) endBatch(dir);
41
+ return null;
42
+ }
43
+ const file = call.tool_input?.file_path;
44
+ if (!EDIT_TOOLS.has(call.tool_name) || typeof file !== "string" || file === "") return null;
45
+ const key = pathKey(file, call.cwd ?? process.cwd());
46
+ if (call.hook_event_name === "PostToolUse") {
47
+ // A client with no batch event ends the claim with the result, so a later edit is never refused.
48
+ if (!isBatchAware(dir)) releasePath(dir, key);
49
+ return null;
50
+ }
51
+ if (call.hook_event_name !== "PreToolUse") return null;
52
+ const root = checkoutRootOf(path.dirname(path.resolve(call.cwd ?? process.cwd(), file)));
53
+ if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
54
+ return claimPath(dir, key, now, CLAIM_TTL_MS) ? null : deny(file);
55
+ } catch {
56
+ // A busy or read-only temp folder is the hook's own problem, never a reason to refuse an edit.
57
+ return null;
58
+ }
59
+ }
60
+
61
+ async function readStdin() {
62
+ let data = "";
63
+ for await (const chunk of process.stdin) data += chunk;
64
+ return data;
65
+ }
66
+
67
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
68
+ if (isEntryPoint) {
69
+ let call = null;
70
+ try {
71
+ call = JSON.parse(await readStdin());
72
+ } catch {
73
+ // Not hook input, so there is nothing to judge.
74
+ }
75
+ const output = call ? decide(call) : null;
76
+ if (output) process.stdout.write(JSON.stringify(output));
77
+ }
@@ -0,0 +1,131 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+ import { CLAIM_TTL_MS, decide, pathKey } from "./edit-batch-guard.mjs";
9
+
10
+ const GUARD = fileURLToPath(new URL("./edit-batch-guard.mjs", import.meta.url));
11
+
12
+ /** An adopted checkout, a checkout with no config, and a temp folder for the batch state. */
13
+ function workspace(t) {
14
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-edit-batch-")));
15
+ t.after(() => rmSync(base, { recursive: true, force: true }));
16
+ const adopted = path.join(base, "adopted");
17
+ const plain = path.join(base, "plain");
18
+ const tmp = path.join(base, "tmp");
19
+ for (const dir of [adopted, plain, tmp]) mkdirSync(dir);
20
+ execFileSync("git", ["init", "-q"], { cwd: adopted, stdio: "pipe" });
21
+ execFileSync("git", ["init", "-q"], { cwd: plain, stdio: "pipe" });
22
+ writeFileSync(path.join(adopted, "qc.config.json"), "{}");
23
+ return { adopted, plain, tmp, file: path.join(adopted, "src", "a.ts") };
24
+ }
25
+
26
+ const callOf = (hook_event_name, file, { agent, tool = "Edit" } = {}) => ({
27
+ session_id: "session-aaaa",
28
+ ...(agent ? { agent_id: agent, agent_type: "general-purpose" } : {}),
29
+ cwd: path.dirname(path.dirname(file)),
30
+ hook_event_name,
31
+ tool_name: tool,
32
+ tool_input: { file_path: file, old_string: "a", new_string: "b" },
33
+ });
34
+ const batchEnd = (agent) => ({
35
+ session_id: "session-aaaa",
36
+ ...(agent ? { agent_id: agent } : {}),
37
+ hook_event_name: "PostToolBatch",
38
+ tool_calls: [],
39
+ });
40
+ const isDenied = (output) => output?.hookSpecificOutput?.permissionDecision === "deny";
41
+
42
+ test("two edits to one path in one batch: the second is denied and told to wait for the result", (t) => {
43
+ const ws = workspace(t);
44
+ assert.equal(decide(callOf("PreToolUse", ws.file), ws.tmp), null);
45
+ const output = decide(callOf("PreToolUse", ws.file, { tool: "Write" }), ws.tmp);
46
+ assert.ok(isDenied(output));
47
+ assert.equal(output.hookSpecificOutput.hookEventName, "PreToolUse");
48
+ assert.match(output.hookSpecificOutput.permissionDecisionReason, /one edit per file per parallel block: send it after this result/);
49
+ });
50
+
51
+ test("a sequential pair passes: the batch event ends the claim", (t) => {
52
+ const ws = workspace(t);
53
+ assert.equal(decide(callOf("PreToolUse", ws.file, { tool: "MultiEdit" }), ws.tmp), null);
54
+ decide(callOf("PostToolUse", ws.file), ws.tmp);
55
+ decide(batchEnd(), ws.tmp);
56
+ assert.equal(decide(callOf("PreToolUse", ws.file), ws.tmp), null);
57
+ });
58
+
59
+ test("a batch event before any claim writes nothing", (t) => {
60
+ const ws = workspace(t);
61
+ decide(batchEnd(), ws.tmp);
62
+ assert.equal(existsSync(path.join(ws.tmp, "architecture-kit", "edit-batch")), false);
63
+ });
64
+
65
+ test("once the agent has seen a batch event, its result alone does not end the claim", (t) => {
66
+ const ws = workspace(t);
67
+ decide(callOf("PreToolUse", ws.file), ws.tmp);
68
+ decide(batchEnd(), ws.tmp);
69
+ assert.equal(decide(callOf("PreToolUse", ws.file), ws.tmp), null);
70
+ decide(callOf("PostToolUse", ws.file), ws.tmp);
71
+ assert.ok(isDenied(decide(callOf("PreToolUse", ws.file), ws.tmp)));
72
+ });
73
+
74
+ test("before any batch event, the result of the edit ends the claim", (t) => {
75
+ const ws = workspace(t);
76
+ assert.equal(decide(callOf("PreToolUse", ws.file, { agent: "agent-1" }), ws.tmp), null);
77
+ decide(callOf("PostToolUse", ws.file, { agent: "agent-1" }), ws.tmp);
78
+ assert.equal(decide(callOf("PreToolUse", ws.file, { agent: "agent-1" }), ws.tmp), null);
79
+ });
80
+
81
+ test("a claim left behind expires", (t) => {
82
+ const ws = workspace(t);
83
+ decide(batchEnd(), ws.tmp);
84
+ assert.equal(decide(callOf("PreToolUse", ws.file), ws.tmp), null);
85
+ assert.ok(isDenied(decide(callOf("PreToolUse", ws.file), ws.tmp)));
86
+ assert.equal(decide(callOf("PreToolUse", ws.file), ws.tmp, Date.now() + CLAIM_TTL_MS + 1000), null);
87
+ });
88
+
89
+ test("different agents, and the main session, do not block each other", (t) => {
90
+ const ws = workspace(t);
91
+ assert.equal(decide(callOf("PreToolUse", ws.file, { agent: "agent-1" }), ws.tmp), null);
92
+ assert.equal(decide(callOf("PreToolUse", ws.file, { agent: "agent-2" }), ws.tmp), null);
93
+ assert.equal(decide(callOf("PreToolUse", ws.file), ws.tmp), null);
94
+ assert.ok(isDenied(decide(callOf("PreToolUse", ws.file, { agent: "agent-2" }), ws.tmp)));
95
+ decide(batchEnd("agent-2"), ws.tmp);
96
+ assert.equal(decide(callOf("PreToolUse", ws.file, { agent: "agent-2" }), ws.tmp), null);
97
+ assert.ok(isDenied(decide(callOf("PreToolUse", ws.file, { agent: "agent-1" }), ws.tmp)));
98
+ });
99
+
100
+ test("a repository with no qc.config.json is never guarded, and other tools are ignored", (t) => {
101
+ const ws = workspace(t);
102
+ const file = path.join(ws.plain, "src", "a.ts");
103
+ decide(callOf("PreToolUse", file), ws.tmp);
104
+ assert.equal(decide(callOf("PreToolUse", file), ws.tmp), null);
105
+ decide(callOf("PreToolUse", ws.file, { tool: "Read" }), ws.tmp);
106
+ assert.equal(decide(callOf("PreToolUse", ws.file), ws.tmp), null);
107
+ });
108
+
109
+ test("a path key is absolute with forward slashes, and case-blind on Windows only", () => {
110
+ assert.equal(pathKey("C:\\Repo\\Src\\A.ts", "C:\\", "win32"), "c:/repo/src/a.ts");
111
+ assert.equal(pathKey("src/A.ts", "C:\\Repo", "win32"), "c:/repo/src/a.ts");
112
+ assert.equal(pathKey("/repo/Src/A.ts", "/", "linux"), "/repo/Src/A.ts");
113
+ assert.equal(pathKey("A.ts", "/repo", "linux"), "/repo/A.ts");
114
+ });
115
+
116
+ test("the hook process prints a deny for the second claim and nothing for the batch event", (t) => {
117
+ const ws = workspace(t);
118
+ const run = (call) => {
119
+ const result = spawnSync(process.execPath, [GUARD], {
120
+ input: JSON.stringify(call),
121
+ env: { ...process.env, TEMP: ws.tmp, TMP: ws.tmp, TMPDIR: ws.tmp },
122
+ encoding: "utf8",
123
+ });
124
+ assert.equal(result.status, 0, result.stderr);
125
+ return result.stdout.trim() === "" ? null : JSON.parse(result.stdout);
126
+ };
127
+ assert.equal(run(callOf("PreToolUse", ws.file)), null);
128
+ assert.ok(isDenied(run(callOf("PreToolUse", ws.file))));
129
+ assert.equal(run(batchEnd()), null);
130
+ assert.equal(run(callOf("PreToolUse", ws.file)), null);
131
+ });
@@ -0,0 +1,57 @@
1
+ // The resource for the edit batch guard: one folder per agent in one session, under the OS temp
2
+ // folder, with one empty claim file per path. A hash names the file, so it holds no path.
3
+
4
+ import { createHash } from "node:crypto";
5
+ import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import path from "node:path";
7
+
8
+ const fileSafe = (id) => String(id).replace(/[^A-Za-z0-9_.-]/g, "_");
9
+ const BATCH_AWARE = "batch-aware";
10
+
11
+ /** The batch folder of one agent in one session. */
12
+ export const batchDirOf = (sessionId, agentKey, tmp) =>
13
+ path.join(tmp, "architecture-kit", "edit-batch", `${fileSafe(sessionId)}-${fileSafe(agentKey)}`);
14
+
15
+ const claimFileOf = (dir, key) => path.join(dir, `${createHash("sha256").update(key).digest("hex")}.claim`);
16
+
17
+ /**
18
+ * Claims one path through an exclusive create, so two hooks that run at once cannot both win.
19
+ * A claim older than `ttlMs` is a leftover and is taken over.
20
+ * @returns true when this call holds the claim; throws on a file system error
21
+ */
22
+ export function claimPath(dir, key, now, ttlMs) {
23
+ const file = claimFileOf(dir, key);
24
+ for (;;) {
25
+ try {
26
+ writeFileSync(file, "", { flag: "wx" });
27
+ return true;
28
+ } catch (error) {
29
+ if (error.code === "ENOENT") {
30
+ mkdirSync(dir, { recursive: true });
31
+ continue;
32
+ }
33
+ if (error.code !== "EEXIST") throw error;
34
+ }
35
+ let claimedAt;
36
+ try {
37
+ claimedAt = statSync(file).mtimeMs;
38
+ } catch {
39
+ continue;
40
+ }
41
+ if (now - claimedAt < ttlMs) return false;
42
+ rmSync(file, { force: true });
43
+ }
44
+ }
45
+
46
+ /** Ends one claim before the batch ends. */
47
+ export const releasePath = (dir, key) => rmSync(claimFileOf(dir, key), { force: true });
48
+
49
+ /** True once a batch event has reached this agent, so its client sends one after every batch. */
50
+ export const isBatchAware = (dir) => existsSync(path.join(dir, BATCH_AWARE));
51
+
52
+ /** Ends every claim of the batch, and records that this agent receives batch events. */
53
+ export function endBatch(dir) {
54
+ rmSync(dir, { recursive: true, force: true });
55
+ mkdirSync(dir, { recursive: true });
56
+ writeFileSync(path.join(dir, BATCH_AWARE), "");
57
+ }
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+ // The PreToolUse trigger that refuses a hand edit of a generated file, or of a generated region of a
3
+ // Markdown file, and names the command that writes it. That command writes through the shell, never here.
4
+
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { CONFIG_FILE, load } from "../config.mjs";
9
+ import { generatedRegions } from "../generated-markers.mjs";
10
+ import { globMatcher } from "../glob.mjs";
11
+ import { checkoutRootOf } from "./checkout-root.mjs";
12
+
13
+ const EDIT_TOOLS = new Set(["Write", "Edit", "MultiEdit"]);
14
+ const MARKDOWN = /\.mdx?$/i;
15
+ const lf = (text) => text.replace(/\r\n/g, "\n");
16
+
17
+ const deny = (reason) => ({
18
+ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason },
19
+ });
20
+
21
+ /** True when any occurrence of `needle` overlaps a region. */
22
+ function touchesRegion(text, needle, regions) {
23
+ for (let at = text.indexOf(needle); at !== -1; at = text.indexOf(needle, at + 1)) {
24
+ if (regions.some(([start, end]) => at < end && at + needle.length > start)) return true;
25
+ }
26
+ return false;
27
+ }
28
+
29
+ /** True when an Edit or MultiEdit changes text inside a generated region of the Markdown file. */
30
+ function editsRegion(file, input) {
31
+ if (!existsSync(file)) return false;
32
+ const text = lf(readFileSync(file, "utf8"));
33
+ const regions = generatedRegions(text);
34
+ if (regions.length === 0) return false;
35
+ const edits = Array.isArray(input.edits) ? input.edits : [input];
36
+ return edits.some((one) => typeof one?.old_string === "string" && one.old_string !== "" && touchesRegion(text, lf(one.old_string), regions));
37
+ }
38
+
39
+ /** The verdict on one edit. @returns the hook output, or null to let the call run with no message. */
40
+ export function decide(call) {
41
+ const input = call.tool_input ?? {};
42
+ if (!EDIT_TOOLS.has(call.tool_name) || typeof input.file_path !== "string" || input.file_path === "") return null;
43
+ const file = path.resolve(call.cwd ?? process.cwd(), input.file_path);
44
+ const root = checkoutRootOf(path.dirname(file));
45
+ if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
46
+
47
+ let generated;
48
+ try {
49
+ generated = load(root).generated;
50
+ } catch {
51
+ // A config error is the edit guard's to name; this guard judges the path alone.
52
+ return null;
53
+ }
54
+ const rel = path.relative(root, file).split(path.sep).join("/");
55
+ const rerun = `Change its source, then run \`${generated.command}\`.`;
56
+ if (globMatcher(generated.globs)(rel)) {
57
+ return deny(`Generated-file guard: ${rel} is generated. ${rerun}`);
58
+ }
59
+ if (call.tool_name !== "Write" && MARKDOWN.test(rel) && editsRegion(file, input)) {
60
+ return deny(`Generated-file guard: the edit changes the generated region of ${rel}. ${rerun}`);
61
+ }
62
+ return null;
63
+ }
64
+
65
+ async function readStdin() {
66
+ let data = "";
67
+ for await (const chunk of process.stdin) data += chunk;
68
+ return data;
69
+ }
70
+
71
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
72
+ if (isEntryPoint) {
73
+ let call = null;
74
+ try {
75
+ call = JSON.parse(await readStdin());
76
+ } catch {
77
+ // Not hook input, so there is nothing to judge.
78
+ }
79
+ const output = call ? decide(call) : null;
80
+ if (output) process.stdout.write(JSON.stringify(output));
81
+ }
@@ -0,0 +1,104 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+ import { decide } from "./generated-file-guard.mjs";
9
+
10
+ const GUARD = fileURLToPath(new URL("./generated-file-guard.mjs", import.meta.url));
11
+
12
+ const ENFORCEMENT = [
13
+ "# Enforcement",
14
+ "",
15
+ "Hand-written intro.",
16
+ "",
17
+ "<!-- generated: rule-to-check. pnpm codegen. -->",
18
+ "",
19
+ "| Rule | Check |",
20
+ "| A comment is one line | `qc/comment-style` |",
21
+ "",
22
+ "<!-- /generated -->",
23
+ "",
24
+ "Hand-written judgement calls.",
25
+ "",
26
+ ].join("\n");
27
+
28
+ /** A checkout with the given config, holding a generated file, its source, and a doc with a generated region. */
29
+ function workspace(t, config = {}) {
30
+ const root = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-generated-")));
31
+ t.after(() => rmSync(root, { recursive: true, force: true }));
32
+ execFileSync("git", ["init", "-q"], { cwd: root, stdio: "pipe" });
33
+ if (config !== null) writeFileSync(path.join(root, "qc.config.json"), JSON.stringify(config));
34
+ for (const dir of ["src", "docs", "gen"]) mkdirSync(path.join(root, dir));
35
+ writeFileSync(path.join(root, "docs", "enforcement.md"), ENFORCEMENT);
36
+ writeFileSync(path.join(root, "docs", "crlf.md"), ENFORCEMENT.replace(/\n/g, "\r\n"));
37
+ return { root, at: (rel) => path.join(root, rel) };
38
+ }
39
+
40
+ const edit = (file, old_string, tool_input = {}) => ({
41
+ hook_event_name: "PreToolUse",
42
+ tool_name: "Edit",
43
+ cwd: path.dirname(file),
44
+ tool_input: { file_path: file, old_string, new_string: "x", ...tool_input },
45
+ });
46
+ const write = (file) => ({ ...edit(file, ""), tool_name: "Write", tool_input: { file_path: file, content: "x" } });
47
+ const reasonOf = (output) => (output?.hookSpecificOutput?.permissionDecision === "deny" ? output.hookSpecificOutput.permissionDecisionReason : null);
48
+
49
+ test("an edit of a generated file is denied, and the reason names the command that writes it", (t) => {
50
+ const ws = workspace(t);
51
+ for (const call of [edit(ws.at("src/routes.generated.ts"), "a"), write(ws.at("src/routes.generated.ts"))]) {
52
+ const reason = reasonOf(decide(call));
53
+ assert.match(reason, /src\/routes\.generated\.ts is generated/);
54
+ assert.match(reason, /`pnpm codegen`/);
55
+ }
56
+ });
57
+
58
+ test("a generated file at the repository root is denied too", (t) => {
59
+ const ws = workspace(t);
60
+ assert.match(reasonOf(decide(write(ws.at("routes.generated.ts")))), /routes\.generated\.ts is generated/);
61
+ });
62
+
63
+ test("an edit of the generated file's source passes", (t) => {
64
+ const ws = workspace(t);
65
+ assert.equal(decide(edit(ws.at("src/routes.ts"), "a")), null);
66
+ assert.equal(decide(write(ws.at("src/routes.ts"))), null);
67
+ });
68
+
69
+ test("generated.globs and generated.command in qc.config.json replace the defaults", (t) => {
70
+ const ws = workspace(t, { generated: { globs: ["gen/**"], command: "npm run gen" } });
71
+ assert.match(reasonOf(decide(write(ws.at("gen/a.ts")))), /`npm run gen`/);
72
+ assert.equal(decide(write(ws.at("src/routes.generated.ts"))), null);
73
+ });
74
+
75
+ test("an edit whose old_string lies in or across a generated region is denied", (t) => {
76
+ const ws = workspace(t);
77
+ const doc = ws.at("docs/enforcement.md");
78
+ assert.match(reasonOf(decide(edit(doc, "| A comment is one line | `qc/comment-style` |"))), /generated region of docs\/enforcement\.md/);
79
+ assert.ok(reasonOf(decide(edit(doc, "Hand-written intro.\n\n<!-- generated: rule-to-check."))));
80
+ assert.ok(reasonOf(decide(edit(ws.at("docs/crlf.md"), "| Rule | Check |\n| A comment"))));
81
+ const multi = {
82
+ tool_name: "MultiEdit",
83
+ tool_input: { file_path: doc, edits: [{ old_string: "Hand-written intro." }, { old_string: "| Rule | Check |" }] },
84
+ };
85
+ assert.ok(reasonOf(decide({ ...edit(doc, ""), ...multi })));
86
+ });
87
+
88
+ test("an edit outside the generated region passes", (t) => {
89
+ const ws = workspace(t);
90
+ assert.equal(decide(edit(ws.at("docs/enforcement.md"), "Hand-written judgement calls.")), null);
91
+ assert.equal(decide(edit(ws.at("docs/enforcement.md"), "Hand-written intro.", { replace_all: true })), null);
92
+ });
93
+
94
+ test("a repository with no qc.config.json is never guarded", (t) => {
95
+ const ws = workspace(t, null);
96
+ assert.equal(decide(write(ws.at("src/routes.generated.ts"))), null);
97
+ });
98
+
99
+ test("the hook process prints the deny", (t) => {
100
+ const ws = workspace(t);
101
+ const result = spawnSync(process.execPath, [GUARD], { input: JSON.stringify(write(ws.at("src/a.generated.ts"))), encoding: "utf8" });
102
+ assert.equal(result.status, 0, result.stderr);
103
+ assert.equal(JSON.parse(result.stdout).hookSpecificOutput.permissionDecision, "deny");
104
+ });
@@ -0,0 +1,57 @@
1
+ // A fragment that reads a PowerShell command the way shell-command.mjs reads a POSIX one, for the
2
+ // Bash edit guard. It shares that parser and its git vocabulary, and an unknown name counts as a write.
3
+
4
+ import { GIT_READS, commandWords, gitCall, segmentsOf } from "./shell-command.mjs";
5
+
6
+ const DIALECT = { escape: "`" };
7
+ const NULL_DEVICES = new Set(["$null", "/dev/null", "nul"]);
8
+
9
+ /** Approved verbs that only read, and the cmdlets and aliases that only read or print. */
10
+ const READ_VERBS = new Set([
11
+ "get", "test", "select", "measure", "format", "compare", "find", "resolve", "convertto",
12
+ "convertfrom", "sort", "group", "where", "join", "split",
13
+ ]);
14
+ const READ_NAMES = new Set([
15
+ "write-output", "write-host", "out-null", "out-string", "out-host", "ls", "dir", "gci", "cat",
16
+ "gc", "type", "sls", "select", "where", "?", "sort", "measure", "pwd", "gl", "echo", "write",
17
+ "gi", "gp", "gcm", "gm", "ft", "fl", "popd", "pop-location",
18
+ ]);
19
+ const LOCATION_NAMES = new Set(["cd", "chdir", "sl", "set-location", "pushd", "push-location"]);
20
+ const PATH_PARAMETERS = new Set(["-path", "-literalpath"]);
21
+
22
+ /** @returns the directory a location change moves to, or null when the segment is none. */
23
+ function locationTarget(segment) {
24
+ const [program, ...args] = commandWords(segment);
25
+ if (!LOCATION_NAMES.has(program?.toLowerCase())) return null;
26
+ for (let i = 0; i < args.length; i++) {
27
+ if (PATH_PARAMETERS.has(args[i].toLowerCase())) return args[i + 1] ?? "~";
28
+ if (!args[i].startsWith("-")) return args[i];
29
+ }
30
+ return "~";
31
+ }
32
+
33
+ function isReadOnly(segment) {
34
+ if (segment.redirects.some((file) => !NULL_DEVICES.has(file.toLowerCase()))) return false;
35
+ // A script block can hold any command, so a segment that carries one is judged a write.
36
+ if (segment.words.some((word) => word.includes("{"))) return false;
37
+ if (locationTarget(segment) !== null) return true;
38
+ const git = gitCall(segment);
39
+ if (git) return GIT_READS.has(git.sub);
40
+ const name = commandWords(segment)[0]?.toLowerCase() ?? "";
41
+ const [verb, noun] = name.split("-");
42
+ return READ_NAMES.has(name) || (noun !== undefined && READ_VERBS.has(verb));
43
+ }
44
+
45
+ /** False only when every segment is known to read, so an unknown command counts as a write. */
46
+ export const mayWrite = (command) => !segmentsOf(command, DIALECT).every(isReadOnly);
47
+
48
+ /** Every directory the command names through a location change or `git -C`, in order, as written. */
49
+ export function checkoutDirs(command) {
50
+ const dirs = [];
51
+ for (const segment of segmentsOf(command, DIALECT)) {
52
+ const target = locationTarget(segment);
53
+ if (target !== null) dirs.push(target);
54
+ dirs.push(...(gitCall(segment)?.dirs ?? []).filter(Boolean));
55
+ }
56
+ return dirs;
57
+ }
@@ -0,0 +1,52 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { checkoutDirs, mayWrite } from "./powershell-command.mjs";
4
+
5
+ test("a PowerShell command that only reads skips the check, in any letter case", () => {
6
+ for (const command of [
7
+ "Get-ChildItem -Recurse src",
8
+ "get-content a.txt | select-string foo",
9
+ "Test-Path C:\\repo\\a.txt",
10
+ "Get-Content a.txt | Measure-Object -Line",
11
+ "Get-Process | Format-Table Name",
12
+ "Write-Output done",
13
+ 'git status; git diff --stat; git log --oneline -5',
14
+ "Get-Date > $null",
15
+ "Get-Item x 2>$null",
16
+ "Set-Location C:\\repo; Get-Location",
17
+ "ls; cat a.txt; pwd",
18
+ ]) {
19
+ assert.equal(mayWrite(command), false, command);
20
+ }
21
+ });
22
+
23
+ test("a PowerShell write, an unknown command and a script block are never skipped", () => {
24
+ for (const command of [
25
+ "Set-Content a.txt x",
26
+ "Add-Content a.txt x",
27
+ "Get-Content a.txt | Out-File b.txt",
28
+ "Get-Date > C:\\repo\\d.txt",
29
+ "Write-Output x >> log.txt",
30
+ "New-Item -ItemType File a.txt",
31
+ "Copy-Item a b",
32
+ "Move-Item a b",
33
+ "Remove-Item -Recurse -Force build",
34
+ "Rename-Item a b",
35
+ 'git commit -m "x"',
36
+ "git checkout main -- src",
37
+ "node scripts/codemod.mjs",
38
+ "Get-ChildItem | Where-Object { Remove-Item $_ }",
39
+ "Get-ChildItem | ForEach-Object Name",
40
+ "& C:\\tools\\fix.ps1",
41
+ ]) {
42
+ assert.equal(mayWrite(command), true, command);
43
+ }
44
+ });
45
+
46
+ test("the checkout directories are each location change and each git -C directory, with backslashes kept", () => {
47
+ assert.deepEqual(
48
+ checkoutDirs('Set-Location C:\\repo\\a; git -C "C:\\b c" status; cd ..\\d; Push-Location -Path C:\\e; popd'),
49
+ ["C:\\repo\\a", "C:\\b c", "..\\d", "C:\\e"],
50
+ );
51
+ assert.deepEqual(checkoutDirs("Get-ChildItem"), []);
52
+ });
@@ -5,17 +5,13 @@ import { execFile } from "node:child_process";
5
5
  import { readdir, stat } from "node:fs/promises";
6
6
  import path from "node:path";
7
7
  import { promisify } from "node:util";
8
- import { globToRegExp } from "../glob.mjs";
8
+ import { globMatcher } from "../glob.mjs";
9
9
 
10
10
  const execFileAsync = promisify(execFile);
11
11
  // The execFile default is 1 MB. A 30,000-file repository lists about 2 MB of paths.
12
12
  const MAX_BUFFER = 256 * 1024 * 1024;
13
13
 
14
- /** A leading `**` also matches at the root, as ESLint reads the same `ignores`. */
15
- function ignoredBy(globs) {
16
- const patterns = globs.map(globToRegExp);
17
- return (rel) => patterns.some((pattern) => pattern.test(rel) || pattern.test(`/${rel}`));
18
- }
14
+ const ignoredBy = globMatcher;
19
15
 
20
16
  // `-t` tags each entry. `R` is a tracked file gone from the working tree and `S` is skip-worktree, so neither is on disk.
21
17
  const NOT_ON_DISK = new Set(["R", "S"]);
@@ -25,8 +25,13 @@ function skipHeredocs(command, start, heredocs) {
25
25
  return i;
26
26
  }
27
27
 
28
- /** @returns {Segment[]} the segments between unquoted `;`, `&`, `&&`, `|`, `||`, parentheses and newlines. */
29
- export function segmentsOf(command) {
28
+ const POSIX_ESCAPE = "\\";
29
+
30
+ /**
31
+ * @param dialect `escape` is the escape character: a backslash for a POSIX shell, a backtick for PowerShell.
32
+ * @returns {Segment[]} the segments between unquoted `;`, `&`, `&&`, `|`, `||`, parentheses and newlines.
33
+ */
34
+ export function segmentsOf(command, { escape = POSIX_ESCAPE } = {}) {
30
35
  const segments = [];
31
36
  let words = [];
32
37
  let redirects = [];
@@ -61,7 +66,8 @@ export function segmentsOf(command) {
61
66
  i++;
62
67
  } else if (quote === '"') {
63
68
  // Inside double quotes a backslash escapes only these, so a Windows path keeps its separators.
64
- if (c === "\\" && next !== undefined && '$`"\\\n'.includes(next)) {
69
+ // A backtick escapes any character.
70
+ if (c === escape && next !== undefined && (escape !== POSIX_ESCAPE || '$`"\\\n'.includes(next))) {
65
71
  word += next;
66
72
  i += 2;
67
73
  } else {
@@ -73,7 +79,7 @@ export function segmentsOf(command) {
73
79
  quote = c;
74
80
  inWord = true;
75
81
  i++;
76
- } else if (c === "\\") {
82
+ } else if (c === escape) {
77
83
  if (next !== "\n") word += next ?? "";
78
84
  inWord = next !== "\n" || inWord;
79
85
  i += 2;
@@ -144,25 +150,29 @@ export function segmentsOf(command) {
144
150
  const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
145
151
 
146
152
  /** The words after any leading `NAME=value` assignments. */
147
- const commandWords = (segment) => {
153
+ export const commandWords = (segment) => {
148
154
  const start = segment.words.findIndex((word) => !ASSIGNMENT.test(word));
149
155
  return start === -1 ? [] : segment.words.slice(start);
150
156
  };
151
157
 
152
- const isGit = (word) => /(^|[\\/])git(\.exe)?$/.test(word ?? "");
158
+ const isGit = (word) => /(^|[\\/])git(\.exe)?$/i.test(word ?? "");
153
159
 
154
- /** @returns the git subcommand and each `-C` directory, or null when the segment is no git call. */
160
+ /**
161
+ * @returns the git subcommand, each `-C` directory, each `-c` setting and the words after the
162
+ * subcommand, or null when the segment is no git call.
163
+ */
155
164
  export function gitCall(segment) {
156
- const [program, ...args] = commandWords(segment);
165
+ const [program, ...words] = commandWords(segment);
157
166
  if (!isGit(program)) return null;
158
167
  const dirs = [];
159
- for (let i = 0; i < args.length; i++) {
160
- const arg = args[i];
161
- if (arg === "-C") dirs.push(args[++i]);
162
- else if (arg === "-c") i++;
163
- else if (!arg.startsWith("-")) return { sub: arg, dirs };
168
+ const configs = [];
169
+ for (let i = 0; i < words.length; i++) {
170
+ const word = words[i];
171
+ if (word === "-C") dirs.push(words[++i]);
172
+ else if (word === "-c") configs.push(words[++i]);
173
+ else if (!word.startsWith("-")) return { sub: word, dirs, configs, args: words.slice(i + 1) };
164
174
  }
165
- return { sub: null, dirs };
175
+ return { sub: null, dirs, configs, args: [] };
166
176
  }
167
177
 
168
178
  /** @returns the directory a `cd` or `pushd` segment moves to, or null. */
@@ -176,7 +186,7 @@ const READ_PROGRAMS = new Set([
176
186
  "cut", "tr", "jq", "which", "type", "stat", "file", "du", "df", "date", "basename",
177
187
  "dirname", "realpath", "readlink", "diff", "cmp", "true", "false", "test", "[", "popd",
178
188
  ]);
179
- const GIT_READS = new Set([
189
+ export const GIT_READS = new Set([
180
190
  "status", "diff", "log", "show", "rev-parse", "ls-files", "grep", "blame", "branch", "remote",
181
191
  "fetch", "describe", "shortlog", "config",
182
192
  ]);
@@ -34,7 +34,7 @@ test("a redirect target is recorded apart from the words, and a descriptor copy
34
34
 
35
35
  test("a git call names its subcommand and every -C directory", () => {
36
36
  const [segment] = segmentsOf(`GIT_PAGER=cat git -C "C:/a b" -c core.x=y --no-pager commit -m x`);
37
- assert.deepEqual(gitCall(segment), { sub: "commit", dirs: ["C:/a b"] });
37
+ assert.deepEqual(gitCall(segment), { sub: "commit", dirs: ["C:/a b"], configs: ["core.x=y"], args: ["-m", "x"] });
38
38
  assert.equal(gitCall(segmentsOf("gitk --all")[0]), null);
39
39
  });
40
40
 
@@ -93,3 +93,26 @@ test("the checkout directories are every cd target and every git -C directory, i
93
93
  ]);
94
94
  assert.deepEqual(checkoutDirs("ls"), []);
95
95
  });
96
+
97
+ test("a git call carries each -c setting and the words after its subcommand", () => {
98
+ const [segment] = segmentsOf(`git -c core.hooksPath=/dev/null -C repo commit -m "a b" --no-verify`);
99
+ assert.deepEqual(gitCall(segment), {
100
+ sub: "commit",
101
+ dirs: ["repo"],
102
+ configs: ["core.hooksPath=/dev/null"],
103
+ args: ["-m", "a b", "--no-verify"],
104
+ });
105
+ assert.deepEqual(gitCall(segmentsOf("git --version")[0]), { sub: null, dirs: [], configs: [], args: [] });
106
+ });
107
+
108
+ test("the PowerShell escape keeps a backslash literal and escapes with a backtick", () => {
109
+ const powershell = { escape: "`" };
110
+ assert.deepEqual(
111
+ segmentsOf('Set-Content C:\\a\\b.txt "x`"y" ; Get-Item `$HOME', powershell).map((segment) => segment.words),
112
+ [
113
+ ["Set-Content", "C:\\a\\b.txt", 'x"y'],
114
+ ["Get-Item", "$HOME"],
115
+ ],
116
+ );
117
+ assert.deepEqual(segmentsOf("Get-Date > C:\\out\\d.txt", powershell)[0].redirects, ["C:\\out\\d.txt"]);
118
+ });
package/src/config.mjs CHANGED
@@ -210,6 +210,9 @@ export const defaults = {
210
210
  toolCallBudget: 100,
211
211
  },
212
212
 
213
+ // Files a generator writes. The generated-file hook refuses a hand edit of one and names `command`.
214
+ generated: { globs: ["**/*.generated.*"], command: "pnpm codegen" },
215
+
213
216
  // `qc worktree`. `install` runs in each new worktree. `base` is the default `--from`: the ref a
214
217
  // branch starts at, and the ref `remove` checks a merge against.
215
218
  worktree: { install: "pnpm install --frozen-lockfile", base: "origin/main" },
@@ -3,9 +3,10 @@
3
3
  import { enabled } from "./config.mjs";
4
4
  import { gateDescriptions } from "./descriptions.mjs";
5
5
  import { rules } from "./eslint/index.mjs";
6
+ import { GENERATED_CLOSE } from "./generated-markers.mjs";
6
7
 
7
8
  export const OPEN = "<!-- generated: rule-to-check. -->";
8
- export const CLOSE = "<!-- /generated -->";
9
+ export const CLOSE = GENERATED_CLOSE;
9
10
  // A repository may annotate the open marker with its own reminder (e.g. "pnpm codegen.") —
10
11
  // matched by prefix, not by exact string, so that annotation does not break detection.
11
12
  const OPEN_PATTERN = /<!--\s*generated:\s*rule-to-check\.[^>]*-->/;
@@ -0,0 +1,16 @@
1
+ // A fragment: the markers around a generated region of a Markdown file. The enforcement map writes its
2
+ // table between them, and the generated-file guard refuses a hand edit inside them.
3
+
4
+ export const GENERATED_CLOSE = "<!-- /generated -->";
5
+ const GENERATED_OPEN = /<!--\s*generated:[^>]*-->/g;
6
+
7
+ /** @returns each generated region as `[start, end)`, from its open marker through its close marker or the end. */
8
+ export function generatedRegions(markdown) {
9
+ const regions = [];
10
+ for (const found of markdown.matchAll(GENERATED_OPEN)) {
11
+ const close = markdown.indexOf(GENERATED_CLOSE, found.index);
12
+ const end = close === -1 ? markdown.length : close + GENERATED_CLOSE.length;
13
+ if (regions.length === 0 || found.index >= regions.at(-1)[1]) regions.push([found.index, end]);
14
+ }
15
+ return regions;
16
+ }
package/src/glob.mjs CHANGED
@@ -10,3 +10,14 @@ export function globToRegExp(glob) {
10
10
  .replace(/\u0000/g, ".*");
11
11
  return new RegExp(`^${body}$`);
12
12
  }
13
+
14
+ /**
15
+ * A matcher for a list of globs over repository-relative paths. A leading `**` also matches at the
16
+ * root, as ESLint reads the same globs: `**\/*.generated.*` matches `a.generated.ts` and `src/a.generated.ts`.
17
+ * @param {readonly string[]} globs
18
+ * @returns {(rel: string) => boolean}
19
+ */
20
+ export function globMatcher(globs) {
21
+ const patterns = globs.map(globToRegExp);
22
+ return (rel) => patterns.some((pattern) => pattern.test(rel) || pattern.test(`/${rel}`));
23
+ }