architecture-harness 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/package.json +1 -1
  2. package/src/cli/bash-command-guard.mjs +129 -0
  3. package/src/cli/bash-command-guard.test.mjs +96 -0
  4. package/src/cli/bash-edit-guard.mjs +163 -0
  5. package/src/cli/bash-edit-guard.test.mjs +114 -0
  6. package/src/cli/budget-counter.mjs +40 -0
  7. package/src/cli/budget-counter.test.mjs +35 -0
  8. package/src/cli/budget-guard.mjs +56 -0
  9. package/src/cli/budget-guard.test.mjs +90 -0
  10. package/src/cli/budget.mjs +74 -0
  11. package/src/cli/budget.test.mjs +79 -0
  12. package/src/cli/check.mjs +197 -174
  13. package/src/cli/checkout-root.mjs +16 -0
  14. package/src/cli/cli.test.mjs +79 -0
  15. package/src/cli/decisions.mjs +5 -6
  16. package/src/cli/edit-batch-guard.mjs +77 -0
  17. package/src/cli/edit-batch-guard.test.mjs +131 -0
  18. package/src/cli/edit-batch-state.mjs +57 -0
  19. package/src/cli/generated-file-guard.mjs +81 -0
  20. package/src/cli/generated-file-guard.test.mjs +104 -0
  21. package/src/cli/ignored-paths.mjs +29 -0
  22. package/src/cli/ignored-paths.test.mjs +44 -0
  23. package/src/cli/powershell-command.mjs +57 -0
  24. package/src/cli/powershell-command.test.mjs +52 -0
  25. package/src/cli/qc.mjs +10 -2
  26. package/src/cli/repo-files.mjs +65 -0
  27. package/src/cli/repo-files.test.mjs +78 -0
  28. package/src/cli/shell-command.mjs +221 -0
  29. package/src/cli/shell-command.test.mjs +118 -0
  30. package/src/cli/work-order-guard.mjs +19 -21
  31. package/src/cli/work-order-guard.test.mjs +18 -0
  32. package/src/cli/work-order-manifest.mjs +14 -0
  33. package/src/cli/worktree-isolation.mjs +3 -1
  34. package/src/cli/worktree-isolation.test.mjs +13 -0
  35. package/src/cli/worktree.mjs +145 -0
  36. package/src/cli/worktree.test.mjs +110 -0
  37. package/src/config.mjs +9 -0
  38. package/src/enforcement-map.mjs +2 -1
  39. package/src/gates/english-source.mjs +13 -9
  40. package/src/gates/english-source.test.mjs +19 -1
  41. package/src/generated-markers.mjs +16 -0
  42. package/src/glob.mjs +23 -0
  43. package/templates/CLAUDE.md +1 -1
@@ -14,12 +14,15 @@
14
14
  // file for free and need nothing further from this script.
15
15
 
16
16
  import { execFile } from "node:child_process";
17
- import { existsSync, readFileSync, realpathSync } from "node:fs";
17
+ import { existsSync, realpathSync } from "node:fs";
18
18
  import path from "node:path";
19
19
  import { fileURLToPath } from "node:url";
20
20
  import { promisify } from "node:util";
21
21
  import { load } from "../config.mjs";
22
+ import { globToRegExp } from "../glob.mjs";
23
+ import { ignoredPaths } from "./ignored-paths.mjs";
22
24
  import { claimLease, leaseFileOf, readLease } from "./lease-file.mjs";
25
+ import { MANIFEST_FILE, readManifest } from "./work-order-manifest.mjs";
23
26
  import {
24
27
  OFF,
25
28
  denyOutput as isolationDeny,
@@ -35,14 +38,7 @@ const slashed = (file) => file.split(path.sep).join("/");
35
38
  // The refusal names this copy of the CLI: a repository's own `qc` can be a version with no `lease`.
36
39
  const QC = `node "${slashed(fileURLToPath(new URL("./qc.mjs", import.meta.url)))}"`;
37
40
 
38
- export function globToRegExp(glob) {
39
- const body = glob
40
- .replace(/[.+^${}()|[\]\\]/g, "\\$&")
41
- .replace(/\*\*/g, "\u0000")
42
- .replace(/\*/g, "[^/]*")
43
- .replace(/\u0000/g, ".*");
44
- return new RegExp(`^${body}$`);
45
- }
41
+ export { globToRegExp };
46
42
 
47
43
  /** @param {string} relPath forward-slash, relative to the work order manifest's own root */
48
44
  export function isAllowed(relPath, patterns) {
@@ -81,7 +77,7 @@ export function denyOutput(relPath, patterns) {
81
77
  permissionDecision: "deny",
82
78
  permissionDecisionReason:
83
79
  `"${relPath}" is outside this work order's declared paths ` +
84
- `(.claude/work-order.local.json: ${patterns.join(", ")}). ` +
80
+ `(${MANIFEST_FILE}: ${patterns.join(", ")}). ` +
85
81
  "Ask the orchestrator before editing outside scope, or update the manifest if the scope was wrong.",
86
82
  },
87
83
  };
@@ -144,7 +140,7 @@ async function isolationVerdict(root, relPath, call) {
144
140
  return null;
145
141
  }
146
142
  const sessionId = sessionIdOf(call.session_id);
147
- const reason = isolationRefusal({
143
+ const facts = {
148
144
  settings,
149
145
  branch: state.branch,
150
146
  kind: state.kind,
@@ -155,8 +151,14 @@ async function isolationVerdict(root, relPath, call) {
155
151
  leaseFile: slashed(leaseFileOf(state.gitDir)),
156
152
  root: slashed(root),
157
153
  qc: QC,
158
- });
159
- if (reason) return isolationDeny(reason);
154
+ };
155
+ if (isolationRefusal(facts)) {
156
+ // Asked only on the refusal path, so an edit that passes costs no extra git process.
157
+ const ignored = (await ignoredPaths(root, [relPath])).has(relPath);
158
+ const reason = isolationRefusal({ ...facts, ignored });
159
+ if (reason) return isolationDeny(reason);
160
+ return null;
161
+ }
160
162
  // Only the PreToolUse hook claims: a hand run of this script with a made-up session never does.
161
163
  if (call.hook_event_name === "PreToolUse") claimLease(state.gitDir, sessionId, state.branch);
162
164
  return null;
@@ -188,9 +190,8 @@ export async function decide(call, root) {
188
190
  if (refusal) return refusal;
189
191
  }
190
192
 
191
- const manifestPath = path.join(root, ".claude", "work-order.local.json");
192
- if (!existsSync(manifestPath)) return null;
193
- const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
193
+ const manifest = readManifest(root);
194
+ if (!manifest) return null;
194
195
  await warnOnBranchMismatch(root, manifest);
195
196
 
196
197
  const patterns = manifest.paths ?? [];
@@ -216,11 +217,8 @@ export async function runWorkOrderCheck(root) {
216
217
  // -- sed, a heredoc, a script -- never reaches it. A commit cannot be made without git.
217
218
  if (await isolationCommitRefusal(root)) return 1;
218
219
 
219
- const manifestPath = path.join(root, ".claude", "work-order.local.json");
220
- if (!existsSync(manifestPath)) return 0;
221
-
222
- const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
223
- if (!manifest.branch) return 0;
220
+ const manifest = readManifest(root);
221
+ if (!manifest?.branch) return 0;
224
222
  if (inSpecialGitOperation(path.join(root, ".git"))) return 0;
225
223
 
226
224
  const reason = branchMismatch(manifest.branch, await currentBranch(root));
@@ -91,6 +91,7 @@ function isolatedRepository() {
91
91
  mkdirSync(outside);
92
92
  git(primary, "init", "-q", "-b", "main");
93
93
  writeFileSync(path.join(primary, "qc.config.json"), JSON.stringify({ swarm: { isolation: { require: "worktree" } } }));
94
+ writeFileSync(path.join(primary, ".gitignore"), "*.local.json\n");
94
95
  git(primary, "add", ".");
95
96
  git(primary, "-c", "user.name=qc", "-c", "user.email=qc@example.com", "commit", "-q", "-m", "init");
96
97
  git(primary, "worktree", "add", "-q", linked, "-b", "feat/work-order");
@@ -118,6 +119,23 @@ test("an edit in the primary checkout on a protected branch is still refused", a
118
119
  assert.match(output.hookSpecificOutput.permissionDecisionReason, /"main" is a protected branch/);
119
120
  });
120
121
 
122
+ test("on a protected branch, an ignored local file passes and claims no lease", async (t) => {
123
+ const repo = isolatedRepository();
124
+ t.after(repo.cleanup);
125
+ const file = path.join(repo.primary, ".claude", "settings.local.json");
126
+ assert.equal(await decide({ ...editOf(file), hook_event_name: "PreToolUse" }, repo.primary), null);
127
+ assert.equal(existsSync(leaseFileOf(repo.primary)), false);
128
+ });
129
+
130
+ test("on a protected branch, a tracked file and a new unignored file are refused", async (t) => {
131
+ const repo = isolatedRepository();
132
+ t.after(repo.cleanup);
133
+ for (const file of ["qc.config.json", path.join("src", "new.ts")]) {
134
+ const output = await decide(editOf(path.join(repo.primary, file)), repo.primary);
135
+ assert.match(output.hookSpecificOutput.permissionDecisionReason, /"main" is a protected branch/, file);
136
+ }
137
+ });
138
+
121
139
  test("the primary checkout is refused even when the session opened the linked worktree", async (t) => {
122
140
  const repo = isolatedRepository();
123
141
  t.after(repo.cleanup);
@@ -0,0 +1,14 @@
1
+ // The resource for a work order's declaration: the gitignored manifest in the project root that
2
+ // names the paths and the branch the work order owns. Both edit guards read it through here.
3
+
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import path from "node:path";
6
+
7
+ export const MANIFEST_FILE = ".claude/work-order.local.json";
8
+
9
+ /** @returns the parsed manifest, or null when the project declares no work order. */
10
+ export function readManifest(root) {
11
+ const file = path.join(root, MANIFEST_FILE);
12
+ if (!existsSync(file)) return null;
13
+ return JSON.parse(readFileSync(file, "utf8"));
14
+ }
@@ -94,13 +94,15 @@ function heldRefusal(held, { branch, now, leaseFile, root, qc }) {
94
94
  * @returns a reason string to refuse the edit, or null to allow it.
95
95
  */
96
96
  export function isolationRefusal(state) {
97
- const { settings, branch, kind, inSpecialOperation, lease, sessionId, now } = state;
97
+ const { settings, branch, kind, inSpecialOperation, lease, sessionId, now, ignored = false } = state;
98
98
  if (settings.require === OFF) return null;
99
99
  if (inSpecialOperation) return null;
100
100
 
101
101
  if (!branch) {
102
102
  return "HEAD is detached, so this edit belongs to no branch. Check out a work-order branch before generating code.";
103
103
  }
104
+ // A path git ignores is local configuration, and it can never reach a commit on any branch.
105
+ if (ignored) return null;
104
106
  if (settings.protectedBranches.includes(branch)) {
105
107
  return (
106
108
  `"${branch}" is a protected branch and an agent does not generate code on it. ` +
@@ -38,6 +38,19 @@ test("an agent on its own branch in its own worktree is allowed", () => {
38
38
  assert.equal(isolationRefusal(base()), null);
39
39
  });
40
40
 
41
+ test("an ignored path passes on a protected branch, because it never reaches a commit", () => {
42
+ assert.equal(isolationRefusal(base({ branch: "main", kind: "linked", ignored: true })), null);
43
+ });
44
+
45
+ test("an ignored path passes in the primary worktree and past another session's lease", () => {
46
+ const lease = { sessionId: "session-bbbb", branch: "main", updatedAt: new Date(NOW).toISOString() };
47
+ assert.equal(isolationRefusal(base({ branch: "main", kind: "primary", lease, ignored: true })), null);
48
+ });
49
+
50
+ test("an ignored path is still refused on a detached HEAD", () => {
51
+ assert.match(isolationRefusal(base({ branch: "", ignored: true })), /detached/);
52
+ });
53
+
41
54
  test("generating code on a protected branch is refused and names the branch", () => {
42
55
  const reason = isolationRefusal(base({ branch: "main" }));
43
56
  assert.match(reason, /"main" is a protected branch/);
@@ -0,0 +1,145 @@
1
+ // A pipeline: `qc worktree add` makes a linked worktree beside the main checkout and installs it.
2
+ // `qc worktree remove` deletes one, and deletes its branch only when no commit would be lost.
3
+
4
+ import { spawnSync } from "node:child_process";
5
+ import { existsSync, realpathSync } from "node:fs";
6
+ import { rm } from "node:fs/promises";
7
+ import path from "node:path";
8
+
9
+ export const USAGE = `qc worktree — a linked worktree beside the main checkout
10
+
11
+ qc worktree add <name> <branch> [--from <ref>] fetch, add ../<name> on <branch>, install, print the path
12
+ qc worktree remove <name> [--from <ref>] refuse a dirty tree; delete it, then the branch once merged or pushed
13
+
14
+ --from the ref a new branch starts at, and the ref remove checks a merge against.
15
+ The default is worktree.base in qc.config.json. The install is worktree.install.`;
16
+
17
+ function git(cwd, ...args) {
18
+ const result = spawnSync("git", args, { cwd, encoding: "utf8" });
19
+ return { ok: result.status === 0, out: (result.stdout ?? "").trim(), err: (result.stderr ?? "").trim() };
20
+ }
21
+
22
+ /** One spelling per folder: Windows hands out short 8.3 names, and git prints the long ones. */
23
+ function keyOf(file) {
24
+ let real;
25
+ try {
26
+ real = realpathSync.native(file);
27
+ } catch {
28
+ const parent = path.dirname(file);
29
+ real = parent === file ? file : path.join(keyOf(parent), path.basename(file));
30
+ }
31
+ return process.platform === "win32" ? path.resolve(real).toLowerCase() : path.resolve(real);
32
+ }
33
+
34
+ function mainCheckout(cwd) {
35
+ const common = git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir");
36
+ return common.ok ? path.dirname(common.out) : null;
37
+ }
38
+
39
+ /** @returns {{path: string, branch?: string}[]} */
40
+ function worktrees(main) {
41
+ return git(main, "worktree", "list", "--porcelain")
42
+ .out.split(/\n\s*\n/)
43
+ .map((block) => {
44
+ const field = (name) => block.split("\n").find((line) => line.startsWith(`${name} `))?.slice(name.length + 1);
45
+ return { path: field("worktree"), branch: field("branch")?.replace(/^refs\/heads\//, "") };
46
+ })
47
+ .filter((entry) => entry.path);
48
+ }
49
+
50
+ async function add(config, main, target, branch, from) {
51
+ const found = worktrees(main).find((entry) => keyOf(entry.path) === keyOf(target));
52
+ if (found && found.branch !== branch) {
53
+ console.error(`${target} is a worktree on ${found.branch ?? "a detached HEAD"}, not ${branch}.`);
54
+ return 1;
55
+ }
56
+ if (!found) {
57
+ if (existsSync(target)) {
58
+ console.error(`${target} exists and is not a worktree of this repository.`);
59
+ return 1;
60
+ }
61
+ const fetched = git(main, "fetch", "--quiet");
62
+ if (!fetched.ok) {
63
+ console.error(fetched.err);
64
+ return 1;
65
+ }
66
+ const exists = git(main, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).ok;
67
+ const made = exists
68
+ ? git(main, "worktree", "add", target, branch)
69
+ : git(main, "worktree", "add", target, "-b", branch, from);
70
+ if (!made.ok) {
71
+ console.error(made.err);
72
+ return 1;
73
+ }
74
+ }
75
+ // Every add runs the install, so a second add finishes what a failed install left.
76
+ const install = config.worktree?.install;
77
+ if (install) {
78
+ const ran = spawnSync(install, { cwd: target, shell: true, stdio: "inherit" });
79
+ if (ran.status !== 0) {
80
+ console.error(`the install failed in ${target}: ${install}`);
81
+ return ran.status ?? 1;
82
+ }
83
+ }
84
+ console.log(target);
85
+ return 0;
86
+ }
87
+
88
+ /** A branch goes only when the base holds it, or its upstream holds every commit. */
89
+ function settleBranch(main, branch, from) {
90
+ const merged = git(main, "merge-base", "--is-ancestor", branch, from).ok;
91
+ const upstream = git(main, "rev-parse", "--abbrev-ref", `${branch}@{upstream}`);
92
+ const pushed = upstream.ok && git(main, "rev-list", "--count", `${upstream.out}..${branch}`).out === "0";
93
+ if (!merged && !pushed) return `kept branch ${branch}: ${from} does not hold it, and it has commits no remote holds`;
94
+ const deleted = git(main, "branch", "-D", branch);
95
+ return deleted.ok ? `deleted branch ${branch}` : `kept branch ${branch}: ${deleted.err}`;
96
+ }
97
+
98
+ async function remove(main, target, from) {
99
+ if (keyOf(target) === keyOf(main)) {
100
+ console.error("refusing to remove the main checkout.");
101
+ return 1;
102
+ }
103
+ const found = worktrees(main).find((entry) => keyOf(entry.path) === keyOf(target));
104
+ if (!found) {
105
+ if (existsSync(target)) {
106
+ console.error(`${target} is not a worktree of this repository. Nothing was removed.`);
107
+ return 1;
108
+ }
109
+ console.log(`no worktree at ${target}; nothing to remove`);
110
+ return 0;
111
+ }
112
+ if (existsSync(target)) {
113
+ const status = git(target, "status", "--porcelain");
114
+ if (!status.ok || status.out !== "") {
115
+ console.error(`${target} has uncommitted changes. Commit or discard them first:\n${status.out || status.err}`);
116
+ return 1;
117
+ }
118
+ // `git worktree remove` fails on Windows past 260 characters. Node's fs reaches long paths.
119
+ await rm(target, { recursive: true, force: true, maxRetries: 5 });
120
+ }
121
+ git(main, "worktree", "prune");
122
+ if (found.branch) console.log(settleBranch(main, found.branch, from));
123
+ console.log(`removed ${target}`);
124
+ return 0;
125
+ }
126
+
127
+ /**
128
+ * @param {object} config
129
+ * @param {string[]} args `add <name> <branch> [--from <ref>]` or `remove <name> [--from <ref>]`
130
+ * @returns {Promise<number>} the exit code
131
+ */
132
+ export async function runWorktree(config, args) {
133
+ const [command, ...rest] = args;
134
+ const at = rest.indexOf("--from");
135
+ const from = at === -1 ? config.worktree?.base ?? "origin/main" : rest[at + 1];
136
+ const [name, branch] = at === -1 ? rest : [...rest.slice(0, at), ...rest.slice(at + 2)];
137
+ const main = mainCheckout(config.root);
138
+ const usable = main && from && name && !/[\\/]/.test(name) && name !== "." && name !== "..";
139
+ if (!usable || !(command === "remove" || (command === "add" && branch))) {
140
+ console.error(main ? USAGE : "qc worktree runs inside a git repository.");
141
+ return 1;
142
+ }
143
+ const target = path.join(path.dirname(main), name);
144
+ return command === "add" ? add(config, main, target, branch, from) : remove(main, target, from);
145
+ }
@@ -0,0 +1,110 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFileSync, spawnSync } from "node:child_process";
4
+ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const QC = fileURLToPath(new URL("./qc.mjs", import.meta.url));
10
+ const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" }).trim();
11
+ const qc = (cwd, ...args) => spawnSync(process.execPath, [QC, "worktree", ...args], { cwd, encoding: "utf8" });
12
+ const lastLine = (out) => out.trim().split(/\r?\n/).at(-1);
13
+
14
+ // The install writes only what git ignores, as pnpm does, so a fresh worktree stays clean.
15
+ const INSTALL = `node -e "require('fs').mkdirSync('node_modules',{recursive:true})"`;
16
+
17
+ /** A main checkout at <top>/main with a pushed main branch, so worktrees land inside <top>. */
18
+ function fixture() {
19
+ const top = mkdtempSync(path.join(tmpdir(), "qc-wt-"));
20
+ const origin = path.join(top, "origin.git");
21
+ const main = path.join(top, "main");
22
+ mkdirSync(main);
23
+ git(top, "init", "-q", "--bare", "-b", "main", origin);
24
+ git(main, "init", "-q", "-b", "main");
25
+ git(main, "config", "user.name", "qc");
26
+ git(main, "config", "user.email", "qc@example.com");
27
+ git(main, "config", "commit.gpgsign", "false");
28
+ writeFileSync(path.join(main, ".gitignore"), "node_modules/\n");
29
+ writeFileSync(path.join(main, "qc.config.json"), JSON.stringify({ worktree: { install: INSTALL } }));
30
+ git(main, "add", ".");
31
+ git(main, "commit", "-q", "-m", "init");
32
+ git(main, "remote", "add", "origin", origin);
33
+ git(main, "push", "-q", "-u", "origin", "main");
34
+ return { top, main };
35
+ }
36
+
37
+ function added(main, name, branch) {
38
+ const result = qc(main, "add", name, branch);
39
+ assert.equal(result.status, 0, result.stderr);
40
+ return lastLine(result.stdout);
41
+ }
42
+
43
+ test("add makes a worktree beside the main checkout and installs it; remove deletes it and its merged branch", () => {
44
+ const { top, main } = fixture();
45
+ const where = added(main, "wt-a", "feat/a");
46
+ assert.equal(realpathSync.native(where), realpathSync.native(path.join(top, "wt-a")));
47
+ assert.ok(existsSync(path.join(where, "node_modules")), "the install command did not run in the worktree");
48
+ assert.equal(git(where, "branch", "--show-current"), "feat/a");
49
+ assert.equal(added(main, "wt-a", "feat/a"), where, "a second add must find the same worktree");
50
+
51
+ const removed = qc(main, "remove", "wt-a");
52
+ assert.equal(removed.status, 0, removed.stderr);
53
+ assert.equal(existsSync(where), false);
54
+ assert.equal(git(main, "branch", "--list", "feat/a"), "");
55
+ assert.doesNotMatch(git(main, "worktree", "list"), /wt-a/);
56
+ const again = qc(main, "remove", "wt-a");
57
+ assert.equal(again.status, 0, again.stderr);
58
+ rmSync(top, { recursive: true, force: true });
59
+ });
60
+
61
+ test("remove refuses a tree with uncommitted changes and leaves it in place", () => {
62
+ const { top, main } = fixture();
63
+ const where = added(main, "wt-b", "feat/b");
64
+ writeFileSync(path.join(where, "draft.txt"), "unsaved\n");
65
+ const refused = qc(main, "remove", "wt-b");
66
+ assert.equal(refused.status, 1);
67
+ assert.match(refused.stderr, /draft\.txt/);
68
+ assert.ok(existsSync(path.join(where, "draft.txt")));
69
+ rmSync(top, { recursive: true, force: true });
70
+ });
71
+
72
+ test("remove keeps a branch with an unpushed commit, and deletes it once pushed", () => {
73
+ const { top, main } = fixture();
74
+ let where = added(main, "wt-c", "feat/c");
75
+ writeFileSync(path.join(where, "work.txt"), "done\n");
76
+ git(where, "add", "work.txt");
77
+ git(where, "commit", "-q", "-m", "work");
78
+ const kept = qc(main, "remove", "wt-c");
79
+ assert.equal(kept.status, 0, kept.stderr);
80
+ assert.equal(existsSync(where), false);
81
+ assert.match(kept.stdout, /kept branch feat\/c/);
82
+ assert.notEqual(git(main, "branch", "--list", "feat/c"), "");
83
+
84
+ where = added(main, "wt-c", "feat/c");
85
+ assert.ok(existsSync(path.join(where, "work.txt")), "the existing branch must be checked out, not recreated");
86
+ git(where, "push", "-q", "-u", "origin", "feat/c");
87
+ const deleted = qc(main, "remove", "wt-c");
88
+ assert.equal(deleted.status, 0, deleted.stderr);
89
+ assert.equal(git(main, "branch", "--list", "feat/c"), "");
90
+ rmSync(top, { recursive: true, force: true });
91
+ });
92
+
93
+ // Windows refuses a path past 260 characters to most tools, `git worktree remove` among them.
94
+ // Every OS runs this; the windows-latest job is the proof.
95
+ test("remove deletes a worktree that holds a path longer than 260 characters", () => {
96
+ const { top, main } = fixture();
97
+ const where = added(main, "wt-long", "feat/long");
98
+ const segments = Array.from({ length: 6 }, (_, i) => `${"segment".repeat(7)}-${i}`);
99
+ const deep = path.join(where, "node_modules", ...segments);
100
+ mkdirSync(deep, { recursive: true });
101
+ writeFileSync(path.join(deep, "index.js"), "module.exports = {};\n");
102
+ assert.ok(path.join(deep, "index.js").length > 260, `the fixture path is only ${path.join(deep, "index.js").length} characters`);
103
+ assert.ok(existsSync(path.join(deep, "index.js")));
104
+
105
+ const removed = qc(main, "remove", "wt-long");
106
+ assert.equal(removed.status, 0, removed.stderr);
107
+ assert.equal(existsSync(where), false);
108
+ assert.doesNotMatch(git(main, "worktree", "list"), /wt-long/);
109
+ rmSync(top, { recursive: true, force: true });
110
+ });
package/src/config.mjs CHANGED
@@ -206,8 +206,17 @@ export const defaults = {
206
206
  // restricted. `require`: off | branch (refuse the trunk) | worktree (also refuse the primary).
207
207
  swarm: {
208
208
  isolation: { require: "off", protectedBranches: ["main", "master"], leaseHours: 8, allow: [] },
209
+ // Tool calls per subagent. The hook reminds at seventy percent and denies all but the hand-off at the budget.
210
+ toolCallBudget: 100,
209
211
  },
210
212
 
213
+ // Files a generator writes. The generated-file hook refuses a hand edit of one and names `command`.
214
+ generated: { globs: ["**/*.generated.*"], command: "pnpm codegen" },
215
+
216
+ // `qc worktree`. `install` runs in each new worktree. `base` is the default `--from`: the ref a
217
+ // branch starts at, and the ref `remove` checks a merge against.
218
+ worktree: { install: "pnpm install --frozen-lockfile", base: "origin/main" },
219
+
211
220
  // Names that must be registered scoped, never singleton.
212
221
  scopedSuffixes: ["Repository", "Saga", "UnitOfWork", "UnitOfWorkFactory"],
213
222
 
@@ -3,9 +3,10 @@
3
3
  import { enabled } from "./config.mjs";
4
4
  import { gateDescriptions } from "./descriptions.mjs";
5
5
  import { rules } from "./eslint/index.mjs";
6
+ import { GENERATED_CLOSE } from "./generated-markers.mjs";
6
7
 
7
8
  export const OPEN = "<!-- generated: rule-to-check. -->";
8
- export const CLOSE = "<!-- /generated -->";
9
+ export const CLOSE = GENERATED_CLOSE;
9
10
  // A repository may annotate the open marker with its own reminder (e.g. "pnpm codegen.") —
10
11
  // matched by prefix, not by exact string, so that annotation does not break detection.
11
12
  const OPEN_PATTERN = /<!--\s*generated:\s*rule-to-check\.[^>]*-->/;
@@ -5,6 +5,8 @@
5
5
  // The line is prose against data. Prose a developer writes for another developer is English. Data
6
6
  // the product needs in another language is declared, and its English variant must exist beside it.
7
7
 
8
+ import { globToRegExp } from "../glob.mjs";
9
+
8
10
  const SCRIPTS = {
9
11
  // Hiragana, katakana, CJK ideographs, Hangul: language a reader must know to follow the text.
10
12
  cjk: "\\u3040-\\u30ff\\u3400-\\u4dbf\\u4e00-\\u9fff\\uac00-\\ud7af",
@@ -19,15 +21,6 @@ function scriptPattern(scripts) {
19
21
  return new RegExp(`[${ranges}]`);
20
22
  }
21
23
 
22
- function globToRegExp(glob) {
23
- const body = glob
24
- .replace(/[.+^${}()|[\]\\]/g, "\\$&")
25
- .replace(/\*\*/g, "\u0000")
26
- .replace(/\*/g, "[^/]*")
27
- .replace(/\u0000/g, ".*");
28
- return new RegExp(`^${body}$`);
29
- }
30
-
31
24
  export function matchesAny(relPath, globs) {
32
25
  return globs.some((glob) => globToRegExp(glob).test(relPath));
33
26
  }
@@ -152,6 +145,17 @@ export function checkEnglishSource(files, options = {}) {
152
145
  return problems;
153
146
  }
154
147
 
148
+ // The stale-entry and budget rules judge the whole ledger, so only the full pass can run them.
149
+ const PER_FILE_RULES = new Set(["english-comment", "english-source", "legacy-entry-grew"]);
150
+
151
+ /**
152
+ * The rules that judge one file alone, for the files a hook or a commit names.
153
+ * @param {{path: string, contents: string}[]} files paths relative to the repository root
154
+ */
155
+ export function checkEnglishFiles(files, options = {}) {
156
+ return checkEnglishSource(files, options).filter((problem) => PER_FILE_RULES.has(problem.rule));
157
+ }
158
+
155
159
  /**
156
160
  * Every declared translation has an English variant beside it, so English is the one language
157
161
  * present in every set -- the main variant, whatever else a repository adds.
@@ -1,6 +1,24 @@
1
1
  import { strict as assert } from "node:assert";
2
2
  import { test } from "node:test";
3
- import { checkEnglishSource, checkTranslationPairs, commentLines } from "./english-source.mjs";
3
+ import { checkEnglishFiles, checkEnglishSource, checkTranslationPairs, commentLines } from "./english-source.mjs";
4
+
5
+ test("the per-file rules report a Japanese comment in a named file", () => {
6
+ const problems = checkEnglishFiles(file("src/a.ts", "// 図面 keeps its card."));
7
+ assert.deepEqual(problems.map((problem) => problem.rule), ["english-comment"]);
8
+ });
9
+
10
+ // A commit names a few files. A ledger entry for a file it did not name is not stale.
11
+ test("the per-file rules leave the ledger-wide rules to the full pass", () => {
12
+ const options = { legacyNonEnglish: { "docs/old.md": 3, "docs/bare.md": true }, legacyBudget: 1 };
13
+ assert.deepEqual(checkEnglishFiles(file("src/a.ts", "export const a = 1;"), options), []);
14
+ assert.ok(checkEnglishSource(file("src/a.ts", "export const a = 1;"), options).length > 0);
15
+ });
16
+
17
+ test("the per-file rules still refuse a ledger file that grew", () => {
18
+ const options = { legacyNonEnglish: { "docs/old.md": 1 } };
19
+ const problems = checkEnglishFiles(file("docs/old.md", "図面 and 図面"), options);
20
+ assert.deepEqual(problems.map((problem) => problem.rule), ["legacy-entry-grew"]);
21
+ });
4
22
 
5
23
  const file = (path, contents) => [{ path, contents }];
6
24
 
@@ -0,0 +1,16 @@
1
+ // A fragment: the markers around a generated region of a Markdown file. The enforcement map writes its
2
+ // table between them, and the generated-file guard refuses a hand edit inside them.
3
+
4
+ export const GENERATED_CLOSE = "<!-- /generated -->";
5
+ const GENERATED_OPEN = /<!--\s*generated:[^>]*-->/g;
6
+
7
+ /** @returns each generated region as `[start, end)`, from its open marker through its close marker or the end. */
8
+ export function generatedRegions(markdown) {
9
+ const regions = [];
10
+ for (const found of markdown.matchAll(GENERATED_OPEN)) {
11
+ const close = markdown.indexOf(GENERATED_CLOSE, found.index);
12
+ const end = close === -1 ? markdown.length : close + GENERATED_CLOSE.length;
13
+ if (regions.length === 0 || found.index >= regions.at(-1)[1]) regions.push([found.index, end]);
14
+ }
15
+ return regions;
16
+ }
package/src/glob.mjs ADDED
@@ -0,0 +1,23 @@
1
+ // A fragment: the one glob matcher. The work-order guard, the English gate and the file lister
2
+ // all read globs from qc.config.json, so they must agree on what a glob matches.
3
+
4
+ /** `**` crosses folders and `*` stays inside one. Every other character is literal. */
5
+ export function globToRegExp(glob) {
6
+ const body = glob
7
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
8
+ .replace(/\*\*/g, "\u0000")
9
+ .replace(/\*/g, "[^/]*")
10
+ .replace(/\u0000/g, ".*");
11
+ return new RegExp(`^${body}$`);
12
+ }
13
+
14
+ /**
15
+ * A matcher for a list of globs over repository-relative paths. A leading `**` also matches at the
16
+ * root, as ESLint reads the same globs: `**\/*.generated.*` matches `a.generated.ts` and `src/a.generated.ts`.
17
+ * @param {readonly string[]} globs
18
+ * @returns {(rel: string) => boolean}
19
+ */
20
+ export function globMatcher(globs) {
21
+ const patterns = globs.map(globToRegExp);
22
+ return (rel) => patterns.some((pattern) => pattern.test(rel) || pattern.test(`/${rel}`));
23
+ }
@@ -26,7 +26,7 @@ every one here — this table is what an agent reads instead of guessing.
26
26
  ```bash
27
27
  pnpm spec:check # every structural gate (qc check)
28
28
  pnpm gen:feature <name> # scaffold a feature. Full domain name, never a code
29
- npx qc check <file> # the fast path a post-edit hook takes
29
+ npx qc check <file>... # the fast path a post-edit hook or a commit takes
30
30
  npx qc config # print the configuration in force
31
31
  ```
32
32