architecture-harness 0.6.0 → 0.8.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-edit-guard.mjs +161 -0
- package/src/cli/bash-edit-guard.test.mjs +98 -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/ignored-paths.mjs +29 -0
- package/src/cli/ignored-paths.test.mjs +44 -0
- package/src/cli/qc.mjs +10 -2
- package/src/cli/repo-files.mjs +69 -0
- package/src/cli/repo-files.test.mjs +78 -0
- package/src/cli/shell-command.mjs +211 -0
- package/src/cli/shell-command.test.mjs +95 -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 +6 -0
- package/src/gates/english-source.mjs +13 -9
- package/src/gates/english-source.test.mjs +19 -1
- package/src/gates/test-mirror.mjs +22 -9
- package/src/gates/test-mirror.test.mjs +34 -0
- package/src/glob.mjs +12 -0
- package/templates/CLAUDE.md +1 -1
package/package.json
CHANGED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The PostToolUse trigger that holds a Bash command to the rules the edit guard holds Write and Edit
|
|
3
|
+
// to: the work order's declared paths, and no change on a protected branch. A shell write through
|
|
4
|
+
// sed, a script or a codemod never reaches the edit guard. This one warns and never reverts.
|
|
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 { checkoutDirs, mayWrite } from "./shell-command.mjs";
|
|
16
|
+
import { isAllowed } from "./work-order-guard.mjs";
|
|
17
|
+
import { MANIFEST_FILE, readManifest } from "./work-order-manifest.mjs";
|
|
18
|
+
import { OFF, isolationSettings } from "./worktree-isolation.mjs";
|
|
19
|
+
|
|
20
|
+
const execFileAsync = promisify(execFile);
|
|
21
|
+
const slashed = (file) => file.split(path.sep).join("/");
|
|
22
|
+
const MAX_LISTED = 40;
|
|
23
|
+
|
|
24
|
+
/** The paths `git status --porcelain -z` names, with both sides of a rename. */
|
|
25
|
+
export function changedPaths(porcelain) {
|
|
26
|
+
const fields = porcelain.split("\u0000");
|
|
27
|
+
const paths = [];
|
|
28
|
+
for (let i = 0; i < fields.length; i++) {
|
|
29
|
+
const entry = fields[i];
|
|
30
|
+
if (entry.length < 4) continue;
|
|
31
|
+
paths.push(entry.slice(3));
|
|
32
|
+
if (entry[0] === "R") paths.push(fields[++i]);
|
|
33
|
+
else if (entry[0] === "C") i++;
|
|
34
|
+
}
|
|
35
|
+
return paths.filter(Boolean);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const native = (dir) => {
|
|
39
|
+
try {
|
|
40
|
+
return realpathSync.native(dir);
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** A directory as the command wrote it, resolved the way the shell would, or null when it does not exist. */
|
|
47
|
+
function resolveDir(cwd, dir) {
|
|
48
|
+
let spelled = dir.replace(/^~(?=$|[\\/])/, os.homedir());
|
|
49
|
+
if (process.platform === "win32") spelled = spelled.replace(/^\/([A-Za-z])(?=\/|$)/, "$1:");
|
|
50
|
+
const absolute = path.resolve(cwd, spelled);
|
|
51
|
+
return existsSync(absolute) ? absolute : null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Every distinct checkout the command could have changed: its cwd, and each `cd` and `git -C` directory. */
|
|
55
|
+
function checkoutsOf(cwd, command) {
|
|
56
|
+
const roots = new Set();
|
|
57
|
+
for (const dir of [cwd, ...checkoutDirs(command).map((d) => resolveDir(cwd, d))]) {
|
|
58
|
+
const root = dir && checkoutRootOf(dir);
|
|
59
|
+
const real = root && native(root);
|
|
60
|
+
if (real) roots.add(real);
|
|
61
|
+
}
|
|
62
|
+
return [...roots];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function gitFacts(root) {
|
|
66
|
+
const run = async (...args) => (await execFileAsync("git", args, { cwd: root, maxBuffer: 64 * 1024 * 1024 })).stdout;
|
|
67
|
+
const [status, branch] = await Promise.all([
|
|
68
|
+
run("status", "--porcelain", "-z", "--untracked-files=all"),
|
|
69
|
+
run("branch", "--show-current"),
|
|
70
|
+
]);
|
|
71
|
+
return { changed: changedPaths(status), branch: branch.trim() };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** @returns each changed path in one checkout that breaks a rule, with the rules it breaks. */
|
|
75
|
+
async function findingsIn(root, manifest, projectRoot) {
|
|
76
|
+
let settings = null;
|
|
77
|
+
try {
|
|
78
|
+
settings = isolationSettings(load(root).swarm);
|
|
79
|
+
} catch {
|
|
80
|
+
// A config error is the edit guard's to name; this guard judges the declaration alone.
|
|
81
|
+
}
|
|
82
|
+
const guardsBranch = settings !== null && settings.require !== OFF;
|
|
83
|
+
if (!manifest && !guardsBranch) return [];
|
|
84
|
+
|
|
85
|
+
let facts;
|
|
86
|
+
try {
|
|
87
|
+
facts = await gitFacts(root);
|
|
88
|
+
} catch {
|
|
89
|
+
return [];
|
|
90
|
+
}
|
|
91
|
+
const rules = new Map();
|
|
92
|
+
const add = (rel, rule) => rules.set(rel, [...(rules.get(rel) ?? []), rule]);
|
|
93
|
+
|
|
94
|
+
const patterns = manifest?.paths ?? [];
|
|
95
|
+
for (const rel of facts.changed) {
|
|
96
|
+
if (!isAllowed(slashed(path.relative(projectRoot, path.join(root, rel))), patterns)) {
|
|
97
|
+
add(rel, `outside the work order's declared paths (${MANIFEST_FILE}: ${patterns.join(", ")})`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (guardsBranch && settings.protectedBranches.includes(facts.branch)) {
|
|
101
|
+
const candidates = facts.changed.filter((rel) => !(settings.allow.length > 0 && isAllowed(rel, settings.allow)));
|
|
102
|
+
const ignored = await ignoredPaths(root, candidates);
|
|
103
|
+
for (const rel of candidates) {
|
|
104
|
+
if (!ignored.has(rel)) add(rel, `changed on the protected branch "${facts.branch}"`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return [...rules].map(([rel, broken]) => `${slashed(root)}/${rel}: ${broken.join("; ")}`);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The report on one finished Bash call. @param projectRoot the folder that holds the work-order manifest
|
|
112
|
+
* @returns PostToolUse output with model-visible context, or null when nothing breaks a rule
|
|
113
|
+
*/
|
|
114
|
+
export async function report(call, projectRoot) {
|
|
115
|
+
const command = call.tool_input?.command;
|
|
116
|
+
if (typeof command !== "string" || !mayWrite(command)) return null;
|
|
117
|
+
const cwd = call.cwd ?? process.cwd();
|
|
118
|
+
const project = native(projectRoot) ?? projectRoot;
|
|
119
|
+
|
|
120
|
+
let manifest = null;
|
|
121
|
+
try {
|
|
122
|
+
manifest = readManifest(project);
|
|
123
|
+
} catch {
|
|
124
|
+
// The edit guard names a manifest that does not parse.
|
|
125
|
+
}
|
|
126
|
+
const findings = [];
|
|
127
|
+
for (const root of checkoutsOf(cwd, command)) findings.push(...(await findingsIn(root, manifest, project)));
|
|
128
|
+
if (findings.length === 0) return null;
|
|
129
|
+
|
|
130
|
+
const listed = findings.slice(0, MAX_LISTED).map((line) => `- ${line}`);
|
|
131
|
+
if (findings.length > MAX_LISTED) listed.push(`- and ${findings.length - MAX_LISTED} more`);
|
|
132
|
+
return {
|
|
133
|
+
hookSpecificOutput: {
|
|
134
|
+
hookEventName: "PostToolUse",
|
|
135
|
+
additionalContext: [
|
|
136
|
+
"Bash edit guard: the checkout holds uncommitted changes that the swarm rules do not allow.",
|
|
137
|
+
...listed,
|
|
138
|
+
"Revert a change only if your work order made it and should not have. " +
|
|
139
|
+
"For any other change, stop and tell the orchestrator. The guard does not revert anything.",
|
|
140
|
+
].join("\n"),
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function readStdin() {
|
|
146
|
+
let data = "";
|
|
147
|
+
for await (const chunk of process.stdin) data += chunk;
|
|
148
|
+
return data;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
|
|
152
|
+
if (isEntryPoint) {
|
|
153
|
+
let call = null;
|
|
154
|
+
try {
|
|
155
|
+
call = JSON.parse(await readStdin());
|
|
156
|
+
} catch {
|
|
157
|
+
// Not hook input, so there is no command to judge.
|
|
158
|
+
}
|
|
159
|
+
const output = call ? await report(call, process.env.CLAUDE_PROJECT_DIR ?? process.cwd()) : null;
|
|
160
|
+
if (output) process.stdout.write(JSON.stringify(output));
|
|
161
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
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
|
+
|
|
41
|
+
test("a write inside the work order's declared paths is silent", async (t) => {
|
|
42
|
+
const ws = workspace(t);
|
|
43
|
+
ws.put(ws.linked, "src/a.ts");
|
|
44
|
+
assert.equal(await report(bash(ws.linked, "node scripts/codemod.mjs"), ws.linked), null);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("a write outside the declared paths is reported with the path and the rule, as model-visible context", async (t) => {
|
|
48
|
+
const ws = workspace(t);
|
|
49
|
+
ws.put(ws.linked, "src/a.ts");
|
|
50
|
+
ws.put(ws.linked, "docs/b.md");
|
|
51
|
+
const output = await report(bash(ws.linked, "sed -i 's/a/b/' docs/b.md"), ws.linked);
|
|
52
|
+
assert.equal(output.hookSpecificOutput.hookEventName, "PostToolUse");
|
|
53
|
+
const text = contextOf(output);
|
|
54
|
+
assert.match(text, /docs\/b\.md/);
|
|
55
|
+
assert.doesNotMatch(text, /src\/a\.ts/);
|
|
56
|
+
assert.match(text, /work-order\.local\.json/);
|
|
57
|
+
assert.match(text, /src\/\*\*/);
|
|
58
|
+
assert.match(text, /does not revert/);
|
|
59
|
+
// Status also lists changes made before the command, in a checkout other sessions can share.
|
|
60
|
+
assert.match(text, /uncommitted changes/);
|
|
61
|
+
assert.match(text, /only if your work order made it/);
|
|
62
|
+
assert.match(text, /stop and tell the orchestrator/);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("a change on a protected branch is reported with no work order, and an ignored file is not", async (t) => {
|
|
66
|
+
const ws = workspace(t);
|
|
67
|
+
ws.put(ws.primary, "src/a.ts");
|
|
68
|
+
ws.put(ws.primary, ".claude/settings.local.json");
|
|
69
|
+
const text = contextOf(await report(bash(ws.primary, "python fix.py"), ws.primary));
|
|
70
|
+
assert.match(text, /src\/a\.ts/);
|
|
71
|
+
assert.match(text, /protected branch "main"/);
|
|
72
|
+
assert.doesNotMatch(text, /settings\.local\.json/);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("a read-only command is skipped, even with an out-of-scope change in the checkout", async (t) => {
|
|
76
|
+
const ws = workspace(t);
|
|
77
|
+
ws.put(ws.linked, "docs/b.md");
|
|
78
|
+
assert.equal(await report(bash(ws.linked, "git status && cat docs/b.md | grep x"), ws.linked), null);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test("git -C names the checkout the command changed, whatever the session's directory", async (t) => {
|
|
82
|
+
const ws = workspace(t);
|
|
83
|
+
ws.put(ws.primary, "src/a.ts");
|
|
84
|
+
const text = contextOf(await report(bash(ws.outside, `git -C "${ws.primary}" apply fix.patch`), ws.outside));
|
|
85
|
+
assert.match(text, /src\/a\.ts/);
|
|
86
|
+
assert.match(text, /protected branch "main"/);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("a checkout with no isolation and no work order is silent", async (t) => {
|
|
90
|
+
const ws = workspace(t);
|
|
91
|
+
ws.put(ws.plain, "src/a.ts");
|
|
92
|
+
assert.equal(await report(bash(ws.plain, "node x.mjs"), ws.plain), null);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test("porcelain output names each changed path, and both sides of a rename", () => {
|
|
96
|
+
const status = [" M src/a.ts", "?? docs/new file.md", "R lib/new.ts", "lib/old.ts", ""].join("\u0000");
|
|
97
|
+
assert.deepEqual(changedPaths(status), ["src/a.ts", "docs/new file.md", "lib/new.ts", "lib/old.ts"]);
|
|
98
|
+
});
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, 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
|
+
|
|
9
|
+
const GUARD = fileURLToPath(new URL("./budget-guard.mjs", import.meta.url));
|
|
10
|
+
|
|
11
|
+
/** An adopted checkout with a budget, a linked worktree of it, a checkout with no config, and a temp folder for the counters. */
|
|
12
|
+
function workspace(t, swarm = { toolCallBudget: 3 }) {
|
|
13
|
+
const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-budget-")));
|
|
14
|
+
t.after(() => rmSync(base, { recursive: true, force: true }));
|
|
15
|
+
const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe" });
|
|
16
|
+
const primary = path.join(base, "primary");
|
|
17
|
+
const linked = path.join(base, "linked");
|
|
18
|
+
const plain = path.join(base, "plain");
|
|
19
|
+
const tmp = path.join(base, "tmp");
|
|
20
|
+
for (const dir of [primary, plain, tmp]) mkdirSync(dir);
|
|
21
|
+
git(primary, "init", "-q", "-b", "main");
|
|
22
|
+
writeFileSync(path.join(primary, "qc.config.json"), JSON.stringify({ swarm }));
|
|
23
|
+
git(primary, "add", ".");
|
|
24
|
+
git(primary, "-c", "user.name=qc", "-c", "user.email=qc@example.com", "commit", "-q", "-m", "init");
|
|
25
|
+
git(primary, "worktree", "add", "-q", linked, "-b", "feat/work-order");
|
|
26
|
+
git(plain, "init", "-q", "-b", "main");
|
|
27
|
+
mkdirSync(path.join(linked, "src"));
|
|
28
|
+
return { primary, linked, plain, tmp, counters: path.join(tmp, "architecture-kit", "budget") };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const callOf = (cwd, agentId, tool_name = "Bash", tool_input = { command: "npm test" }) => ({
|
|
32
|
+
session_id: "session-aaaa",
|
|
33
|
+
...(agentId ? { agent_id: agentId, agent_type: "general-purpose" } : {}),
|
|
34
|
+
cwd,
|
|
35
|
+
hook_event_name: "PreToolUse",
|
|
36
|
+
tool_name,
|
|
37
|
+
tool_input,
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
/** Runs the hook as its own process, with every temp-folder variable pinned to the test's folder. */
|
|
41
|
+
function runGuard(ws, call) {
|
|
42
|
+
const result = spawnSync(process.execPath, [GUARD], {
|
|
43
|
+
input: JSON.stringify(call),
|
|
44
|
+
env: { ...process.env, TEMP: ws.tmp, TMP: ws.tmp, TMPDIR: ws.tmp },
|
|
45
|
+
encoding: "utf8",
|
|
46
|
+
});
|
|
47
|
+
assert.equal(result.status, 0, result.stderr);
|
|
48
|
+
return result.stdout.trim() === "" ? null : JSON.parse(result.stdout);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const countOf = (ws, agentId) => JSON.parse(readFileSync(path.join(ws.counters, `session-aaaa-${agentId}.json`), "utf8")).count;
|
|
52
|
+
|
|
53
|
+
test("the main session has no agent id, so it is never counted", (t) => {
|
|
54
|
+
const ws = workspace(t);
|
|
55
|
+
for (let i = 0; i < 4; i++) assert.equal(runGuard(ws, callOf(ws.linked, null)), null);
|
|
56
|
+
assert.equal(existsSync(ws.counters), false);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("a repository with no qc.config.json is never counted", (t) => {
|
|
60
|
+
const ws = workspace(t);
|
|
61
|
+
for (let i = 0; i < 4; i++) assert.equal(runGuard(ws, callOf(ws.plain, "agent-1")), null);
|
|
62
|
+
assert.equal(existsSync(ws.counters), false);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("each agent of one session keeps its own count", (t) => {
|
|
66
|
+
const ws = workspace(t, { toolCallBudget: 50 });
|
|
67
|
+
runGuard(ws, callOf(ws.linked, "agent-1"));
|
|
68
|
+
runGuard(ws, callOf(ws.linked, "agent-1"));
|
|
69
|
+
runGuard(ws, callOf(ws.linked, "agent-2"));
|
|
70
|
+
assert.equal(countOf(ws, "agent-1"), 2);
|
|
71
|
+
assert.equal(countOf(ws, "agent-2"), 1);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test("in a linked worktree, the budget from qc.config.json denies the call that reaches it, and the hand-off still runs", (t) => {
|
|
75
|
+
const ws = workspace(t);
|
|
76
|
+
assert.equal(runGuard(ws, callOf(path.join(ws.linked, "src"), "agent-1")), null);
|
|
77
|
+
assert.equal(runGuard(ws, callOf(ws.linked, "agent-1")), null);
|
|
78
|
+
const denied = runGuard(ws, callOf(ws.linked, "agent-1"));
|
|
79
|
+
assert.equal(denied.hookSpecificOutput.permissionDecision, "deny");
|
|
80
|
+
assert.match(denied.hookSpecificOutput.permissionDecisionReason, /call 3 of 3/);
|
|
81
|
+
assert.equal(runGuard(ws, callOf(ws.linked, "agent-1", "Bash", { command: "git push" })), null);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test("the default budget reminds at its seventieth call", (t) => {
|
|
85
|
+
const ws = workspace(t, {});
|
|
86
|
+
mkdirSync(ws.counters, { recursive: true });
|
|
87
|
+
writeFileSync(path.join(ws.counters, "session-aaaa-agent-1.json"), JSON.stringify({ count: 69 }));
|
|
88
|
+
const output = runGuard(ws, callOf(ws.linked, "agent-1"));
|
|
89
|
+
assert.match(output.hookSpecificOutput.additionalContext, /call 70 of 100/);
|
|
90
|
+
});
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// The branch that turns an agent's tool-call count into a verdict: nothing, a reminder, or a deny.
|
|
2
|
+
// An agent does not count its own calls, and each call re-sends its whole transcript, so the hook
|
|
3
|
+
// counts for it and closes every tool except the hand-off once the budget is spent.
|
|
4
|
+
|
|
5
|
+
import { defaults } from "../config.mjs";
|
|
6
|
+
import { gitCall, isReadOnly, segmentsOf, writesRedirect } from "./shell-command.mjs";
|
|
7
|
+
|
|
8
|
+
export const DEFAULT_BUDGET = defaults.swarm.toolCallBudget;
|
|
9
|
+
const REMIND_PERCENT = 70;
|
|
10
|
+
const REMIND_EVERY = 10;
|
|
11
|
+
const KEY = "swarm.toolCallBudget";
|
|
12
|
+
const HANDOFF_GIT = new Set(["status", "diff", "log", "add", "commit", "push"]);
|
|
13
|
+
|
|
14
|
+
/** @returns the budget from the `swarm` config section, or throws naming the key a repository got wrong. */
|
|
15
|
+
export function budgetOf(swarm = {}) {
|
|
16
|
+
const budget = swarm.toolCallBudget ?? DEFAULT_BUDGET;
|
|
17
|
+
if (!Number.isInteger(budget) || budget < 1) {
|
|
18
|
+
throw new Error(`${KEY} in qc.config.json must be a positive whole number, got ${JSON.stringify(swarm.toolCallBudget)}`);
|
|
19
|
+
}
|
|
20
|
+
return budget;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const isHandoffSegment = (segment) =>
|
|
24
|
+
isReadOnly(segment) || (!writesRedirect(segment) && HANDOFF_GIT.has(gitCall(segment)?.sub));
|
|
25
|
+
|
|
26
|
+
/** True for a call the hand-off needs: read, commit and push, write the note, send the report. */
|
|
27
|
+
export function isHandoffCall(call) {
|
|
28
|
+
const input = call.tool_input ?? {};
|
|
29
|
+
switch (call.tool_name) {
|
|
30
|
+
case "Read":
|
|
31
|
+
case "SubagentHandback":
|
|
32
|
+
return true;
|
|
33
|
+
case "Write":
|
|
34
|
+
case "Edit":
|
|
35
|
+
return String(input.file_path ?? "").replaceAll("\\", "/").includes("/handoffs/");
|
|
36
|
+
case "Bash": {
|
|
37
|
+
const segments = segmentsOf(String(input.command ?? ""));
|
|
38
|
+
return segments.length > 0 && segments.every(isHandoffSegment);
|
|
39
|
+
}
|
|
40
|
+
default:
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const remind = (count, budget) => ({
|
|
46
|
+
hookSpecificOutput: {
|
|
47
|
+
hookEventName: "PreToolUse",
|
|
48
|
+
additionalContext:
|
|
49
|
+
`Tool-call budget: this is call ${count} of ${budget}. Finish the current step, commit and push green work, ` +
|
|
50
|
+
`and plan the hand-off. At call ${budget}, only the hand-off can run.`,
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const deny = (count, budget) => ({
|
|
55
|
+
hookSpecificOutput: {
|
|
56
|
+
hookEventName: "PreToolUse",
|
|
57
|
+
permissionDecision: "deny",
|
|
58
|
+
permissionDecisionReason:
|
|
59
|
+
`Tool-call budget spent: this is call ${count} of ${budget} (${KEY} in qc.config.json). ` +
|
|
60
|
+
"Only the hand-off can run now. " +
|
|
61
|
+
"1. Commit and push green work with git add, git commit and git push. " +
|
|
62
|
+
"2. Write the hand-off note to a path under /handoffs/: what is done, what is left in order, and the exact next step. " +
|
|
63
|
+
"3. Send the final report, and name the note. " +
|
|
64
|
+
"Read and read-only commands still run.",
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
/** @returns the hook output for the call numbered `count`, or null to let it run with no message. */
|
|
69
|
+
export function budgetVerdict({ count, budget, call }) {
|
|
70
|
+
if (count >= budget) return isHandoffCall(call) ? null : deny(count, budget);
|
|
71
|
+
const remindAt = Math.ceil((budget * REMIND_PERCENT) / 100);
|
|
72
|
+
if (count >= remindAt && (count - remindAt) % REMIND_EVERY === 0) return remind(count, budget);
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { DEFAULT_BUDGET, budgetOf, budgetVerdict, isHandoffCall } from "./budget.mjs";
|
|
4
|
+
|
|
5
|
+
const bash = (command) => ({ tool_name: "Bash", tool_input: { command } });
|
|
6
|
+
const write = (file_path) => ({ tool_name: "Write", tool_input: { file_path, content: "x" } });
|
|
7
|
+
const edit = (file_path) => ({ tool_name: "Edit", tool_input: { file_path, old_string: "a", new_string: "b" } });
|
|
8
|
+
const verdict = (count, call = bash("npm test"), budget = 100) => budgetVerdict({ count, budget, call });
|
|
9
|
+
|
|
10
|
+
test("the budget is swarm.toolCallBudget, and one hundred calls without it", () => {
|
|
11
|
+
assert.equal(DEFAULT_BUDGET, 100);
|
|
12
|
+
assert.equal(budgetOf(), 100);
|
|
13
|
+
assert.equal(budgetOf({}), 100);
|
|
14
|
+
assert.equal(budgetOf({ toolCallBudget: 40 }), 40);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test("a budget that is not a positive whole number is a named config error", () => {
|
|
18
|
+
for (const toolCallBudget of [0, -1, 2.5, "100"]) {
|
|
19
|
+
assert.throws(() => budgetOf({ toolCallBudget }), /swarm\.toolCallBudget/);
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test("below seventy percent of the budget a call runs with no message", () => {
|
|
24
|
+
assert.equal(verdict(1), null);
|
|
25
|
+
assert.equal(verdict(69), null);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("the reminder fires at seventy percent and every ten calls after, as model-visible context", () => {
|
|
29
|
+
for (const count of [70, 80, 90]) {
|
|
30
|
+
const output = verdict(count);
|
|
31
|
+
assert.equal(output.hookSpecificOutput.hookEventName, "PreToolUse");
|
|
32
|
+
assert.equal(output.hookSpecificOutput.permissionDecision, undefined);
|
|
33
|
+
const reminder = output.hookSpecificOutput.additionalContext;
|
|
34
|
+
assert.match(reminder, new RegExp(`call ${count} of 100`));
|
|
35
|
+
assert.match(reminder, /commit and push green work/);
|
|
36
|
+
assert.match(reminder, /hand-off/);
|
|
37
|
+
}
|
|
38
|
+
assert.equal(verdict(71), null);
|
|
39
|
+
assert.equal(verdict(89), null);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("the reminder threshold rounds up for a small budget", () => {
|
|
43
|
+
assert.equal(verdict(3, bash("npm test"), 5), null);
|
|
44
|
+
assert.ok(verdict(4, bash("npm test"), 5).hookSpecificOutput.additionalContext);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("at the budget and past it, a call outside the hand-off is denied with the hand-off steps", () => {
|
|
48
|
+
for (const call of [bash("npm test"), bash("git status && pnpm test"), bash("git checkout main"), bash("git status > s.txt"), { tool_name: "Grep", tool_input: {} }, write("src/a.ts")]) {
|
|
49
|
+
for (const count of [100, 101, 150]) {
|
|
50
|
+
const output = verdict(count, call);
|
|
51
|
+
assert.equal(output.hookSpecificOutput.permissionDecision, "deny", JSON.stringify(call));
|
|
52
|
+
const reason = output.hookSpecificOutput.permissionDecisionReason;
|
|
53
|
+
assert.match(reason, /commit and push green work/i);
|
|
54
|
+
assert.match(reason, /hand-off note/);
|
|
55
|
+
assert.match(reason, /final report/);
|
|
56
|
+
assert.match(reason, /swarm\.toolCallBudget/);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test("at the budget, every call a hand-off needs still runs", () => {
|
|
62
|
+
const handoff = [
|
|
63
|
+
bash("git status"),
|
|
64
|
+
bash("git diff --stat"),
|
|
65
|
+
bash("git log --oneline -3 | head -3"),
|
|
66
|
+
bash('git add -A && git commit -m "wip: stop here" && git push -u origin HEAD'),
|
|
67
|
+
bash('git -C "C:/work/kit wt" commit -m "wip: a; b && c"'),
|
|
68
|
+
bash("cd /work/wt && git push"),
|
|
69
|
+
bash("git commit -F - <<'EOF'\nwip: stop; here && now\nEOF"),
|
|
70
|
+
write("C:\\tmp\\scratch\\handoffs\\k1.md"),
|
|
71
|
+
edit("/tmp/scratch/handoffs/k1.md"),
|
|
72
|
+
{ tool_name: "Read", tool_input: { file_path: "/work/wt/src/a.ts" } },
|
|
73
|
+
{ tool_name: "SubagentHandback", tool_input: { message: "done" } },
|
|
74
|
+
];
|
|
75
|
+
for (const call of handoff) {
|
|
76
|
+
assert.equal(isHandoffCall(call), true, JSON.stringify(call));
|
|
77
|
+
assert.equal(verdict(100, call), null, JSON.stringify(call));
|
|
78
|
+
}
|
|
79
|
+
});
|