architecture-harness 0.8.0 → 0.10.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 +3 -2
- 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 +10 -8
- package/src/cli/bash-edit-guard.test.mjs +16 -0
- package/src/cli/check.mjs +10 -1
- 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/powershell-command.mjs +57 -0
- package/src/cli/powershell-command.test.mjs +52 -0
- package/src/cli/repo-files.mjs +2 -6
- package/src/cli/shell-command.mjs +25 -15
- package/src/cli/shell-command.test.mjs +24 -1
- package/src/config.mjs +24 -0
- package/src/descriptions.mjs +1 -0
- package/src/enforcement-map.mjs +2 -1
- package/src/eslint/index.mjs +6 -0
- package/src/eslint/preset.mjs +23 -8
- package/src/eslint/preset.test.mjs +62 -0
- package/src/eslint/rules/ime-safe-key.mjs +179 -0
- package/src/eslint/rules/no-sql-raw.mjs +30 -0
- package/src/eslint/rules/registry-literal.mjs +66 -0
- package/src/eslint/rules.test.mjs +151 -0
- package/src/gates/registry-readers.mjs +24 -0
- package/src/gates/registry-readers.test.mjs +35 -0
- package/src/generated-markers.mjs +16 -0
- package/src/glob.mjs +11 -0
- package/templates/quality-thresholds.json +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "architecture-harness",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
|
|
6
6
|
"license": "MIT",
|
|
@@ -76,6 +76,7 @@
|
|
|
76
76
|
"@typescript-eslint/eslint-plugin": "^8",
|
|
77
77
|
"@typescript-eslint/parser": "^8",
|
|
78
78
|
"eslint-plugin-boundaries": "^5",
|
|
79
|
-
"eslint-plugin-sonarjs": "^3"
|
|
79
|
+
"eslint-plugin-sonarjs": "^3",
|
|
80
|
+
"typescript": "^5"
|
|
80
81
|
}
|
|
81
82
|
}
|
|
@@ -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
|
|
3
|
-
// to: the work order's declared paths, and no change on a protected branch. A shell
|
|
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
|
|
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
|
-
|
|
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);
|
package/src/cli/check.mjs
CHANGED
|
@@ -30,7 +30,8 @@ import { checkAdrFormat } from "../gates/adr-format.mjs";
|
|
|
30
30
|
import { checkConfigFloor } from "../gates/config-floor.mjs";
|
|
31
31
|
import { defaults } from "../config.mjs";
|
|
32
32
|
import { rules as lintRules } from "../eslint/index.mjs";
|
|
33
|
-
import { enabled } from "../config.mjs";
|
|
33
|
+
import { enabled, readerEntries, thresholds } from "../config.mjs";
|
|
34
|
+
import { checkRegistryReaders } from "../gates/registry-readers.mjs";
|
|
34
35
|
import { repoFiles } from "./repo-files.mjs";
|
|
35
36
|
|
|
36
37
|
// Each skip is tested on "/" + the relative path, so it reads a path the way it read a full one.
|
|
@@ -454,6 +455,14 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
|
|
|
454
455
|
problems.push(...(await agreements(config)));
|
|
455
456
|
}
|
|
456
457
|
|
|
458
|
+
if (enabled(config.gates, "registry-readers")) {
|
|
459
|
+
const entries = readerEntries(thresholds(config));
|
|
460
|
+
const readers = [...new Set(entries.flatMap((entry) => entry.readers))];
|
|
461
|
+
const sources = new Map(await Promise.all(readers.map(async (reader) => [reader, await read(path.join(config.root, reader))])));
|
|
462
|
+
problems.push(...checkRegistryReaders(entries, sources));
|
|
463
|
+
if (readers.length > 0) lines.push(`OK readers ${readers.length} registry reader(s), each present and naming its entry`);
|
|
464
|
+
}
|
|
465
|
+
|
|
457
466
|
if (enabled(config.gates, "sql-identifiers") || enabled(config.gates, "tenant-predicate")) {
|
|
458
467
|
problems.push(...(await sqlAgreement(config, tree, taken)));
|
|
459
468
|
lines.push("OK sql every column is declared, every statement and shared insert carries the tenant");
|
|
@@ -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
|
+
}
|