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.
- package/package.json +1 -1
- package/src/cli/bash-command-guard.mjs +129 -0
- package/src/cli/bash-command-guard.test.mjs +96 -0
- package/src/cli/bash-edit-guard.mjs +163 -0
- package/src/cli/bash-edit-guard.test.mjs +114 -0
- package/src/cli/budget-counter.mjs +40 -0
- package/src/cli/budget-counter.test.mjs +35 -0
- package/src/cli/budget-guard.mjs +56 -0
- package/src/cli/budget-guard.test.mjs +90 -0
- package/src/cli/budget.mjs +74 -0
- package/src/cli/budget.test.mjs +79 -0
- package/src/cli/check.mjs +197 -174
- package/src/cli/checkout-root.mjs +16 -0
- package/src/cli/cli.test.mjs +79 -0
- package/src/cli/decisions.mjs +5 -6
- package/src/cli/edit-batch-guard.mjs +77 -0
- package/src/cli/edit-batch-guard.test.mjs +131 -0
- package/src/cli/edit-batch-state.mjs +57 -0
- package/src/cli/generated-file-guard.mjs +81 -0
- package/src/cli/generated-file-guard.test.mjs +104 -0
- package/src/cli/ignored-paths.mjs +29 -0
- package/src/cli/ignored-paths.test.mjs +44 -0
- package/src/cli/powershell-command.mjs +57 -0
- package/src/cli/powershell-command.test.mjs +52 -0
- package/src/cli/qc.mjs +10 -2
- package/src/cli/repo-files.mjs +65 -0
- package/src/cli/repo-files.test.mjs +78 -0
- package/src/cli/shell-command.mjs +221 -0
- package/src/cli/shell-command.test.mjs +118 -0
- package/src/cli/work-order-guard.mjs +19 -21
- package/src/cli/work-order-guard.test.mjs +18 -0
- package/src/cli/work-order-manifest.mjs +14 -0
- package/src/cli/worktree-isolation.mjs +3 -1
- package/src/cli/worktree-isolation.test.mjs +13 -0
- package/src/cli/worktree.mjs +145 -0
- package/src/cli/worktree.test.mjs +110 -0
- package/src/config.mjs +9 -0
- package/src/enforcement-map.mjs +2 -1
- package/src/gates/english-source.mjs +13 -9
- package/src/gates/english-source.test.mjs +19 -1
- package/src/generated-markers.mjs +16 -0
- package/src/glob.mjs +23 -0
- package/templates/CLAUDE.md +1 -1
package/src/cli/cli.test.mjs
CHANGED
|
@@ -155,6 +155,85 @@ test("check judges every configured mirror root, including a tests folder outsid
|
|
|
155
155
|
rmSync(dir, { recursive: true, force: true });
|
|
156
156
|
});
|
|
157
157
|
|
|
158
|
+
const ENGLISH_RULES = new Set(["english-comment", "english-source"]);
|
|
159
|
+
const englishPaths = (problems) => problems.filter((problem) => ENGLISH_RULES.has(problem.rule)).map((problem) => problem.path).sort();
|
|
160
|
+
|
|
161
|
+
function write(dir, files) {
|
|
162
|
+
for (const [file, contents] of Object.entries(files)) {
|
|
163
|
+
mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });
|
|
164
|
+
writeFileSync(path.join(dir, file), contents);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// The English gate is a policy gate, so the kit ships it off.
|
|
169
|
+
const ENGLISH_ON = JSON.stringify({ featureRoots: ["backend/src/features"], gates: { "english-source": true } });
|
|
170
|
+
|
|
171
|
+
/** Japanese in a git-ignored folder, under a path in `.git/info/exclude`, and in a tracked file. */
|
|
172
|
+
const JAPANESE = {
|
|
173
|
+
"qc.config.json": ENGLISH_ON,
|
|
174
|
+
".gitignore": ".gitnexus/\n",
|
|
175
|
+
".gitnexus/wiki/overview.md": "図面の概要\n",
|
|
176
|
+
"local/draft.md": "下書き\n",
|
|
177
|
+
"docs/tracked.md": "検査の手順\n",
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
test("check skips what git ignores and scans what git tracks", async () => {
|
|
181
|
+
const dir = repo();
|
|
182
|
+
await quiet(() => runInit(load(dir)));
|
|
183
|
+
write(dir, JAPANESE);
|
|
184
|
+
writeFileSync(path.join(dir, ".git/info/exclude"), "local/\n");
|
|
185
|
+
execFileSync("git", ["add", "docs/tracked.md"], { cwd: dir });
|
|
186
|
+
const { problems } = await runCheck(load(dir));
|
|
187
|
+
assert.deepEqual(englishPaths(problems), ["docs/tracked.md"]);
|
|
188
|
+
rmSync(dir, { recursive: true, force: true });
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
test("outside git, check walks the tree and still scans every file", async () => {
|
|
192
|
+
const dir = mkdtempSync(path.join(tmpdir(), "qc-cli-plain-"));
|
|
193
|
+
writeFileSync(path.join(dir, "package.json"), '{"name":"t","private":true,"type":"module"}\n');
|
|
194
|
+
await quiet(() => runInit(load(dir)));
|
|
195
|
+
write(dir, { ...JAPANESE, "node_modules/pkg/readme.md": "日本語\n" });
|
|
196
|
+
const { problems } = await runCheck(load(dir));
|
|
197
|
+
assert.deepEqual(englishPaths(problems), [".gitnexus/wiki/overview.md", "docs/tracked.md", "local/draft.md"]);
|
|
198
|
+
rmSync(dir, { recursive: true, force: true });
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
test("one check lists the repository once, for every gate", async () => {
|
|
202
|
+
const dir = repo();
|
|
203
|
+
await quiet(() => runInit(load(dir)));
|
|
204
|
+
let calls = 0;
|
|
205
|
+
const lister = async (...args) => {
|
|
206
|
+
calls += 1;
|
|
207
|
+
return (await import("./repo-files.mjs")).repoFiles(...args);
|
|
208
|
+
};
|
|
209
|
+
await runCheck(load(dir), [], { lister });
|
|
210
|
+
await runCheck(load(dir), ["docs/decisions.md", "qc.config.json"], { lister });
|
|
211
|
+
assert.equal(calls, 2);
|
|
212
|
+
rmSync(dir, { recursive: true, force: true });
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
test("check with several files reports every problem from each, and judges only those files", async () => {
|
|
216
|
+
const dir = repo();
|
|
217
|
+
await quiet(() => runInit(load(dir)));
|
|
218
|
+
const orders = "backend/src/features/orders";
|
|
219
|
+
const invoices = "backend/src/features/invoices";
|
|
220
|
+
write(dir, {
|
|
221
|
+
"qc.config.json": ENGLISH_ON,
|
|
222
|
+
[`${orders}/index.ts`]: "export {};\n",
|
|
223
|
+
[`${orders}/junk/a.ts`]: "// 注文の補助\nexport {};\n",
|
|
224
|
+
[`${invoices}/index.ts`]: "export {};\n",
|
|
225
|
+
[`${invoices}/junk/b.ts`]: "export {};\n",
|
|
226
|
+
"docs/untouched.md": "触らない\n",
|
|
227
|
+
});
|
|
228
|
+
const { problems } = await runCheck(load(dir), [`${orders}/junk/a.ts`, path.join(dir, invoices, "junk/b.ts")]);
|
|
229
|
+
const features = new Set(problems.filter((problem) => problem.feature).map((problem) => problem.feature.split(path.sep).join("/")));
|
|
230
|
+
assert.deepEqual([...features].sort(), [invoices, orders]);
|
|
231
|
+
assert.deepEqual(englishPaths(problems), [`${orders}/junk/a.ts`]);
|
|
232
|
+
const full = await runCheck(load(dir));
|
|
233
|
+
assert.ok(englishPaths(full.problems).includes("docs/untouched.md"), "no file given must stay the full check");
|
|
234
|
+
rmSync(dir, { recursive: true, force: true });
|
|
235
|
+
});
|
|
236
|
+
|
|
158
237
|
test("a clean mirror run names every root it judged", async () => {
|
|
159
238
|
const dir = await mirrored(["backend/src/orders/ship.ts", "backend/tests/orders/ship.test.ts"]);
|
|
160
239
|
const { lines } = await runCheck(load(dir));
|
package/src/cli/decisions.mjs
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
rewrite,
|
|
21
21
|
squashPlan,
|
|
22
22
|
} from "../decisions.mjs";
|
|
23
|
+
import { repoFiles } from "./repo-files.mjs";
|
|
23
24
|
|
|
24
25
|
const run = promisify(execFile);
|
|
25
26
|
|
|
@@ -39,11 +40,9 @@ export const USAGE = `qc decisions — where every decision id is cited, and how
|
|
|
39
40
|
--dry-run print what would change and write nothing
|
|
40
41
|
--force run against a dirty tree`;
|
|
41
42
|
|
|
42
|
-
//
|
|
43
|
-
async function tracked(
|
|
44
|
-
|
|
45
|
-
const { stdout } = await run("git", args, { cwd: root, maxBuffer: 64 * 1024 * 1024 });
|
|
46
|
-
return [...new Set(stdout.split("\0"))].filter((name) => name !== "" && !BINARY.test(name));
|
|
43
|
+
// The lister every gate reads, so this sees what the citations gate sees.
|
|
44
|
+
async function tracked(config) {
|
|
45
|
+
return (await repoFiles(config.root, { ignores: config.ignores })).filter((name) => !BINARY.test(name));
|
|
47
46
|
}
|
|
48
47
|
|
|
49
48
|
async function scan(config) {
|
|
@@ -51,7 +50,7 @@ async function scan(config) {
|
|
|
51
50
|
const exclude = config.decisions.exclude ?? [];
|
|
52
51
|
const sites = new Map();
|
|
53
52
|
const generated = new Map();
|
|
54
|
-
for (const file of await tracked(config
|
|
53
|
+
for (const file of await tracked(config)) {
|
|
55
54
|
// A vendored tool cites its own upstream register, never this repository's.
|
|
56
55
|
if (exclude.some((source) => new RegExp(source).test(file))) continue;
|
|
57
56
|
const contents = await readFile(path.join(config.root, file), "utf8").catch(() => null);
|
|
@@ -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,29 @@
|
|
|
1
|
+
// The resource for git's own view of which paths a checkout ignores. An ignored path never reaches
|
|
2
|
+
// a commit, so the edit guard and the Bash edit guard both let it through a protected branch.
|
|
3
|
+
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
|
|
7
|
+
const execFileAsync = promisify(execFile);
|
|
8
|
+
const NUL = "\u0000";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* One `git check-ignore` call for every path. A tracked path is never ignored, as in `git status`.
|
|
12
|
+
* @param {string} root the checkout's top level
|
|
13
|
+
* @param {string[]} relPaths forward-slash, relative to `root`
|
|
14
|
+
* @returns {Promise<Set<string>>} the ignored subset; empty when none is, or git cannot tell
|
|
15
|
+
*/
|
|
16
|
+
export async function ignoredPaths(root, relPaths) {
|
|
17
|
+
if (relPaths.length === 0) return new Set();
|
|
18
|
+
const pending = execFileAsync("git", ["check-ignore", "--stdin", "-z"], { cwd: root });
|
|
19
|
+
// Git outside a checkout exits before it reads, and the broken pipe must not crash the hook.
|
|
20
|
+
pending.child.stdin.on("error", () => {});
|
|
21
|
+
pending.child.stdin.end(relPaths.join(NUL) + NUL);
|
|
22
|
+
try {
|
|
23
|
+
const { stdout } = await pending;
|
|
24
|
+
return new Set(stdout.split(NUL).filter(Boolean));
|
|
25
|
+
} catch {
|
|
26
|
+
// Exit 1 means no path is ignored; any other failure keeps every path in scope of the guard.
|
|
27
|
+
return new Set();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
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 { ignoredPaths } from "./ignored-paths.mjs";
|
|
8
|
+
|
|
9
|
+
/** A checkout that ignores `*.local.json` and tracks one file whose name matches that pattern. */
|
|
10
|
+
function checkout() {
|
|
11
|
+
const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-ignored-")));
|
|
12
|
+
const git = (...args) => execFileSync("git", args, { cwd: base, stdio: "pipe" });
|
|
13
|
+
git("init", "-q", "-b", "main");
|
|
14
|
+
writeFileSync(path.join(base, ".gitignore"), "*.local.json\n");
|
|
15
|
+
writeFileSync(path.join(base, "tracked.local.json"), "{}");
|
|
16
|
+
git("add", ".gitignore");
|
|
17
|
+
git("add", "-f", "tracked.local.json");
|
|
18
|
+
git("-c", "user.name=qc", "-c", "user.email=qc@example.com", "commit", "-q", "-m", "init");
|
|
19
|
+
return { root: base, cleanup: () => rmSync(base, { recursive: true, force: true }) };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
test("the ignored subset of the paths comes back, in one call", async (t) => {
|
|
23
|
+
const repo = checkout();
|
|
24
|
+
t.after(repo.cleanup);
|
|
25
|
+
const ignored = await ignoredPaths(repo.root, [".claude/settings.local.json", "src/a.ts", "notes.local.json"]);
|
|
26
|
+
assert.deepEqual([...ignored].sort(), [".claude/settings.local.json", "notes.local.json"]);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("a tracked file is never ignored, even when its name matches an ignore pattern", async (t) => {
|
|
30
|
+
const repo = checkout();
|
|
31
|
+
t.after(repo.cleanup);
|
|
32
|
+
assert.equal((await ignoredPaths(repo.root, ["tracked.local.json"])).size, 0);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test("no path ignored, no paths, or no checkout is the empty set", async (t) => {
|
|
36
|
+
const repo = checkout();
|
|
37
|
+
t.after(repo.cleanup);
|
|
38
|
+
assert.equal((await ignoredPaths(repo.root, ["src/a.ts"])).size, 0);
|
|
39
|
+
assert.equal((await ignoredPaths(repo.root, [])).size, 0);
|
|
40
|
+
const outside = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-no-checkout-")));
|
|
41
|
+
t.after(() => rmSync(outside, { recursive: true, force: true }));
|
|
42
|
+
mkdirSync(path.join(outside, "sub"));
|
|
43
|
+
assert.equal((await ignoredPaths(path.join(outside, "sub"), ["a.local.json"])).size, 0);
|
|
44
|
+
});
|