architecture-harness 0.18.2 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/cli/bash-command-guard.mjs +60 -11
- package/src/cli/bash-command-guard.test.mjs +66 -0
- package/src/cli/check-input.mjs +24 -0
- package/src/cli/check.mjs +2 -2
- package/src/cli/cli.test.mjs +50 -1
- package/src/cli/init.mjs +12 -0
- package/src/cli/merge-guard.mjs +4 -0
- package/src/cli/merge-guard.test.mjs +21 -2
- package/src/cli/powershell-command.mjs +1 -1
- package/src/cli/qc.mjs +9 -4
- package/src/cli/workflow-hooks.test.mjs +1 -0
- package/src/cli/worktree-gate.mjs +117 -0
- package/src/cli/worktree-gate.test.mjs +152 -0
- package/src/cli/worktree-settings.mjs +27 -0
- package/src/cli/worktree.mjs +60 -21
- package/src/cli/worktree.test.mjs +106 -7
- package/src/config.mjs +8 -1
- package/src/eslint/preset.mjs +2 -2
- package/src/eslint/preset.test.mjs +4 -2
- package/src/gates/sql-identifiers.mjs +11 -3
- package/src/gates/sql-identifiers.test.mjs +39 -0
- package/templates/.jscpd.json +1 -0
- package/templates/docs/decisions.md +1 -0
- package/templates/docs/enforcement.md +10 -0
- package/templates/githooks/pre-commit +8 -6
package/package.json
CHANGED
|
@@ -1,18 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// The PreToolUse trigger that refuses a Bash or PowerShell command which skips the git hooks,
|
|
3
|
-
//
|
|
2
|
+
// The PreToolUse trigger that refuses a Bash or PowerShell command which skips the git hooks, runs a hook script
|
|
3
|
+
// by hand, or adds a worktree outside the worktree folder (QC-015). It reads the command and never runs it.
|
|
4
4
|
|
|
5
5
|
import { existsSync } from "node:fs";
|
|
6
|
+
import os from "node:os";
|
|
6
7
|
import path from "node:path";
|
|
7
8
|
import { fileURLToPath } from "node:url";
|
|
8
9
|
import { CONFIG_FILE } from "../config.mjs";
|
|
9
10
|
import { checkoutRootOf } from "./checkout-root.mjs";
|
|
10
|
-
import { powershellSegments } from "./powershell-command.mjs";
|
|
11
|
-
import { commandWords, gitCall, segmentsOf } from "./shell-command.mjs";
|
|
11
|
+
import { locationTarget, powershellSegments } from "./powershell-command.mjs";
|
|
12
|
+
import { cdTarget, commandWords, gitCall, segmentsOf } from "./shell-command.mjs";
|
|
13
|
+
import { nativePath } from "./workflow-place.mjs";
|
|
14
|
+
import { keyOf } from "./worktree.mjs";
|
|
15
|
+
import { worktreeRuleAt } from "./worktree-settings.mjs";
|
|
12
16
|
|
|
13
17
|
const HOOK_SCRIPTS = [
|
|
14
18
|
"work-order-guard.mjs", "budget-guard.mjs", "bash-edit-guard.mjs", "worktree-isolation.mjs", "pre-edit-guard.sh",
|
|
15
|
-
"report-stop.mjs", "plan-stop.mjs", "merge-guard.mjs", "issue-gate.mjs", "controller-guard.mjs",
|
|
19
|
+
"report-stop.mjs", "plan-stop.mjs", "merge-guard.mjs", "issue-gate.mjs", "controller-guard.mjs", "worktree-gate.mjs",
|
|
16
20
|
];
|
|
17
21
|
const NO_VERIFY = "--no-verify";
|
|
18
22
|
// The shortest prefix git could still expand to `--no-verify`.
|
|
@@ -28,6 +32,10 @@ const COMMIT_VALUE_FLAGS = new Set(["m", "F", "C", "c", "t"]);
|
|
|
28
32
|
|
|
29
33
|
/** The parser for each guarded tool. */
|
|
30
34
|
export const PARSERS = { Bash: segmentsOf, PowerShell: powershellSegments };
|
|
35
|
+
/** The directory a segment moves to, read the way each parser's shell reads it. */
|
|
36
|
+
const MOVES = new Map([[segmentsOf, cdTarget], [powershellSegments, locationTarget]]);
|
|
37
|
+
/** The options of `git worktree add` whose value is the next word. */
|
|
38
|
+
const WORKTREE_VALUE_OPTIONS = new Set(["-b", "-B", "--reason"]);
|
|
31
39
|
/** A POSIX shell reads a command line from `-c`, alone or in a cluster of short flags: `-lc`, `-ic`, `-lic`, `-cl`. */
|
|
32
40
|
const POSIX_COMMAND_FLAG = /^-[A-Za-z]*c[A-Za-z]*$/;
|
|
33
41
|
const POWERSHELL_COMMAND_FLAG = /^-(c|command)$/i;
|
|
@@ -98,6 +106,29 @@ export function nestedCommand(segment) {
|
|
|
98
106
|
return command === undefined ? null : { command, parse: shell.parse };
|
|
99
107
|
}
|
|
100
108
|
|
|
109
|
+
/** @returns the path that `git worktree add` names after its options, or null for another worktree command. */
|
|
110
|
+
function worktreeAddPath(args) {
|
|
111
|
+
if (args[0] !== "add") return null;
|
|
112
|
+
for (let i = 1; i < args.length; i++) {
|
|
113
|
+
if (args[i] === "--") return args[i + 1] ?? null;
|
|
114
|
+
if (WORKTREE_VALUE_OPTIONS.has(args[i])) i++;
|
|
115
|
+
else if (!args[i].startsWith("-")) return args[i];
|
|
116
|
+
}
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** A path as a shell resolves it from `cwd`. PowerShell also reads a backslash as a separator on Linux and macOS. */
|
|
121
|
+
function resolveFrom(cwd, spelled, parse) {
|
|
122
|
+
const word = parse === powershellSegments ? spelled.replace(/\\/g, "/") : spelled;
|
|
123
|
+
return path.resolve(cwd, nativePath(word.replace(/^~(?=$|[\\/])/, os.homedir())));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** True when `target` is one folder directly under `folder`, as `qc worktree add` makes it. */
|
|
127
|
+
function inFolder(folder, target) {
|
|
128
|
+
const parts = path.relative(keyOf(folder), keyOf(target)).split(path.sep);
|
|
129
|
+
return parts.length === 1 && parts[0] !== "" && parts[0] !== ".." && !path.isAbsolute(parts[0]);
|
|
130
|
+
}
|
|
131
|
+
|
|
101
132
|
const REASONS = {
|
|
102
133
|
hooks:
|
|
103
134
|
"the command skips the git hooks. The pre-commit and pre-push hooks are the gates: run the command " +
|
|
@@ -107,18 +138,32 @@ const REASONS = {
|
|
|
107
138
|
script:
|
|
108
139
|
"a hand run of a hook script writes a lease or a ledger record under a made-up session id, and that lease blocks later " +
|
|
109
140
|
"edits in the worktree for hours. Test a hook only through its own suite (`node --test`), in temporary folders.",
|
|
141
|
+
worktree:
|
|
142
|
+
"a worktree lives in the worktree folder of the main checkout, so git ignores it and `qc worktree remove` finds it. " +
|
|
143
|
+
"Run `npx qc worktree add <name> <branch>` from the repository, or give `git worktree add` a path one level under that folder.",
|
|
110
144
|
};
|
|
111
145
|
|
|
112
|
-
/**
|
|
113
|
-
|
|
146
|
+
/**
|
|
147
|
+
* @param {{cwd: string, folder: string} | null} [place] the working directory and the worktree folder; null skips the worktree rule
|
|
148
|
+
* @returns the reasons the command breaks a rule, in a stable order.
|
|
149
|
+
*/
|
|
150
|
+
export function violations(command, parse = segmentsOf, place = null) {
|
|
114
151
|
const segments = parse(command);
|
|
115
152
|
const found = new Set();
|
|
153
|
+
let cwd = place?.cwd;
|
|
116
154
|
for (const segment of segments) {
|
|
155
|
+
const moved = place ? MOVES.get(parse)?.(segment) : null;
|
|
156
|
+
if (moved != null) cwd = resolveFrom(cwd, moved, parse);
|
|
117
157
|
const git = gitCall(segment);
|
|
118
158
|
if (git && skipsHooks(git)) found.add("hooks");
|
|
119
159
|
if (git && setsHooksPath(git)) found.add("hooksPath");
|
|
160
|
+
const added = place && git?.sub === "worktree" ? worktreeAddPath(git.args) : null;
|
|
161
|
+
if (added !== null) {
|
|
162
|
+
const from = git.dirs.filter(Boolean).reduce((dir, next) => resolveFrom(dir, next, parse), cwd);
|
|
163
|
+
if (!inFolder(place.folder, resolveFrom(from, added, parse))) found.add("worktree");
|
|
164
|
+
}
|
|
120
165
|
const nested = nestedCommand(segment);
|
|
121
|
-
if (nested) for (const key of violations(nested.command, nested.parse)) found.add(key);
|
|
166
|
+
if (nested) for (const key of violations(nested.command, nested.parse, place && { ...place, cwd })) found.add(key);
|
|
122
167
|
}
|
|
123
168
|
if (!segments.some(runsTests) && segments.some(runsHookScript)) found.add("script");
|
|
124
169
|
return Object.keys(REASONS).filter((key) => found.has(key));
|
|
@@ -129,15 +174,19 @@ export function decide(call) {
|
|
|
129
174
|
const command = call.tool_input?.command;
|
|
130
175
|
const parse = PARSERS[call.tool_name];
|
|
131
176
|
if (!parse || typeof command !== "string") return null;
|
|
132
|
-
const
|
|
177
|
+
const cwd = call.cwd ?? process.cwd();
|
|
178
|
+
const root = checkoutRootOf(cwd);
|
|
133
179
|
if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
|
|
134
|
-
|
|
180
|
+
// The config is read only for a command that can add a worktree, so every other call stays cheap.
|
|
181
|
+
const rule = /\bworktree\b/i.test(command) ? worktreeRuleAt(cwd) : null;
|
|
182
|
+
const found = violations(command, parse, rule && { cwd: path.resolve(cwd), folder: rule.folder });
|
|
135
183
|
if (found.length === 0) return null;
|
|
184
|
+
const reasonOf = (key) => (key === "worktree" ? `${REASONS.worktree} The folder is ${rule.folder}.` : REASONS[key]);
|
|
136
185
|
return {
|
|
137
186
|
hookSpecificOutput: {
|
|
138
187
|
hookEventName: "PreToolUse",
|
|
139
188
|
permissionDecision: "deny",
|
|
140
|
-
permissionDecisionReason: `${call.tool_name} command guard: ${found.map(
|
|
189
|
+
permissionDecisionReason: `${call.tool_name} command guard: ${found.map(reasonOf).join(" Also, ")}`,
|
|
141
190
|
},
|
|
142
191
|
};
|
|
143
192
|
}
|
|
@@ -88,6 +88,7 @@ test("a hand run of a hook script is denied, and the reason names the lease", (t
|
|
|
88
88
|
"node src/cli/issue-gate.mjs",
|
|
89
89
|
"node src/cli/plan-stop.mjs",
|
|
90
90
|
"node src/cli/controller-guard.mjs",
|
|
91
|
+
"node src/cli/worktree-gate.mjs",
|
|
91
92
|
]) {
|
|
92
93
|
assert.match(reasonOf(decide(bash(ws.adopted, command))) ?? "", /writes a lease/, command);
|
|
93
94
|
}
|
|
@@ -168,3 +169,68 @@ test("the deny names the tool it guarded", (t) => {
|
|
|
168
169
|
const ws = workspace(t);
|
|
169
170
|
assert.match(reasonOf(decide(powershell(ws.adopted, "git push --no-verify"))), /^PowerShell command guard:/);
|
|
170
171
|
});
|
|
172
|
+
|
|
173
|
+
const outsideFolder = (output) => /npx qc worktree add <name> <branch>/.test(reasonOf(output) ?? "");
|
|
174
|
+
|
|
175
|
+
test("git worktree add to a path outside .worktree/ of the main checkout is refused, and names qc worktree add", (t) => {
|
|
176
|
+
const ws = workspace(t);
|
|
177
|
+
for (const command of [
|
|
178
|
+
"git worktree add ../x",
|
|
179
|
+
"git worktree add -b b ../x origin/main",
|
|
180
|
+
"git worktree add -B b --lock --reason why ../x",
|
|
181
|
+
"git -C .. worktree add x",
|
|
182
|
+
"cd .. && git worktree add x",
|
|
183
|
+
"git worktree add .worktree/a/b",
|
|
184
|
+
"git worktree add x",
|
|
185
|
+
`bash -c 'git worktree add ../x'`,
|
|
186
|
+
"git worktree add -- ../x",
|
|
187
|
+
]) {
|
|
188
|
+
assert.ok(outsideFolder(decide(bash(ws.adopted, command))), command);
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
test("git worktree add under .worktree/, qc worktree add, and other worktree commands pass", (t) => {
|
|
193
|
+
const ws = workspace(t);
|
|
194
|
+
for (const command of [
|
|
195
|
+
"git worktree add .worktree/x",
|
|
196
|
+
"git worktree add -b feat/1-x .worktree/x origin/main",
|
|
197
|
+
"git worktree add --detach -f .worktree/x HEAD",
|
|
198
|
+
"cd .worktree && git worktree add x",
|
|
199
|
+
"cd .. && git worktree add adopted/.worktree/x",
|
|
200
|
+
`git -C .. worktree add "${path.join(ws.adopted, ".worktree", "x")}"`,
|
|
201
|
+
"npx qc worktree add x feat/1-x",
|
|
202
|
+
"git worktree list",
|
|
203
|
+
"git worktree remove ../x",
|
|
204
|
+
]) {
|
|
205
|
+
assert.equal(decide(bash(ws.adopted, command)), null, command);
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
test("a PowerShell git worktree add is held to the same folder", (t) => {
|
|
210
|
+
const ws = workspace(t);
|
|
211
|
+
for (const command of [String.raw`git worktree add ..\x`, String.raw`git worktree add -B b ..\x origin/main`, "Set-Location ..; git worktree add x"]) {
|
|
212
|
+
assert.ok(outsideFolder(decide(powershell(ws.adopted, command))), command);
|
|
213
|
+
}
|
|
214
|
+
for (const command of [String.raw`git worktree add .worktree\x`, String.raw`Set-Location .worktree; git worktree add x`]) {
|
|
215
|
+
assert.equal(decide(powershell(ws.adopted, command)), null, command);
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
test("worktree.dir moves the folder, and worktree.enforce false turns the rule off", (t) => {
|
|
220
|
+
const ws = workspace(t);
|
|
221
|
+
writeFileSync(path.join(ws.adopted, "qc.config.json"), JSON.stringify({ worktree: { dir: "trees" } }));
|
|
222
|
+
assert.ok(outsideFolder(decide(bash(ws.adopted, "git worktree add .worktree/x"))));
|
|
223
|
+
assert.equal(decide(bash(ws.adopted, "git worktree add trees/x")), null);
|
|
224
|
+
writeFileSync(path.join(ws.adopted, "qc.config.json"), JSON.stringify({ worktree: { enforce: false } }));
|
|
225
|
+
assert.equal(decide(bash(ws.adopted, "git worktree add ../x")), null);
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
test("inside a linked worktree, the folder is the main checkout's", (t) => {
|
|
229
|
+
const ws = workspace(t);
|
|
230
|
+
execFileSync("git", ["-c", "user.name=qc", "-c", "user.email=qc@example.com", "commit", "-q", "--allow-empty", "-m", "init"], { cwd: ws.adopted, stdio: "pipe" });
|
|
231
|
+
const linked = path.join(ws.adopted, ".worktree", "wt");
|
|
232
|
+
execFileSync("git", ["worktree", "add", "-q", linked], { cwd: ws.adopted, stdio: "pipe" });
|
|
233
|
+
writeFileSync(path.join(linked, "qc.config.json"), "{}");
|
|
234
|
+
assert.equal(decide(bash(linked, "git worktree add ../x")), null);
|
|
235
|
+
assert.ok(outsideFolder(decide(bash(linked, "git worktree add x"))), "a worktree nested in a worktree is refused");
|
|
236
|
+
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// The file list for `qc check`, from arguments and from `--files-from <path|->` (NUL-separated).
|
|
2
|
+
// A list read from a stream has no length limit, unlike the command line of `npx.cmd`.
|
|
3
|
+
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import process from "node:process";
|
|
6
|
+
|
|
7
|
+
/** @returns {Promise<{ files: string[], listed: boolean }>} `listed` is true when `--files-from` was given. */
|
|
8
|
+
export async function checkFiles(args) {
|
|
9
|
+
const files = [];
|
|
10
|
+
let source;
|
|
11
|
+
for (let i = 0; i < args.length; i++) {
|
|
12
|
+
if (args[i] === "--files-from") source = args[++i] ?? "-";
|
|
13
|
+
else files.push(args[i]);
|
|
14
|
+
}
|
|
15
|
+
if (source === undefined) return { files, listed: false };
|
|
16
|
+
const text = source === "-" ? await readStdin() : await readFile(source, "utf8");
|
|
17
|
+
return { files: [...files, ...text.split("\0").filter(Boolean)], listed: true };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async function readStdin() {
|
|
21
|
+
const chunks = [];
|
|
22
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
23
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
24
|
+
}
|
package/src/cli/check.mjs
CHANGED
|
@@ -42,7 +42,7 @@ import { checkAdrFormat } from "../gates/adr-format.mjs";
|
|
|
42
42
|
import { checkConfigFloor } from "../gates/config-floor.mjs";
|
|
43
43
|
import { defaults } from "../config.mjs";
|
|
44
44
|
import { rules as lintRules } from "../eslint/index.mjs";
|
|
45
|
-
import { adrLog, enabled, readerEntries, requiredHooks, thresholds } from "../config.mjs";
|
|
45
|
+
import { adrLog, enabled, ignoresOf, readerEntries, requiredHooks, thresholds } from "../config.mjs";
|
|
46
46
|
import { checkRegistryReaders } from "../gates/registry-readers.mjs";
|
|
47
47
|
import { checkMigrationNumbers } from "../gates/migration-numbers.mjs";
|
|
48
48
|
import { checkRegistryLiteral } from "../gates/registry-literal.mjs";
|
|
@@ -569,7 +569,7 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
|
|
|
569
569
|
.map((file) => relativeTo(config.root)(path.resolve(config.root, file)))
|
|
570
570
|
.filter((rel) => !rel.startsWith("../") && !path.isAbsolute(rel));
|
|
571
571
|
const pathspecs = perFile ? scopeOf(config, given) : undefined;
|
|
572
|
-
const tree = treeOf(await lister(config.root, { ignores: config
|
|
572
|
+
const tree = treeOf(await lister(config.root, { ignores: ignoresOf(config), pathspecs }));
|
|
573
573
|
|
|
574
574
|
const roots = config.featureRoots.map((root) => path.join(config.root, root));
|
|
575
575
|
const { features, contents } = await collect(config, tree, perFile ? given : undefined);
|
package/src/cli/cli.test.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import test from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
4
4
|
import { mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
6
|
import path from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
7
8
|
import { load, requiredHooks } from "../config.mjs";
|
|
8
9
|
import { hookDrift } from "./git-hooks.mjs";
|
|
9
10
|
import { runInit } from "./init.mjs";
|
|
@@ -235,6 +236,29 @@ test("check with several files reports every problem from each, and judges only
|
|
|
235
236
|
rmSync(dir, { recursive: true, force: true });
|
|
236
237
|
});
|
|
237
238
|
|
|
239
|
+
// A Windows command line holds about 8,000 characters through `npx.cmd`, so a hook sends the list on stdin.
|
|
240
|
+
test("check --files-from - reads 300 long paths from stdin and reports a failure in each of two files", async () => {
|
|
241
|
+
const dir = repo();
|
|
242
|
+
await quiet(() => runInit(load(dir)));
|
|
243
|
+
const orders = "backend/src/features/orders";
|
|
244
|
+
const invoices = "backend/src/features/invoices";
|
|
245
|
+
write(dir, {
|
|
246
|
+
"qc.config.json": ENGLISH_ON,
|
|
247
|
+
[`${orders}/index.ts`]: "export {};\n",
|
|
248
|
+
[`${orders}/junk/a.ts`]: "// 注文の補助\nexport {};\n",
|
|
249
|
+
[`${invoices}/index.ts`]: "export {};\n",
|
|
250
|
+
[`${invoices}/junk/b.ts`]: "// 請求の補助\nexport {};\n",
|
|
251
|
+
});
|
|
252
|
+
const filler = Array.from({ length: 300 }, (_, i) => `docs/${"long-segment-".repeat(6)}${i}.md`);
|
|
253
|
+
const input = [...filler, `${orders}/junk/a.ts`, `${invoices}/junk/b.ts`].join("\0") + "\0";
|
|
254
|
+
const qc = fileURLToPath(new URL("./qc.mjs", import.meta.url));
|
|
255
|
+
const run = spawnSync(process.execPath, [qc, "check", "--files-from", "-"], { cwd: dir, input, encoding: "utf8" });
|
|
256
|
+
assert.equal(run.status, 1, run.stderr);
|
|
257
|
+
assert.match(run.stderr, /orders\/junk\/a\.ts/);
|
|
258
|
+
assert.match(run.stderr, /invoices\/junk\/b\.ts/);
|
|
259
|
+
rmSync(dir, { recursive: true, force: true });
|
|
260
|
+
});
|
|
261
|
+
|
|
238
262
|
test("a clean mirror run names every root it judged", async () => {
|
|
239
263
|
const dir = await mirrored(["backend/src/orders/ship.ts", "backend/tests/orders/ship.test.ts"]);
|
|
240
264
|
const { lines } = await runCheck(load(dir));
|
|
@@ -454,3 +478,28 @@ test("check follows an export const alias, and fails a file that aliases the hel
|
|
|
454
478
|
);
|
|
455
479
|
rmSync(dir, { recursive: true, force: true });
|
|
456
480
|
});
|
|
481
|
+
|
|
482
|
+
test("init adds the worktree folder to an existing .gitignore once, and writes it to a new one", async () => {
|
|
483
|
+
const dir = repo();
|
|
484
|
+
writeFileSync(path.join(dir, ".gitignore"), "node_modules/");
|
|
485
|
+
await quiet(() => runInit(load(dir)));
|
|
486
|
+
await quiet(() => runInit(load(dir)));
|
|
487
|
+
assert.equal(readFileSync(path.join(dir, ".gitignore"), "utf8"), "node_modules/\n.worktree/\n");
|
|
488
|
+
const spelled = repo();
|
|
489
|
+
writeFileSync(path.join(spelled, ".gitignore"), "/.worktree\n");
|
|
490
|
+
await quiet(() => runInit(load(spelled)));
|
|
491
|
+
assert.equal(readFileSync(path.join(spelled, ".gitignore"), "utf8"), "/.worktree\n");
|
|
492
|
+
const fresh = repo();
|
|
493
|
+
await quiet(() => runInit(load(fresh)));
|
|
494
|
+
assert.equal(readFileSync(path.join(fresh, ".gitignore"), "utf8"), ".worktree/\n");
|
|
495
|
+
for (const root of [dir, spelled, fresh]) rmSync(root, { recursive: true, force: true });
|
|
496
|
+
});
|
|
497
|
+
|
|
498
|
+
test("check skips the worktree folder, even where git does not ignore it", async () => {
|
|
499
|
+
const dir = repo();
|
|
500
|
+
await quiet(() => runInit(load(dir)));
|
|
501
|
+
write(dir, { "qc.config.json": ENGLISH_ON, ".gitignore": "", ".worktree/wt/docs/draft.md": "下書き\n", "docs/draft.md": "下書き\n" });
|
|
502
|
+
const { problems } = await runCheck(load(dir));
|
|
503
|
+
assert.deepEqual(englishPaths(problems), ["docs/draft.md"]);
|
|
504
|
+
rmSync(dir, { recursive: true, force: true });
|
|
505
|
+
});
|
package/src/cli/init.mjs
CHANGED
|
@@ -68,6 +68,17 @@ async function addScripts(config) {
|
|
|
68
68
|
return [{ to: file, status: "written" }];
|
|
69
69
|
}
|
|
70
70
|
|
|
71
|
+
/** Adds the worktree folder to `.gitignore` unless a line already names it, so no worktree shows in `git status`. QC-015. */
|
|
72
|
+
async function ignoreWorktrees(config) {
|
|
73
|
+
const file = path.join(config.root, ".gitignore");
|
|
74
|
+
const dir = config.worktree.dir.replace(/\/+$/, "");
|
|
75
|
+
const text = existsSync(file) ? await readFile(file, "utf8") : "";
|
|
76
|
+
const spellings = new Set([dir, `${dir}/`, `/${dir}`, `/${dir}/`]);
|
|
77
|
+
if (text.split(/\r?\n/).some((line) => spellings.has(line.trim()))) return { to: file, status: "kept" };
|
|
78
|
+
await writeFile(file, `${text}${text === "" || text.endsWith("\n") ? "" : "\n"}${dir}/\n`);
|
|
79
|
+
return { to: file, status: "written" };
|
|
80
|
+
}
|
|
81
|
+
|
|
71
82
|
export async function runInit(config, args = []) {
|
|
72
83
|
const force = args.includes("--force");
|
|
73
84
|
const results = [];
|
|
@@ -83,6 +94,7 @@ export async function runInit(config, args = []) {
|
|
|
83
94
|
// The docs and the CI workflow both tell a reader to run these, so `init` puts them
|
|
84
95
|
// where a reader will look rather than leaving the instruction dangling.
|
|
85
96
|
results.push(...(await addScripts(config)));
|
|
97
|
+
results.push(await ignoreWorktrees(config));
|
|
86
98
|
|
|
87
99
|
for (const { to, status } of results) {
|
|
88
100
|
console.log(`${status.padEnd(11)} ${path.relative(config.root, to)}`);
|
package/src/cli/merge-guard.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// The trigger that holds `gh pr merge` to its review. Before the call it needs `--match-head-commit` and an
|
|
3
3
|
// APPROVED review of `swarm.review.merge` for that sha. After the call it records the merge and its issues.
|
|
4
4
|
// A merge that names another repository than the checkout's `origin` is that repository's own, so it passes.
|
|
5
|
+
// With `swarm.dispatch` off, the record is still written for the worktree check of QC-015, and nothing is judged.
|
|
5
6
|
|
|
6
7
|
import { spawnSync } from "node:child_process";
|
|
7
8
|
import { fileURLToPath } from "node:url";
|
|
@@ -10,6 +11,7 @@ import { ghApiMerges, ghMerges } from "./gh-merge-command.mjs";
|
|
|
10
11
|
import { runGh } from "./gh-run.mjs";
|
|
11
12
|
import { appendRecord, latestVerdictFor, readLedger } from "./ledger.mjs";
|
|
12
13
|
import { workflowAt } from "./workflow-settings.mjs";
|
|
14
|
+
import { worktreeRuleAt } from "./worktree-settings.mjs";
|
|
13
15
|
|
|
14
16
|
const VIEW_FIELDS = "number,url,state,mergedAt,baseRefName,headRefName,body,closingIssuesReferences";
|
|
15
17
|
const MAYBE_GH = /\bgh(?:\.exe)?\b/i;
|
|
@@ -138,6 +140,8 @@ export function decide(call, { gh = runGh } = {}) {
|
|
|
138
140
|
} catch (error) {
|
|
139
141
|
return event === "PreToolUse" ? context(`Merge guard is off: ${error.message}`) : null;
|
|
140
142
|
}
|
|
143
|
+
// Only the record needs a ledger; the review check stays off with the workflow.
|
|
144
|
+
if (!workflow && event !== "PreToolUse") workflow = worktreeRuleAt(call.cwd ?? process.cwd());
|
|
141
145
|
if (!workflow) return null;
|
|
142
146
|
if (event === "PreToolUse") {
|
|
143
147
|
const [found] = ghApiMerges(command, parse, { cwd: call.cwd ?? process.cwd() });
|
|
@@ -58,13 +58,25 @@ const MERGED = JSON.stringify({
|
|
|
58
58
|
],
|
|
59
59
|
});
|
|
60
60
|
|
|
61
|
-
test("with swarm.dispatch off, a merge is
|
|
61
|
+
test("with swarm.dispatch off, a merge is not judged, and the merge is recorded for the worktree check", (t) => {
|
|
62
62
|
const ws = workspace(t);
|
|
63
63
|
const { gh, calls } = fakeGh(MERGED);
|
|
64
64
|
assert.equal(decide(shell(ws.off, "gh pr merge 60"), { gh }), null);
|
|
65
|
-
assert.equal(decide(shell(ws.off, "gh pr merge 60", "PostToolUse"), { gh }), null);
|
|
66
65
|
assert.equal(decide(shell(ws.off, "gh api -X PUT repos/o/r/pulls/60/merge"), { gh }), null);
|
|
66
|
+
assert.equal(calls.length, 0, "a PreToolUse call reads nothing");
|
|
67
|
+
assert.equal(decide(shell(ws.off, "gh pr merge 60", "PostToolUse"), { gh }), null);
|
|
68
|
+
const records = readLedger(ws.ledgerOf(ws.off));
|
|
69
|
+
assert.deepEqual(records.map(({ type, pr, repo, branch }) => ({ type, pr, repo, branch })), [{ type: "merge", pr: 60, repo: "o/r", branch: "feat/62-x" }]);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test("with swarm.dispatch off and worktree.enforce false, a merge is neither judged nor recorded", (t) => {
|
|
73
|
+
const ws = workspace(t);
|
|
74
|
+
writeFileSync(path.join(ws.off, "qc.config.json"), JSON.stringify({ swarm: {}, worktree: { enforce: false } }));
|
|
75
|
+
const { gh, calls } = fakeGh(MERGED);
|
|
76
|
+
assert.equal(decide(shell(ws.off, "gh pr merge 60"), { gh }), null);
|
|
77
|
+
assert.equal(decide(shell(ws.off, "gh pr merge 60", "PostToolUse"), { gh }), null);
|
|
67
78
|
assert.equal(calls.length, 0);
|
|
79
|
+
assert.equal(existsSync(ws.ledgerOf(ws.off)), false);
|
|
68
80
|
});
|
|
69
81
|
|
|
70
82
|
test("a merge without --match-head-commit is refused", (t) => {
|
|
@@ -326,3 +338,10 @@ test("a gh api call to a repos/ path whose body file quotes the mutation is allo
|
|
|
326
338
|
assert.equal(decide(shell(ws.on, "gh api repos/o/r/issues/64/comments -F body=@review.md")), null);
|
|
327
339
|
assert.match(denied(decide(shell(ws.on, "gh api graphql -F query=@review.md"))) ?? "", /gh pr merge <n> --match-head-commit <sha>/);
|
|
328
340
|
});
|
|
341
|
+
|
|
342
|
+
test("with swarm.dispatch off, a merge whose command failed after GitHub merged is still recorded", (t) => {
|
|
343
|
+
const ws = workspace(t);
|
|
344
|
+
// `gh pr merge --delete-branch` exits non-zero when a worktree holds the branch, after the merge itself.
|
|
345
|
+
assert.equal(decide(shell(ws.off, "gh pr merge 60 --squash --delete-branch", "PostToolUseFailure"), { gh: fakeGh(MERGED).gh }), null);
|
|
346
|
+
assert.deepEqual(readLedger(ws.ledgerOf(ws.off)).map(({ type, pr }) => ({ type, pr })), [{ type: "merge", pr: 60 }]);
|
|
347
|
+
});
|
|
@@ -23,7 +23,7 @@ const LOCATION_NAMES = new Set(["cd", "chdir", "sl", "set-location", "pushd", "p
|
|
|
23
23
|
const PATH_PARAMETERS = new Set(["-path", "-literalpath"]);
|
|
24
24
|
|
|
25
25
|
/** @returns the directory a location change moves to, or null when the segment is none. */
|
|
26
|
-
function locationTarget(segment) {
|
|
26
|
+
export function locationTarget(segment) {
|
|
27
27
|
const [program, ...args] = commandWords(segment);
|
|
28
28
|
if (!LOCATION_NAMES.has(program?.toLowerCase())) return null;
|
|
29
29
|
for (let i = 0; i < args.length; i++) {
|
package/src/cli/qc.mjs
CHANGED
|
@@ -4,10 +4,12 @@
|
|
|
4
4
|
import process from "node:process";
|
|
5
5
|
import { load } from "../config.mjs";
|
|
6
6
|
import { runCheck } from "./check.mjs";
|
|
7
|
+
import { checkFiles } from "./check-input.mjs";
|
|
7
8
|
|
|
8
9
|
const USAGE = `qc — architecture gates
|
|
9
10
|
|
|
10
|
-
qc check [file...]
|
|
11
|
+
qc check [file...] [--files-from <path|->]
|
|
12
|
+
every structural gate; files given, or listed NUL-separated in a file or on stdin, take the fast path
|
|
11
13
|
qc init scaffold the docs, config, hooks and workflow into this repository
|
|
12
14
|
qc feature <name> scaffold a feature in the configured anatomy
|
|
13
15
|
qc run [name] drive one feature command headless; no name lists them
|
|
@@ -25,9 +27,9 @@ const USAGE = `qc — architecture gates
|
|
|
25
27
|
qc tokens [--session <id>] [--project <dir>] [--claude-dir <dir>] [--json]
|
|
26
28
|
one session's tokens and cache hit rate per agent type, from its transcripts
|
|
27
29
|
qc worktree add <name> <branch> [--from <ref>]
|
|
28
|
-
fetch, add
|
|
30
|
+
fetch, add .worktree/<name> in the main checkout, install, print the path
|
|
29
31
|
qc worktree remove <name>
|
|
30
|
-
refuse a dirty tree; delete it, then its branch once merged or
|
|
32
|
+
refuse a dirty tree; delete it, then its branch once merged, pushed, or a merged PR head
|
|
31
33
|
qc enforcement-map refresh the generated rule/gate table in docs/enforcement.md
|
|
32
34
|
qc doctor the hooks and the lockfile must run the same harness
|
|
33
35
|
qc config print the resolved configuration
|
|
@@ -45,7 +47,10 @@ async function main() {
|
|
|
45
47
|
|
|
46
48
|
switch (command) {
|
|
47
49
|
case "check": {
|
|
48
|
-
const {
|
|
50
|
+
const { files, listed } = await checkFiles(rest);
|
|
51
|
+
// An empty list means nothing staged to check, not the full check.
|
|
52
|
+
if (listed && files.length === 0) return;
|
|
53
|
+
const { problems, lines } = await runCheck(config, files);
|
|
49
54
|
if (problems.length > 0) {
|
|
50
55
|
for (const problem of problems) {
|
|
51
56
|
console.error(`FAIL ${problem.feature ?? problem.path} ${problem.rule}: ${problem.detail}`);
|
|
@@ -25,6 +25,7 @@ test("hooks.json runs each workflow check on its events", () => {
|
|
|
25
25
|
assert.deepEqual(matchersOf("SubagentStop", script), [undefined], script);
|
|
26
26
|
}
|
|
27
27
|
assert.deepEqual(matchersOf("Stop", "issue-gate.mjs"), [undefined]);
|
|
28
|
+
assert.deepEqual(matchersOf("Stop", "worktree-gate.mjs"), [undefined]);
|
|
28
29
|
});
|
|
29
30
|
|
|
30
31
|
test("every node script hooks.json names exists", () => {
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The Stop trigger of QC-015: a PR this session merged leaves no worktree, local branch, or remote branch on its
|
|
3
|
+
// head. It reads the merge records of the ledger, and runs git only for a merge of this session.
|
|
4
|
+
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
import os from "node:os";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { globMatcher } from "../glob.mjs";
|
|
12
|
+
import { fileSafe } from "./edit-batch-state.mjs";
|
|
13
|
+
import { readLedger } from "./ledger.mjs";
|
|
14
|
+
import { keyOf, worktrees } from "./worktree.mjs";
|
|
15
|
+
import { worktreeRuleAt } from "./worktree-settings.mjs";
|
|
16
|
+
|
|
17
|
+
const GIT_TIMEOUT_MS = 20_000;
|
|
18
|
+
|
|
19
|
+
function git(cwd, ...args) {
|
|
20
|
+
const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, timeout: GIT_TIMEOUT_MS });
|
|
21
|
+
return { ok: result.status === 0, out: (result.stdout ?? "").trim() };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The settled merges of this session, one per head branch, less each head that is long-lived by config. */
|
|
25
|
+
function mergesOf(records, session, config) {
|
|
26
|
+
const longLived = globMatcher([...(config.swarm?.isolation?.protectedBranches ?? []), ...(config.branches?.allow ?? [])]);
|
|
27
|
+
const byBranch = new Map();
|
|
28
|
+
for (const record of records) {
|
|
29
|
+
if (record.type !== "merge" || record.session !== session || record.pending || record.closed) continue;
|
|
30
|
+
if (typeof record.branch === "string" && record.branch !== "" && !longLived(record.branch)) byBranch.set(record.branch, record);
|
|
31
|
+
}
|
|
32
|
+
return [...byBranch.values()];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The commands that remove what a merged head leaves, or none when nothing is left. */
|
|
36
|
+
function cleanupOf(merge, { main, folder }) {
|
|
37
|
+
const { branch } = merge;
|
|
38
|
+
const tree = worktrees(main).find((entry) => entry.branch === branch);
|
|
39
|
+
const local = git(main, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).ok;
|
|
40
|
+
const remote = git(main, "ls-remote", "--heads", "origin", `refs/heads/${branch}`);
|
|
41
|
+
const steps = [];
|
|
42
|
+
if (tree && keyOf(tree.path) === keyOf(main)) steps.push(`\`git switch ${merge.base ?? "main"}\``, `\`git branch -D ${branch}\``);
|
|
43
|
+
else if (tree && [folder, path.dirname(main)].some((parent) => keyOf(path.dirname(tree.path)) === keyOf(parent))) {
|
|
44
|
+
// `remove` deletes the local branch, and the remote one at the head of a merged PR.
|
|
45
|
+
return [`\`npx qc worktree remove ${path.basename(tree.path)}\``];
|
|
46
|
+
} else if (tree) steps.push(`\`git worktree remove ${tree.path}\``, `\`git branch -D ${branch}\``);
|
|
47
|
+
else if (local) steps.push(`\`git branch -D ${branch}\``);
|
|
48
|
+
if (remote.ok && remote.out !== "") steps.push(`\`git push origin --delete ${branch}\``);
|
|
49
|
+
return steps;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const memoryOf = (tmp, session) => path.join(tmp, "qc-worktree-gate", `${fileSafe(session)}.last`);
|
|
53
|
+
const hashOf = (text) => createHash("sha256").update(text).digest("hex");
|
|
54
|
+
|
|
55
|
+
function lastBlock(file) {
|
|
56
|
+
try {
|
|
57
|
+
return readFileSync(file, "utf8");
|
|
58
|
+
} catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The verdict on one Stop. @returns the hook output, or null to let the turn end with no message. */
|
|
64
|
+
export function decide(call, { tmp = os.tmpdir(), projectDir = process.env.CLAUDE_PROJECT_DIR } = {}) {
|
|
65
|
+
if (call.hook_event_name !== "Stop") return null;
|
|
66
|
+
const rule = worktreeRuleAt(call.cwd ?? process.cwd()) ?? (projectDir ? worktreeRuleAt(projectDir) : null);
|
|
67
|
+
if (!rule) return null;
|
|
68
|
+
const session = call.session_id ?? "session";
|
|
69
|
+
let records;
|
|
70
|
+
try {
|
|
71
|
+
records = readLedger(rule.ledger);
|
|
72
|
+
} catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
const lines = mergesOf(records, session, rule.config)
|
|
76
|
+
.map((merge) => ({ merge, steps: cleanupOf(merge, rule) }))
|
|
77
|
+
.filter(({ steps }) => steps.length > 0)
|
|
78
|
+
.map(({ merge, steps }) => `- ${merge.repo}#${merge.pr} (${merge.branch}): ${steps.join(", then ")}`);
|
|
79
|
+
const memory = memoryOf(tmp, session);
|
|
80
|
+
if (lines.length === 0) {
|
|
81
|
+
rmSync(memory, { force: true });
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
const reason = [
|
|
85
|
+
`Worktree check: a PR this session merged leaves its worktree or its branch. From the main checkout (${rule.main}), run:`,
|
|
86
|
+
...lines,
|
|
87
|
+
].join("\n");
|
|
88
|
+
// A repeat stop with the same leftovers ends with a note, so a removal the agent cannot run never loops.
|
|
89
|
+
const note = { systemMessage: `Worktree check: the same leftovers as at the last block remain. Remove them by hand: ${lines[0].slice(2)}` };
|
|
90
|
+
if (call.stop_hook_active === true && lastBlock(memory) === hashOf(reason)) return note;
|
|
91
|
+
try {
|
|
92
|
+
mkdirSync(path.dirname(memory), { recursive: true });
|
|
93
|
+
writeFileSync(memory, hashOf(reason));
|
|
94
|
+
} catch {
|
|
95
|
+
// With no memory, a repeat stop cannot tell a change, so it ends with the note.
|
|
96
|
+
if (call.stop_hook_active === true) return note;
|
|
97
|
+
}
|
|
98
|
+
return { decision: "block", reason };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function readStdin() {
|
|
102
|
+
let data = "";
|
|
103
|
+
for await (const chunk of process.stdin) data += chunk;
|
|
104
|
+
return data;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
|
|
108
|
+
if (isEntryPoint) {
|
|
109
|
+
let call = null;
|
|
110
|
+
try {
|
|
111
|
+
call = JSON.parse(await readStdin());
|
|
112
|
+
} catch {
|
|
113
|
+
// Not hook input, so there is no merge to follow up.
|
|
114
|
+
}
|
|
115
|
+
const output = call ? decide(call) : null;
|
|
116
|
+
if (output) process.stdout.write(JSON.stringify(output));
|
|
117
|
+
}
|