architecture-harness 0.7.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.
Files changed (43) hide show
  1. package/package.json +1 -1
  2. package/src/cli/bash-command-guard.mjs +129 -0
  3. package/src/cli/bash-command-guard.test.mjs +96 -0
  4. package/src/cli/bash-edit-guard.mjs +163 -0
  5. package/src/cli/bash-edit-guard.test.mjs +114 -0
  6. package/src/cli/budget-counter.mjs +40 -0
  7. package/src/cli/budget-counter.test.mjs +35 -0
  8. package/src/cli/budget-guard.mjs +56 -0
  9. package/src/cli/budget-guard.test.mjs +90 -0
  10. package/src/cli/budget.mjs +74 -0
  11. package/src/cli/budget.test.mjs +79 -0
  12. package/src/cli/check.mjs +197 -174
  13. package/src/cli/checkout-root.mjs +16 -0
  14. package/src/cli/cli.test.mjs +79 -0
  15. package/src/cli/decisions.mjs +5 -6
  16. package/src/cli/edit-batch-guard.mjs +77 -0
  17. package/src/cli/edit-batch-guard.test.mjs +131 -0
  18. package/src/cli/edit-batch-state.mjs +57 -0
  19. package/src/cli/generated-file-guard.mjs +81 -0
  20. package/src/cli/generated-file-guard.test.mjs +104 -0
  21. package/src/cli/ignored-paths.mjs +29 -0
  22. package/src/cli/ignored-paths.test.mjs +44 -0
  23. package/src/cli/powershell-command.mjs +57 -0
  24. package/src/cli/powershell-command.test.mjs +52 -0
  25. package/src/cli/qc.mjs +10 -2
  26. package/src/cli/repo-files.mjs +65 -0
  27. package/src/cli/repo-files.test.mjs +78 -0
  28. package/src/cli/shell-command.mjs +221 -0
  29. package/src/cli/shell-command.test.mjs +118 -0
  30. package/src/cli/work-order-guard.mjs +19 -21
  31. package/src/cli/work-order-guard.test.mjs +18 -0
  32. package/src/cli/work-order-manifest.mjs +14 -0
  33. package/src/cli/worktree-isolation.mjs +3 -1
  34. package/src/cli/worktree-isolation.test.mjs +13 -0
  35. package/src/cli/worktree.mjs +145 -0
  36. package/src/cli/worktree.test.mjs +110 -0
  37. package/src/config.mjs +9 -0
  38. package/src/enforcement-map.mjs +2 -1
  39. package/src/gates/english-source.mjs +13 -9
  40. package/src/gates/english-source.test.mjs +19 -1
  41. package/src/generated-markers.mjs +16 -0
  42. package/src/glob.mjs +23 -0
  43. package/templates/CLAUDE.md +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.7.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
+ });
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env node
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
+
6
+ import { execFile } from "node:child_process";
7
+ import { existsSync, realpathSync } from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import { promisify } from "node:util";
12
+ import { load } from "../config.mjs";
13
+ import { checkoutRootOf } from "./checkout-root.mjs";
14
+ import { ignoredPaths } from "./ignored-paths.mjs";
15
+ import * as powershell from "./powershell-command.mjs";
16
+ import * as posix from "./shell-command.mjs";
17
+ import { isAllowed } from "./work-order-guard.mjs";
18
+ import { MANIFEST_FILE, readManifest } from "./work-order-manifest.mjs";
19
+ import { OFF, isolationSettings } from "./worktree-isolation.mjs";
20
+
21
+ const execFileAsync = promisify(execFile);
22
+ const slashed = (file) => file.split(path.sep).join("/");
23
+ const MAX_LISTED = 40;
24
+
25
+ /** The paths `git status --porcelain -z` names, with both sides of a rename. */
26
+ export function changedPaths(porcelain) {
27
+ const fields = porcelain.split("\u0000");
28
+ const paths = [];
29
+ for (let i = 0; i < fields.length; i++) {
30
+ const entry = fields[i];
31
+ if (entry.length < 4) continue;
32
+ paths.push(entry.slice(3));
33
+ if (entry[0] === "R") paths.push(fields[++i]);
34
+ else if (entry[0] === "C") i++;
35
+ }
36
+ return paths.filter(Boolean);
37
+ }
38
+
39
+ const native = (dir) => {
40
+ try {
41
+ return realpathSync.native(dir);
42
+ } catch {
43
+ return null;
44
+ }
45
+ };
46
+
47
+ /** A directory as the command wrote it, resolved the way the shell would, or null when it does not exist. */
48
+ function resolveDir(cwd, dir) {
49
+ let spelled = dir.replace(/^~(?=$|[\\/])/, os.homedir());
50
+ if (process.platform === "win32") spelled = spelled.replace(/^\/([A-Za-z])(?=\/|$)/, "$1:");
51
+ const absolute = path.resolve(cwd, spelled);
52
+ return existsSync(absolute) ? absolute : null;
53
+ }
54
+
55
+ /** Every distinct checkout the command could have changed: its cwd, and each `cd` and `git -C` directory. */
56
+ function checkoutsOf(cwd, command, dialect) {
57
+ const roots = new Set();
58
+ for (const dir of [cwd, ...dialect.checkoutDirs(command).map((d) => resolveDir(cwd, d))]) {
59
+ const root = dir && checkoutRootOf(dir);
60
+ const real = root && native(root);
61
+ if (real) roots.add(real);
62
+ }
63
+ return [...roots];
64
+ }
65
+
66
+ async function gitFacts(root) {
67
+ const run = async (...args) => (await execFileAsync("git", args, { cwd: root, maxBuffer: 64 * 1024 * 1024 })).stdout;
68
+ const [status, branch] = await Promise.all([
69
+ run("status", "--porcelain", "-z", "--untracked-files=all"),
70
+ run("branch", "--show-current"),
71
+ ]);
72
+ return { changed: changedPaths(status), branch: branch.trim() };
73
+ }
74
+
75
+ /** @returns each changed path in one checkout that breaks a rule, with the rules it breaks. */
76
+ async function findingsIn(root, manifest, projectRoot) {
77
+ let settings = null;
78
+ try {
79
+ settings = isolationSettings(load(root).swarm);
80
+ } catch {
81
+ // A config error is the edit guard's to name; this guard judges the declaration alone.
82
+ }
83
+ const guardsBranch = settings !== null && settings.require !== OFF;
84
+ if (!manifest && !guardsBranch) return [];
85
+
86
+ let facts;
87
+ try {
88
+ facts = await gitFacts(root);
89
+ } catch {
90
+ return [];
91
+ }
92
+ const rules = new Map();
93
+ const add = (rel, rule) => rules.set(rel, [...(rules.get(rel) ?? []), rule]);
94
+
95
+ const patterns = manifest?.paths ?? [];
96
+ for (const rel of facts.changed) {
97
+ if (!isAllowed(slashed(path.relative(projectRoot, path.join(root, rel))), patterns)) {
98
+ add(rel, `outside the work order's declared paths (${MANIFEST_FILE}: ${patterns.join(", ")})`);
99
+ }
100
+ }
101
+ if (guardsBranch && settings.protectedBranches.includes(facts.branch)) {
102
+ const candidates = facts.changed.filter((rel) => !(settings.allow.length > 0 && isAllowed(rel, settings.allow)));
103
+ const ignored = await ignoredPaths(root, candidates);
104
+ for (const rel of candidates) {
105
+ if (!ignored.has(rel)) add(rel, `changed on the protected branch "${facts.branch}"`);
106
+ }
107
+ }
108
+ return [...rules].map(([rel, broken]) => `${slashed(root)}/${rel}: ${broken.join("; ")}`);
109
+ }
110
+
111
+ /**
112
+ * The report on one finished Bash call. @param projectRoot the folder that holds the work-order manifest
113
+ * @returns PostToolUse output with model-visible context, or null when nothing breaks a rule
114
+ */
115
+ export async function report(call, projectRoot) {
116
+ const command = call.tool_input?.command;
117
+ const dialect = call.tool_name === "PowerShell" ? powershell : posix;
118
+ if (typeof command !== "string" || !dialect.mayWrite(command)) return null;
119
+ const cwd = call.cwd ?? process.cwd();
120
+ const project = native(projectRoot) ?? projectRoot;
121
+
122
+ let manifest = null;
123
+ try {
124
+ manifest = readManifest(project);
125
+ } catch {
126
+ // The edit guard names a manifest that does not parse.
127
+ }
128
+ const findings = [];
129
+ for (const root of checkoutsOf(cwd, command, dialect)) findings.push(...(await findingsIn(root, manifest, project)));
130
+ if (findings.length === 0) return null;
131
+
132
+ const listed = findings.slice(0, MAX_LISTED).map((line) => `- ${line}`);
133
+ if (findings.length > MAX_LISTED) listed.push(`- and ${findings.length - MAX_LISTED} more`);
134
+ return {
135
+ hookSpecificOutput: {
136
+ hookEventName: "PostToolUse",
137
+ additionalContext: [
138
+ "Bash edit guard: the checkout holds uncommitted changes that the swarm rules do not allow.",
139
+ ...listed,
140
+ "Revert a change only if your work order made it and should not have. " +
141
+ "For any other change, stop and tell the orchestrator. The guard does not revert anything.",
142
+ ].join("\n"),
143
+ },
144
+ };
145
+ }
146
+
147
+ async function readStdin() {
148
+ let data = "";
149
+ for await (const chunk of process.stdin) data += chunk;
150
+ return data;
151
+ }
152
+
153
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
154
+ if (isEntryPoint) {
155
+ let call = null;
156
+ try {
157
+ call = JSON.parse(await readStdin());
158
+ } catch {
159
+ // Not hook input, so there is no command to judge.
160
+ }
161
+ const output = call ? await report(call, process.env.CLAUDE_PROJECT_DIR ?? process.cwd()) : null;
162
+ if (output) process.stdout.write(JSON.stringify(output));
163
+ }
@@ -0,0 +1,114 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync } 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 { changedPaths, report } from "./bash-edit-guard.mjs";
8
+
9
+ /**
10
+ * A primary checkout on main that turns isolation on, a linked worktree whose work order declares
11
+ * `src/**`, a checkout with no config, and a folder in no checkout.
12
+ */
13
+ function workspace(t) {
14
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-bash-guard-")));
15
+ t.after(() => rmSync(base, { recursive: true, force: true }));
16
+ const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe" });
17
+ const primary = path.join(base, "primary");
18
+ const linked = path.join(base, "linked");
19
+ const plain = path.join(base, "plain");
20
+ const outside = path.join(base, "outside");
21
+ for (const dir of [primary, plain, outside]) mkdirSync(dir);
22
+ git(primary, "init", "-q", "-b", "main");
23
+ writeFileSync(path.join(primary, "qc.config.json"), JSON.stringify({ swarm: { isolation: { require: "branch" } } }));
24
+ writeFileSync(path.join(primary, ".gitignore"), "*.local.json\n");
25
+ git(primary, "add", ".");
26
+ git(primary, "-c", "user.name=qc", "-c", "user.email=qc@example.com", "commit", "-q", "-m", "init");
27
+ git(primary, "worktree", "add", "-q", linked, "-b", "feat/work-order");
28
+ mkdirSync(path.join(linked, ".claude"));
29
+ writeFileSync(path.join(linked, ".claude", "work-order.local.json"), JSON.stringify({ paths: ["src/**"] }));
30
+ git(plain, "init", "-q", "-b", "main");
31
+ const put = (root, rel) => {
32
+ mkdirSync(path.dirname(path.join(root, rel)), { recursive: true });
33
+ writeFileSync(path.join(root, rel), "changed\n");
34
+ };
35
+ return { primary, linked, plain, outside, put };
36
+ }
37
+
38
+ const bash = (cwd, command) => ({ hook_event_name: "PostToolUse", tool_name: "Bash", cwd, tool_input: { command } });
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
+ });
56
+
57
+ test("a write inside the work order's declared paths is silent", async (t) => {
58
+ const ws = workspace(t);
59
+ ws.put(ws.linked, "src/a.ts");
60
+ assert.equal(await report(bash(ws.linked, "node scripts/codemod.mjs"), ws.linked), null);
61
+ });
62
+
63
+ test("a write outside the declared paths is reported with the path and the rule, as model-visible context", async (t) => {
64
+ const ws = workspace(t);
65
+ ws.put(ws.linked, "src/a.ts");
66
+ ws.put(ws.linked, "docs/b.md");
67
+ const output = await report(bash(ws.linked, "sed -i 's/a/b/' docs/b.md"), ws.linked);
68
+ assert.equal(output.hookSpecificOutput.hookEventName, "PostToolUse");
69
+ const text = contextOf(output);
70
+ assert.match(text, /docs\/b\.md/);
71
+ assert.doesNotMatch(text, /src\/a\.ts/);
72
+ assert.match(text, /work-order\.local\.json/);
73
+ assert.match(text, /src\/\*\*/);
74
+ assert.match(text, /does not revert/);
75
+ // Status also lists changes made before the command, in a checkout other sessions can share.
76
+ assert.match(text, /uncommitted changes/);
77
+ assert.match(text, /only if your work order made it/);
78
+ assert.match(text, /stop and tell the orchestrator/);
79
+ });
80
+
81
+ test("a change on a protected branch is reported with no work order, and an ignored file is not", async (t) => {
82
+ const ws = workspace(t);
83
+ ws.put(ws.primary, "src/a.ts");
84
+ ws.put(ws.primary, ".claude/settings.local.json");
85
+ const text = contextOf(await report(bash(ws.primary, "python fix.py"), ws.primary));
86
+ assert.match(text, /src\/a\.ts/);
87
+ assert.match(text, /protected branch "main"/);
88
+ assert.doesNotMatch(text, /settings\.local\.json/);
89
+ });
90
+
91
+ test("a read-only command is skipped, even with an out-of-scope change in the checkout", async (t) => {
92
+ const ws = workspace(t);
93
+ ws.put(ws.linked, "docs/b.md");
94
+ assert.equal(await report(bash(ws.linked, "git status && cat docs/b.md | grep x"), ws.linked), null);
95
+ });
96
+
97
+ test("git -C names the checkout the command changed, whatever the session's directory", async (t) => {
98
+ const ws = workspace(t);
99
+ ws.put(ws.primary, "src/a.ts");
100
+ const text = contextOf(await report(bash(ws.outside, `git -C "${ws.primary}" apply fix.patch`), ws.outside));
101
+ assert.match(text, /src\/a\.ts/);
102
+ assert.match(text, /protected branch "main"/);
103
+ });
104
+
105
+ test("a checkout with no isolation and no work order is silent", async (t) => {
106
+ const ws = workspace(t);
107
+ ws.put(ws.plain, "src/a.ts");
108
+ assert.equal(await report(bash(ws.plain, "node x.mjs"), ws.plain), null);
109
+ });
110
+
111
+ test("porcelain output names each changed path, and both sides of a rename", () => {
112
+ const status = [" M src/a.ts", "?? docs/new file.md", "R lib/new.ts", "lib/old.ts", ""].join("\u0000");
113
+ assert.deepEqual(changedPaths(status), ["src/a.ts", "docs/new file.md", "lib/new.ts", "lib/old.ts"]);
114
+ });
@@ -0,0 +1,40 @@
1
+ // The resource for the tool-call counters: one small JSON file per agent, under the OS temp folder.
2
+ // It holds no transcript and no tool input, only a number, and a lost file only restarts a count.
3
+
4
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
+ import path from "node:path";
6
+
7
+ const fileSafe = (id) => String(id).replace(/[^A-Za-z0-9_.-]/g, "_");
8
+
9
+ /** The counter file of one agent in one session. */
10
+ export const counterFileOf = (sessionId, agentId, tmp) =>
11
+ path.join(tmp, "architecture-kit", "budget", `${fileSafe(sessionId)}-${fileSafe(agentId)}.json`);
12
+
13
+ function readCount(file) {
14
+ try {
15
+ const { count } = JSON.parse(readFileSync(file, "utf8"));
16
+ return Number.isInteger(count) && count > 0 ? count : 0;
17
+ } catch {
18
+ return 0;
19
+ }
20
+ }
21
+
22
+ /** Adds one to the count and writes it through a rename. @returns the new count; throws on a write error. */
23
+ export function bumpCount(file, now = Date.now()) {
24
+ const count = readCount(file) + 1;
25
+ const temp = `${file}.${process.pid}.tmp`;
26
+ const payload = JSON.stringify({ count, updatedAt: new Date(now).toISOString() });
27
+ try {
28
+ writeFileSync(temp, payload);
29
+ } catch {
30
+ mkdirSync(path.dirname(file), { recursive: true });
31
+ writeFileSync(temp, payload);
32
+ }
33
+ try {
34
+ renameSync(temp, file);
35
+ } catch (error) {
36
+ rmSync(temp, { force: true });
37
+ throw error;
38
+ }
39
+ return count;
40
+ }
@@ -0,0 +1,35 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { bumpCount, counterFileOf } from "./budget-counter.mjs";
7
+
8
+ function tempDir(t) {
9
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-budget-counter-"));
10
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
11
+ return dir;
12
+ }
13
+
14
+ test("the counter file is keyed on the session and the agent, with file-safe names", () => {
15
+ assert.equal(
16
+ counterFileOf("sess/1", "agent:2", "/tmp"),
17
+ path.join("/tmp", "architecture-kit", "budget", "sess_1-agent_2.json"),
18
+ );
19
+ });
20
+
21
+ test("each bump adds one, and each agent keeps its own count", (t) => {
22
+ const tmp = tempDir(t);
23
+ const a = counterFileOf("s", "a", tmp);
24
+ const b = counterFileOf("s", "b", tmp);
25
+ assert.deepEqual([bumpCount(a), bumpCount(a), bumpCount(b), bumpCount(a)], [1, 2, 1, 3]);
26
+ assert.deepEqual(readdirSync(path.dirname(a)).sort(), ["s-a.json", "s-b.json"]);
27
+ });
28
+
29
+ test("a counter file that does not parse starts again at one", (t) => {
30
+ const tmp = tempDir(t);
31
+ const file = counterFileOf("s", "a", tmp);
32
+ mkdirSync(path.dirname(file), { recursive: true });
33
+ writeFileSync(file, "not json");
34
+ assert.equal(bumpCount(file), 1);
35
+ });
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ // The PreToolUse trigger for the tool-call budget of swarm.md. It runs on every call of every agent,
3
+ // so it spawns no process and touches one small file. The main session has no agent id and is exempt.
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, load } from "../config.mjs";
10
+ import { budgetOf, budgetVerdict } from "./budget.mjs";
11
+ import { bumpCount, counterFileOf } from "./budget-counter.mjs";
12
+ import { checkoutRootOf } from "./checkout-root.mjs";
13
+
14
+ const context = (text) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: text } });
15
+
16
+ /** The verdict on one tool call. @returns the hook output, or null to let the call run with no message. */
17
+ export function decide(call, tmp = os.tmpdir()) {
18
+ const agentId = call.agent_id;
19
+ if (typeof agentId !== "string" || agentId === "") return null;
20
+ const root = checkoutRootOf(call.cwd ?? process.cwd());
21
+ if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
22
+
23
+ let budget;
24
+ try {
25
+ budget = budgetOf(load(root).swarm);
26
+ } catch (error) {
27
+ // A config typo must not stop every agent; the agent sees the error and reports it.
28
+ return context(`Tool-call budget is off: ${error.message}`);
29
+ }
30
+ let count;
31
+ try {
32
+ count = bumpCount(counterFileOf(call.session_id ?? "session", agentId, tmp));
33
+ } catch {
34
+ // A busy or read-only temp folder is the hook's own problem, never a reason to stop the agent.
35
+ return null;
36
+ }
37
+ return budgetVerdict({ count, budget, call });
38
+ }
39
+
40
+ async function readStdin() {
41
+ let data = "";
42
+ for await (const chunk of process.stdin) data += chunk;
43
+ return data;
44
+ }
45
+
46
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
47
+ if (isEntryPoint) {
48
+ let call = null;
49
+ try {
50
+ call = JSON.parse(await readStdin());
51
+ } catch {
52
+ // Not hook input, so there is nothing to count.
53
+ }
54
+ const output = call ? decide(call) : null;
55
+ if (output) process.stdout.write(JSON.stringify(output));
56
+ }