architecture-harness 0.5.0 → 0.7.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
package/src/cli/check.mjs CHANGED
@@ -23,7 +23,7 @@ import { checkGatesAreTested } from "../gates/gate-tests.mjs";
23
23
  import { checkAuditAppendOnly } from "../gates/audit-append-only.mjs";
24
24
  import { checkEnforcementMap } from "../gates/enforcement-map.mjs";
25
25
  import { checkFrontendBoundaries } from "../gates/frontend-boundaries.mjs";
26
- import { checkTestMirror } from "../gates/test-mirror.mjs";
26
+ import { checkTestMirror, mirrorFolders } from "../gates/test-mirror.mjs";
27
27
  import { checkCommentStyle } from "../gates/comment-style.mjs";
28
28
  import { checkEnglishSource, checkTranslationPairs } from "../gates/english-source.mjs";
29
29
  import { checkAdrFormat } from "../gates/adr-format.mjs";
@@ -502,13 +502,19 @@ export async function runCheck(config, only) {
502
502
  }
503
503
  }
504
504
  if (enabled(config.gates, "test-mirror")) {
505
- const all = await sourceFiles(config);
506
- const testPaths = all.filter((file) => TEST_FILE.test(file.path)).map((file) => file.path);
507
- const srcPaths = all.filter((file) => !TEST_FILE.test(file.path)).map((file) => file.path);
508
- const mirrorProblems = checkTestMirror(testPaths, srcPaths);
505
+ const { roots } = config.testMirror;
506
+ const walked = new Set();
507
+ for (const dir of mirrorFolders(roots)) {
508
+ for (const file of await sourceFiles(config, dir)) walked.add(file.path);
509
+ }
510
+ const all = [...walked];
511
+ const testPaths = all.filter((file) => TEST_FILE.test(file));
512
+ const srcPaths = all.filter((file) => !TEST_FILE.test(file));
513
+ const mirrorProblems = checkTestMirror(testPaths, srcPaths, roots);
509
514
  problems.push(...mirrorProblems);
510
515
  if (mirrorProblems.length === 0) {
511
- lines.push("OK mirror frontend tests mirror src paths 1:1, no orphaned test");
516
+ const judged = roots.map((root) => root.tests).join(", ") || "no configured root";
517
+ lines.push(`OK mirror tests mirror src paths 1:1, no orphaned test, in ${judged}`);
512
518
  }
513
519
  }
514
520
 
@@ -118,3 +118,47 @@ test("one present feature root is enough", async () => {
118
118
  );
119
119
  rmSync(dir, { recursive: true, force: true });
120
120
  });
121
+
122
+ const MIRROR_RULES = new Set(["unmirrored-test", "orphaned-test", "invalid-mirror-root"]);
123
+
124
+ /** An initialised repository with two mirror roots, and the given files under it. */
125
+ async function mirrored(files) {
126
+ const dir = repo();
127
+ await quiet(() => runInit(load(dir)));
128
+ const roots = [{ src: "frontend/src", tests: "frontend/tests" }, { src: "backend/src", tests: "backend/tests" }];
129
+ writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ testMirror: { roots } }));
130
+ for (const file of files) {
131
+ mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });
132
+ writeFileSync(path.join(dir, file), "export {};\n");
133
+ }
134
+ return dir;
135
+ }
136
+
137
+ // backend/tests is in no citable root, so only a walk of the configured roots can see its orphan.
138
+ test("check judges every configured mirror root, including a tests folder outside the citable roots", async () => {
139
+ const dir = await mirrored([
140
+ "backend/src/orders/place.ts",
141
+ "backend/src/orders/place.test.ts",
142
+ "backend/src/orders/ship.ts",
143
+ "backend/tests/orders/ship.test.ts",
144
+ "backend/tests/orders/cancel.test.ts",
145
+ ]);
146
+ const { problems } = await runCheck(load(dir));
147
+ const found = problems.filter((problem) => MIRROR_RULES.has(problem.rule)).map(({ path: file, rule }) => ({ file, rule }));
148
+ assert.deepEqual(
149
+ found.sort((a, b) => a.file.localeCompare(b.file)),
150
+ [
151
+ { file: "backend/src/orders/place.test.ts", rule: "unmirrored-test" },
152
+ { file: "backend/tests/orders/cancel.test.ts", rule: "orphaned-test" },
153
+ ],
154
+ );
155
+ rmSync(dir, { recursive: true, force: true });
156
+ });
157
+
158
+ test("a clean mirror run names every root it judged", async () => {
159
+ const dir = await mirrored(["backend/src/orders/ship.ts", "backend/tests/orders/ship.test.ts"]);
160
+ const { lines } = await runCheck(load(dir));
161
+ const line = lines.find((entry) => entry.startsWith("OK mirror"));
162
+ assert.ok(line?.includes("frontend/tests") && line.includes("backend/tests"), `mirror line: ${line}`);
163
+ rmSync(dir, { recursive: true, force: true });
164
+ });
@@ -0,0 +1,33 @@
1
+ // The resource for the worktree lease: the one file that says which agent session holds a worktree.
2
+ // It lives in the worktree's own git dir, so it is never committed and goes away with the worktree.
3
+
4
+ import { readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import path from "node:path";
6
+
7
+ export const LEASE_FILE = "qc-agent-lease.json";
8
+
9
+ export const leaseFileOf = (gitDir) => path.join(gitDir, LEASE_FILE);
10
+
11
+ /** @returns the parsed lease, or null when there is no file or it does not parse. */
12
+ export function readLease(gitDir) {
13
+ try {
14
+ return JSON.parse(readFileSync(leaseFileOf(gitDir), "utf8"));
15
+ } catch {
16
+ return null;
17
+ }
18
+ }
19
+
20
+ /** @param {string | null} sessionId already validated; null claims nothing. */
21
+ export function claimLease(gitDir, sessionId, branch, now = Date.now()) {
22
+ if (!sessionId) return;
23
+ try {
24
+ const payload = { sessionId, branch, updatedAt: new Date(now).toISOString() };
25
+ writeFileSync(leaseFileOf(gitDir), `${JSON.stringify(payload, null, 2)}\n`);
26
+ } catch {
27
+ // A read-only or absent git dir is not a reason to block an edit.
28
+ }
29
+ }
30
+
31
+ export function removeLease(gitDir) {
32
+ rmSync(leaseFileOf(gitDir), { force: true });
33
+ }
@@ -0,0 +1,136 @@
1
+ // `qc lease`, the trigger that shows and releases the worktree lease the edit guard claims.
2
+ // A lease another session holds is released only on purpose: by its holder, or by a person with --force.
3
+
4
+ import { execFile } from "node:child_process";
5
+ import { existsSync, statSync } from "node:fs";
6
+ import path from "node:path";
7
+ import { parseArgs, promisify } from "node:util";
8
+ import { load } from "../config.mjs";
9
+ import { leaseFileOf, readLease, removeLease } from "./lease-file.mjs";
10
+ import { OFF, duration, isolationSettings, leaseState, sessionIdOf, timestamp } from "./worktree-isolation.mjs";
11
+
12
+ const execFileAsync = promisify(execFile);
13
+
14
+ export const USAGE = `qc lease — the lease that holds a worktree for one agent session
15
+
16
+ qc lease status [path] its holder, branch, age, and the time it lapses
17
+ qc lease release [path] --session <id> remove the lease that this session holds
18
+ qc lease release [path] --force remove any lease, and print what it removed
19
+
20
+ path is any folder inside the worktree, and defaults to the current directory.`;
21
+
22
+ /** The worktree root and git dir that hold a path, or null when no checkout does. */
23
+ async function worktreeAt(target) {
24
+ const absolute = path.resolve(target);
25
+ const dir = existsSync(absolute) && !statSync(absolute).isDirectory() ? path.dirname(absolute) : absolute;
26
+ try {
27
+ const { stdout } = await execFileAsync("git", ["rev-parse", "--show-toplevel", "--absolute-git-dir"], { cwd: dir });
28
+ const [root, gitDir] = stdout.trim().split(/\r?\n/);
29
+ return { root, gitDir };
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ const NO_TIME = "(no readable time)";
36
+
37
+ const written = (state) =>
38
+ Number.isNaN(state.written) ? NO_TIME : `${timestamp(state.written)}, ${duration(Math.max(state.age, 0))} ago`;
39
+
40
+ function lapses(state, now) {
41
+ if (Number.isNaN(state.lapsesAt)) return NO_TIME;
42
+ const when = now > state.lapsesAt ? `${duration(now - state.lapsesAt)} ago` : `in ${duration(state.lapsesAt - now)}`;
43
+ return `${timestamp(state.lapsesAt)}, ${when}`;
44
+ }
45
+
46
+ function verdict(state, settings) {
47
+ if (settings.require === OFF) return "inactive: swarm.isolation.require is off, so no edit reads it";
48
+ if (state.holder === null || Number.isNaN(state.written)) return "unreadable: it binds no session";
49
+ if (state.live) return "held: an edit from any other session is refused";
50
+ return state.age < 0 ? "written in the future: it binds no session" : "lapsed: it binds no session";
51
+ }
52
+
53
+ /** The status report as lines. `lease` is undefined when there is no file, and null when it does not parse. */
54
+ export function statusLines(file, lease, settings, now) {
55
+ if (lease === undefined) return [`no lease: ${file} does not exist`];
56
+ const state = leaseState(lease, now, settings.leaseHours);
57
+ return [
58
+ `lease ${file}`,
59
+ `holder ${state.holder ?? "(none)"}`,
60
+ `branch ${state.branch ?? "(none)"}`,
61
+ `written ${written(state)}`,
62
+ `lapses ${lapses(state, now)}`,
63
+ `state ${verdict(state, settings)}`,
64
+ ];
65
+ }
66
+
67
+ /** @returns null when the release may go ahead, or the reason it may not. */
68
+ export function releaseRefusal(lease, { session, force }) {
69
+ if (force) return null;
70
+ const caller = sessionIdOf(session);
71
+ const holder = sessionIdOf(lease?.sessionId);
72
+ if (!caller) {
73
+ return `refused: pass --session <id> to release your own lease, or --force to release any lease. Holder: ${holder ?? "(none)"}.`;
74
+ }
75
+ if (holder === null) return "refused: the lease names no readable holder, so only --force removes it.";
76
+ if (caller === holder) return null;
77
+ return `refused: session ${holder} holds this lease, not ${caller}. Only its holder releases it without --force.`;
78
+ }
79
+
80
+ function removed(file, lease, now) {
81
+ // A release reads no config, so a broken one cannot block it; the lapse is not needed here.
82
+ const state = leaseState(lease, now, Number.POSITIVE_INFINITY);
83
+ return `released ${file}: session ${state.holder ?? "(none)"} on "${state.branch ?? "(none)"}", written ${written(state)}`;
84
+ }
85
+
86
+ export async function runLease(args, now = Date.now()) {
87
+ let parsed;
88
+ try {
89
+ parsed = parseArgs({
90
+ args,
91
+ allowPositionals: true,
92
+ options: { session: { type: "string" }, force: { type: "boolean", default: false } },
93
+ });
94
+ } catch (error) {
95
+ console.error(`${error.message}\n\n${USAGE}`);
96
+ return 1;
97
+ }
98
+ const [action, target = process.cwd(), ...extra] = parsed.positionals;
99
+ if (!["status", "release"].includes(action) || extra.length > 0) {
100
+ console.log(USAGE);
101
+ return action === undefined || action === "help" ? 0 : 1;
102
+ }
103
+
104
+ const worktree = await worktreeAt(target);
105
+ if (!worktree) {
106
+ console.error(`${target} is not inside a git checkout, so it has no lease.`);
107
+ return 1;
108
+ }
109
+ const file = leaseFileOf(worktree.gitDir);
110
+ const lease = existsSync(file) ? readLease(worktree.gitDir) : undefined;
111
+
112
+ if (action === "status") {
113
+ let settings;
114
+ try {
115
+ settings = isolationSettings(load(worktree.root).swarm);
116
+ } catch (error) {
117
+ console.error(error.message);
118
+ return 1;
119
+ }
120
+ for (const line of statusLines(file, lease, settings, now)) console.log(line);
121
+ return 0;
122
+ }
123
+
124
+ if (lease === undefined) {
125
+ console.log(`no lease: ${file} does not exist`);
126
+ return 0;
127
+ }
128
+ const refusal = releaseRefusal(lease, parsed.values);
129
+ if (refusal) {
130
+ console.error(refusal);
131
+ return 1;
132
+ }
133
+ removeLease(worktree.gitDir);
134
+ console.log(removed(file, lease, now));
135
+ return 0;
136
+ }
@@ -0,0 +1,140 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const QC = fileURLToPath(new URL("./qc.mjs", import.meta.url));
10
+ const MINUTE = 60_000;
11
+ const HOUR = 60 * MINUTE;
12
+ const HOLDER = "session-bbbb-0000-1111";
13
+
14
+ /** A primary checkout with the given isolation config, one linked worktree, and a folder in no checkout to run from. */
15
+ function leasedWorktree(isolation = { require: "worktree" }) {
16
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-lease-")));
17
+ const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" });
18
+ const primary = path.join(base, "primary");
19
+ const linked = path.join(base, "linked");
20
+ const outside = path.join(base, "outside");
21
+ mkdirSync(primary);
22
+ mkdirSync(outside);
23
+ git(primary, "init", "-q", "-b", "main");
24
+ writeFileSync(path.join(primary, "qc.config.json"), JSON.stringify({ swarm: { isolation } }));
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
+ const leaseFile = path.join(realpathSync.native(git(linked, "rev-parse", "--absolute-git-dir").trim()), "qc-agent-lease.json");
29
+ const writeLease = (ageMs, sessionId = HOLDER) => {
30
+ const updatedAt = new Date(Date.now() - ageMs).toISOString();
31
+ writeFileSync(leaseFile, JSON.stringify({ sessionId, branch: "feat/work-order", updatedAt }));
32
+ return Date.parse(updatedAt);
33
+ };
34
+ // Run from a folder in no checkout, so the command can only find the worktree through its path argument.
35
+ const qc = (...args) =>
36
+ spawnSync(process.execPath, [QC, "lease", ...args], { cwd: outside, input: "", encoding: "utf8" });
37
+ return { linked, outside, leaseFile, writeLease, qc, cleanup: () => rmSync(base, { recursive: true, force: true }) };
38
+ }
39
+
40
+ const iso = (ms) => new Date(ms).toISOString();
41
+
42
+ test("status reports a fresh lease: its holder, branch, age, lapse time, and that it binds", (t) => {
43
+ const ws = leasedWorktree();
44
+ t.after(ws.cleanup);
45
+ const written = ws.writeLease(30 * MINUTE + 10_000);
46
+ const result = ws.qc("status", ws.linked);
47
+ assert.equal(result.status, 0, result.stderr);
48
+ assert.match(result.stdout, new RegExp(`holder\\s+${HOLDER}`));
49
+ assert.match(result.stdout, /branch\s+feat\/work-order/);
50
+ assert.ok(result.stdout.includes(`${iso(written)}, 30m ago`), result.stdout);
51
+ assert.ok(result.stdout.includes(`${iso(written + 8 * HOUR)}, in 7h 29m`), result.stdout);
52
+ assert.match(result.stdout, /state\s+held/);
53
+ });
54
+
55
+ test("status reads leaseHours from the worktree's own config, and reports a lapsed lease as lapsed", (t) => {
56
+ const ws = leasedWorktree({ require: "worktree", leaseHours: 1 });
57
+ t.after(ws.cleanup);
58
+ const written = ws.writeLease(2 * HOUR + 10_000);
59
+ const result = ws.qc("status", ws.linked);
60
+ assert.equal(result.status, 0, result.stderr);
61
+ assert.ok(result.stdout.includes(`${iso(written + HOUR)}, 1h 0m ago`), result.stdout);
62
+ assert.match(result.stdout, /state\s+lapsed/);
63
+ });
64
+
65
+ test("status and release on a worktree with no lease both say so", (t) => {
66
+ const ws = leasedWorktree();
67
+ t.after(ws.cleanup);
68
+ for (const args of [["status", ws.linked], ["release", ws.linked, "--force"]]) {
69
+ const result = ws.qc(...args);
70
+ assert.equal(result.status, 0, result.stderr);
71
+ assert.match(result.stdout, /no lease/);
72
+ }
73
+ });
74
+
75
+ test("release without --force refuses a lease that another session holds", (t) => {
76
+ const ws = leasedWorktree();
77
+ t.after(ws.cleanup);
78
+ ws.writeLease(5 * MINUTE);
79
+ const result = ws.qc("release", ws.linked, "--session", "session-aaaa");
80
+ assert.equal(result.status, 1);
81
+ assert.ok(result.stderr.includes(HOLDER), result.stderr);
82
+ assert.equal(existsSync(ws.leaseFile), true, "a refused release removed the lease");
83
+ });
84
+
85
+ test("release with neither --session nor --force refuses, and names both", (t) => {
86
+ const ws = leasedWorktree();
87
+ t.after(ws.cleanup);
88
+ ws.writeLease(5 * MINUTE);
89
+ const result = ws.qc("release", ws.linked);
90
+ assert.equal(result.status, 1);
91
+ assert.match(result.stderr, /--session/);
92
+ assert.match(result.stderr, /--force/);
93
+ assert.equal(existsSync(ws.leaseFile), true);
94
+ });
95
+
96
+ test("release by the holder's own session removes the lease", (t) => {
97
+ const ws = leasedWorktree();
98
+ t.after(ws.cleanup);
99
+ ws.writeLease(5 * MINUTE);
100
+ const result = ws.qc("release", ws.linked, "--session", HOLDER);
101
+ assert.equal(result.status, 0, result.stderr);
102
+ assert.equal(existsSync(ws.leaseFile), false);
103
+ });
104
+
105
+ test("release --force removes another session's lease, and prints what it removed", (t) => {
106
+ const ws = leasedWorktree();
107
+ t.after(ws.cleanup);
108
+ const written = ws.writeLease(5 * MINUTE);
109
+ const result = ws.qc("release", ws.linked, "--force");
110
+ assert.equal(result.status, 0, result.stderr);
111
+ assert.equal(existsSync(ws.leaseFile), false);
112
+ assert.ok(result.stdout.includes(HOLDER), result.stdout);
113
+ assert.ok(result.stdout.includes("feat/work-order"), result.stdout);
114
+ assert.ok(result.stdout.includes(iso(written)), result.stdout);
115
+ });
116
+
117
+ test("release reads no config, so a qc.config.json that does not parse cannot block it", (t) => {
118
+ const ws = leasedWorktree();
119
+ t.after(ws.cleanup);
120
+ ws.writeLease(5 * MINUTE);
121
+ for (const folder of [ws.outside, ws.linked]) writeFileSync(path.join(folder, "qc.config.json"), "{ not json");
122
+ const result = ws.qc("release", ws.linked, "--force");
123
+ assert.equal(result.status, 0, result.stderr);
124
+ assert.equal(existsSync(ws.leaseFile), false);
125
+ });
126
+
127
+ test("the qc usage lists both lease commands", () => {
128
+ const result = spawnSync(process.execPath, [QC, "help"], { encoding: "utf8" });
129
+ assert.equal(result.status, 0, result.stderr);
130
+ assert.match(result.stdout, /qc lease status \[path\]/);
131
+ assert.match(result.stdout, /qc lease release \[path\]/);
132
+ });
133
+
134
+ test("a path in no git checkout is a named error, not a silent pass", (t) => {
135
+ const ws = leasedWorktree();
136
+ t.after(ws.cleanup);
137
+ const result = ws.qc("status", ws.outside);
138
+ assert.equal(result.status, 1);
139
+ assert.match(result.stderr, /not inside a git checkout/);
140
+ });
@@ -0,0 +1,75 @@
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 HOOK = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..", "hooks", "post-edit-gate.sh");
10
+
11
+ /** A session's project checkout, one linked worktree, a checkout with no config, a folder in none, and a qc CLI that records where it ran. */
12
+ function workspace() {
13
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-post-edit-")));
14
+ const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe" });
15
+ const project = path.join(base, "project");
16
+ const linked = path.join(base, "linked");
17
+ const plain = path.join(base, "plain");
18
+ const outside = path.join(base, "outside", "features", "x");
19
+ for (const dir of [project, plain, outside]) mkdirSync(dir, { recursive: true });
20
+ git(project, "init", "-q", "-b", "main");
21
+ writeFileSync(path.join(project, "qc.config.json"), "{}");
22
+ git(project, "add", ".");
23
+ git(project, "-c", "user.name=qc", "-c", "user.email=qc@example.com", "commit", "-q", "-m", "init");
24
+ git(project, "worktree", "add", "-q", linked, "-b", "feat/work-order");
25
+ git(plain, "init", "-q", "-b", "main");
26
+
27
+ const log = path.join(base, "qc-ran.log");
28
+ const cli = path.join(base, "plugin", "packages", "qc-harness", "src", "cli");
29
+ mkdirSync(cli, { recursive: true });
30
+ writeFileSync(
31
+ path.join(cli, "qc.mjs"),
32
+ `import { appendFileSync } from "node:fs";\nappendFileSync(${JSON.stringify(log)}, process.cwd() + String.fromCharCode(10));\nprocess.exit(1);\n`,
33
+ );
34
+ const ranIn = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").map((dir) => realpathSync.native(dir)) : []);
35
+ return { project, linked, plain, outside, pluginRoot: path.join(base, "plugin"), ranIn, cleanup: () => rmSync(base, { recursive: true, force: true }) };
36
+ }
37
+
38
+ function runHook(ws, file) {
39
+ const featureFile = path.join(file, "features", "tasks", "index.ts");
40
+ mkdirSync(path.dirname(featureFile), { recursive: true });
41
+ writeFileSync(featureFile, "export {};\n");
42
+ return spawnSync("bash", [HOOK], {
43
+ input: JSON.stringify({ tool_input: { file_path: featureFile } }),
44
+ env: { ...process.env, CLAUDE_PROJECT_DIR: ws.project, CLAUDE_PLUGIN_ROOT: ws.pluginRoot },
45
+ encoding: "utf8",
46
+ }).status;
47
+ }
48
+
49
+ test("a feature file in no git checkout runs no gate, even when the session's project has adopted the kit", (t) => {
50
+ const ws = workspace();
51
+ t.after(ws.cleanup);
52
+ assert.equal(runHook(ws, ws.outside), 0);
53
+ assert.deepEqual(ws.ranIn(), []);
54
+ });
55
+
56
+ test("a feature file in a linked worktree is checked from that worktree, not the session's project", (t) => {
57
+ const ws = workspace();
58
+ t.after(ws.cleanup);
59
+ assert.equal(runHook(ws, path.join(ws.linked, "backend", "src")), 2);
60
+ assert.deepEqual(ws.ranIn(), [ws.linked]);
61
+ });
62
+
63
+ test("a feature file in a checkout with no qc.config.json runs no gate", (t) => {
64
+ const ws = workspace();
65
+ t.after(ws.cleanup);
66
+ assert.equal(runHook(ws, path.join(ws.plain, "backend", "src")), 0);
67
+ assert.deepEqual(ws.ranIn(), []);
68
+ });
69
+
70
+ test("a feature file in the session's own project is checked from the project", (t) => {
71
+ const ws = workspace();
72
+ t.after(ws.cleanup);
73
+ assert.equal(runHook(ws, path.join(ws.project, "backend", "src")), 2);
74
+ assert.deepEqual(ws.ranIn(), [ws.project]);
75
+ });
package/src/cli/qc.mjs CHANGED
@@ -7,22 +7,29 @@ import { runCheck } from "./check.mjs";
7
7
 
8
8
  const USAGE = `qc — architecture gates
9
9
 
10
- qc check [file] every structural gate; one file is the fast path a hook takes
11
- qc init scaffold the docs, config, hooks and workflow into this repository
12
- qc feature <name> scaffold a feature in the configured anatomy
13
- qc run [name] drive one feature command headless; no name lists them
14
- qc install-hooks point git at the kit's pre-commit hook
15
- qc work-order-check refuse to commit on the wrong branch, per .claude/work-order.local.json
16
- qc commit-msg <file> refuse a commit message that credits a tool as an author
17
- qc decisions [id] where decisions are cited; --squash closes the gaps
18
- qc enforcement-map refresh the generated rule/gate table in docs/enforcement.md
19
- qc doctor the hooks and the lockfile must run the same harness
20
- qc config print the resolved configuration
10
+ qc check [file] every structural gate; one file is the fast path a hook takes
11
+ qc init scaffold the docs, config, hooks and workflow into this repository
12
+ qc feature <name> scaffold a feature in the configured anatomy
13
+ qc run [name] drive one feature command headless; no name lists them
14
+ qc install-hooks point git at the kit's pre-commit hook
15
+ qc work-order-check refuse to commit on the wrong branch, per .claude/work-order.local.json
16
+ qc lease status [path] who holds this worktree's lease, since when, and when it lapses
17
+ qc lease release [path] remove it: --session <id> for your own, --force for another's
18
+ qc commit-msg <file> refuse a commit message that credits a tool as an author
19
+ qc decisions [id] where decisions are cited; --squash closes the gaps
20
+ qc enforcement-map refresh the generated rule/gate table in docs/enforcement.md
21
+ qc doctor the hooks and the lockfile must run the same harness
22
+ qc config print the resolved configuration
21
23
 
22
24
  Every gate reads qc.config.json. A key it does not set keeps the reference default.`;
23
25
 
24
26
  async function main() {
25
27
  const [command, ...rest] = process.argv.slice(2);
28
+ // A broken qc.config.json must not keep a lease in place, so the lease runs before the load.
29
+ if (command === "lease") {
30
+ const { runLease } = await import("./lease.mjs");
31
+ process.exit(await runLease(rest));
32
+ }
26
33
  const config = load(process.cwd());
27
34
 
28
35
  switch (command) {
Binary file
@@ -1,9 +1,11 @@
1
1
  import { strict as assert } from "node:assert";
2
- import { readFileSync } from "node:fs";
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";
3
5
  import path from "node:path";
4
6
  import { test } from "node:test";
5
7
  import { fileURLToPath } from "node:url";
6
- import { branchMismatch, denyOutput, globToRegExp, inSpecialGitOperation, isAllowed } from "./work-order-guard.mjs";
8
+ import { branchMismatch, decide, denyOutput, globToRegExp, inSpecialGitOperation, isAllowed } from "./work-order-guard.mjs";
7
9
 
8
10
  test("a path under a declared glob is allowed", () => {
9
11
  assert.equal(isAllowed("frontend/src/platform/ui/button.tsx", ["frontend/src/platform/**"]), true);
@@ -77,3 +79,126 @@ test("the installed pre-commit hook checks the work order before its staged-file
77
79
  assert.notEqual(filterLine, -1, "pre-commit should still filter staged files by extension");
78
80
  assert.ok(checkLine < filterLine, "the branch check must run before the extension filter, or a .tf/.yml/.md commit skips it");
79
81
  });
82
+
83
+ /** A primary checkout on main that requires worktree isolation, one linked worktree, and a folder in no checkout. */
84
+ function isolatedRepository() {
85
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-guard-")));
86
+ const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe" });
87
+ const primary = path.join(base, "primary");
88
+ const linked = path.join(base, "linked");
89
+ const outside = path.join(base, "outside");
90
+ mkdirSync(primary);
91
+ mkdirSync(outside);
92
+ git(primary, "init", "-q", "-b", "main");
93
+ writeFileSync(path.join(primary, "qc.config.json"), JSON.stringify({ swarm: { isolation: { require: "worktree" } } }));
94
+ git(primary, "add", ".");
95
+ git(primary, "-c", "user.name=qc", "-c", "user.email=qc@example.com", "commit", "-q", "-m", "init");
96
+ git(primary, "worktree", "add", "-q", linked, "-b", "feat/work-order");
97
+ return { primary, linked, outside, cleanup: () => rmSync(base, { recursive: true, force: true }) };
98
+ }
99
+
100
+ const editOf = (file) => ({ tool_input: { file_path: file }, session_id: "session-aaaa" });
101
+
102
+ test("an edit to a file in no git checkout is allowed, whatever branch the project is on", async (t) => {
103
+ const repo = isolatedRepository();
104
+ t.after(repo.cleanup);
105
+ assert.equal(await decide(editOf(path.join(repo.outside, "memory", "note.md")), repo.primary), null);
106
+ });
107
+
108
+ test("an edit in a linked worktree on a work-order branch is judged by that worktree, not the project", async (t) => {
109
+ const repo = isolatedRepository();
110
+ t.after(repo.cleanup);
111
+ assert.equal(await decide(editOf(path.join(repo.linked, "src", "new-folder", "file.ts")), repo.primary), null);
112
+ });
113
+
114
+ test("an edit in the primary checkout on a protected branch is still refused", async (t) => {
115
+ const repo = isolatedRepository();
116
+ t.after(repo.cleanup);
117
+ const output = await decide(editOf(path.join(repo.primary, "src", "file.ts")), repo.primary);
118
+ assert.match(output.hookSpecificOutput.permissionDecisionReason, /"main" is a protected branch/);
119
+ });
120
+
121
+ test("the primary checkout is refused even when the session opened the linked worktree", async (t) => {
122
+ const repo = isolatedRepository();
123
+ t.after(repo.cleanup);
124
+ const output = await decide(editOf(path.join(repo.primary, "src", "file.ts")), repo.linked);
125
+ assert.match(output.hookSpecificOutput.permissionDecisionReason, /"main" is a protected branch/);
126
+ });
127
+
128
+ const GUARD = fileURLToPath(new URL("./work-order-guard.mjs", import.meta.url));
129
+ const QC = fileURLToPath(new URL("./qc.mjs", import.meta.url));
130
+ const slashed = (file) => file.split(path.sep).join("/");
131
+ const hookEditOf = (file, sessionId) => ({
132
+ hook_event_name: "PreToolUse",
133
+ tool_name: "Edit",
134
+ tool_input: { file_path: file },
135
+ session_id: sessionId,
136
+ });
137
+
138
+ function leaseFileOf(worktree) {
139
+ const gitDir = execFileSync("git", ["rev-parse", "--absolute-git-dir"], { cwd: worktree, encoding: "utf8" }).trim();
140
+ return path.join(realpathSync.native(gitDir), "qc-agent-lease.json");
141
+ }
142
+
143
+ /** Runs the guard as its own process, the way a hand test does, with the project pinned to the temp repository. */
144
+ function runGuard(worktree, input) {
145
+ return spawnSync(process.execPath, [GUARD], {
146
+ cwd: worktree,
147
+ input,
148
+ env: { ...process.env, CLAUDE_PROJECT_DIR: worktree },
149
+ encoding: "utf8",
150
+ });
151
+ }
152
+
153
+ test("a direct run of the guard with no hook input writes no lease", (t) => {
154
+ const repo = isolatedRepository();
155
+ t.after(repo.cleanup);
156
+ const result = runGuard(repo.linked, "");
157
+ assert.equal(result.status, 0, result.stderr);
158
+ assert.equal(existsSync(leaseFileOf(repo.linked)), false);
159
+ });
160
+
161
+ test("a hand-built input with a made-up session and no hook event writes no lease", (t) => {
162
+ const repo = isolatedRepository();
163
+ t.after(repo.cleanup);
164
+ const input = JSON.stringify({ tool_input: { file_path: path.join(repo.linked, "src", "a.ts") }, session_id: "test-session" });
165
+ const result = runGuard(repo.linked, input);
166
+ assert.equal(result.status, 0, result.stderr);
167
+ assert.equal(existsSync(leaseFileOf(repo.linked)), false);
168
+ });
169
+
170
+ test("PreToolUse hook input claims the lease for its session and branch", (t) => {
171
+ const repo = isolatedRepository();
172
+ t.after(repo.cleanup);
173
+ const result = runGuard(repo.linked, JSON.stringify(hookEditOf(path.join(repo.linked, "src", "a.ts"), "session-aaaa")));
174
+ assert.equal(result.status, 0, result.stderr);
175
+ const lease = JSON.parse(readFileSync(leaseFileOf(repo.linked), "utf8"));
176
+ assert.equal(lease.sessionId, "session-aaaa");
177
+ assert.equal(lease.branch, "feat/work-order");
178
+ });
179
+
180
+ test("PreToolUse hook input with a blank session id claims no lease", async (t) => {
181
+ const repo = isolatedRepository();
182
+ t.after(repo.cleanup);
183
+ assert.equal(await decide(hookEditOf(path.join(repo.linked, "src", "a.ts"), " "), repo.linked), null);
184
+ assert.equal(existsSync(leaseFileOf(repo.linked)), false);
185
+ });
186
+
187
+ test("a second session is refused with the lease file, its holder, and commands this copy can run", async (t) => {
188
+ const repo = isolatedRepository();
189
+ t.after(repo.cleanup);
190
+ const file = path.join(repo.linked, "src", "a.ts");
191
+ assert.equal(await decide(hookEditOf(file, "session-aaaa"), repo.linked), null);
192
+ const output = await decide(hookEditOf(file, "session-bbbb"), repo.linked);
193
+ const reason = output.hookSpecificOutput.permissionDecisionReason;
194
+ assert.ok(reason.includes(slashed(leaseFileOf(repo.linked))), reason);
195
+ assert.ok(reason.includes("session session-aaaa"), reason);
196
+ assert.ok(reason.includes(`lease release "${slashed(repo.linked)}" --force`), reason);
197
+
198
+ const status = reason.match(/`node "([^"]+)" lease status "([^"]+)"`/);
199
+ assert.ok(status, `the refusal names no runnable status command: ${reason}`);
200
+ assert.equal(path.resolve(status[1]), QC, "the command must name this copy of the CLI, not whichever qc is on the path");
201
+ const shown = spawnSync(process.execPath, [status[1], "lease", "status", status[2]], { cwd: repo.outside, encoding: "utf8" });
202
+ assert.equal(shown.status, 0, shown.stderr);
203
+ assert.match(shown.stdout, /session-aaaa/);
204
+ });
@@ -39,13 +39,54 @@ export function worktreeKind(gitDir, gitCommonDir) {
39
39
  return path.resolve(gitDir) === path.resolve(gitCommonDir) ? "primary" : "linked";
40
40
  }
41
41
 
42
- /** A lease is another agent's only while it is fresh -- an abandoned session must not wedge a worktree. */
42
+ const HOUR = 3_600_000;
43
+
44
+ /** A session id is a non-empty string; anything else is no session at all. */
45
+ export function sessionIdOf(value) {
46
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : null;
47
+ }
48
+
49
+ /**
50
+ * The lease clock, the one place its age and lapse are computed. A lease binds only while it is fresh,
51
+ * so an abandoned session cannot wedge a worktree; no holder, or a bad or future time, never binds.
52
+ */
53
+ export function leaseState(lease, now, leaseHours) {
54
+ const holder = sessionIdOf(lease?.sessionId);
55
+ const written = Date.parse(lease?.updatedAt ?? "");
56
+ const age = now - written;
57
+ const lapsesAt = written + leaseHours * HOUR;
58
+ const live = holder !== null && age >= 0 && now <= lapsesAt;
59
+ return { holder, branch: lease?.branch ?? null, written, age, lapsesAt, live };
60
+ }
61
+
62
+ /** @returns the lease state when another session holds the worktree, or null. */
43
63
  export function leaseHeldByAnother(lease, sessionId, now, leaseHours) {
44
- if (!lease?.sessionId || !sessionId) return null;
45
- if (lease.sessionId === sessionId) return null;
46
- const age = now - Date.parse(lease.updatedAt ?? 0);
47
- if (!(age >= 0) || age > leaseHours * 3_600_000) return null;
48
- return lease;
64
+ const caller = sessionIdOf(sessionId);
65
+ const state = leaseState(lease, now, leaseHours);
66
+ if (!caller || !state.live || state.holder === caller) return null;
67
+ return state;
68
+ }
69
+
70
+ export function duration(ms) {
71
+ const minutes = Math.floor(ms / 60_000);
72
+ if (minutes < 1) return `${Math.floor(ms / 1000)}s`;
73
+ const hours = Math.floor(minutes / 60);
74
+ return hours > 0 ? `${hours}h ${minutes % 60}m` : `${minutes}m`;
75
+ }
76
+
77
+ export const timestamp = (ms) => new Date(ms).toISOString();
78
+
79
+ function heldRefusal(held, { branch, now, leaseFile, root, qc }) {
80
+ const at = `"${root}"`;
81
+ return (
82
+ `Another agent (session ${held.holder}) is already working in this worktree on ` +
83
+ `"${held.branch ?? branch}". Two agents on one branch lose each other's edits. ` +
84
+ `Take your own: \`git worktree add ../<slug> -b <branch>\`. ` +
85
+ `The lease is ${leaseFile}, written ${duration(held.age)} ago; it lapses at ` +
86
+ `${timestamp(held.lapsesAt)}, in ${duration(held.lapsesAt - now)}. See it: \`${qc} lease status ${at}\`. ` +
87
+ `Its holder releases it: \`${qc} lease release ${at} --session <id>\`. ` +
88
+ `Releasing another session's lease is a person's call: \`${qc} lease release ${at} --force\`.`
89
+ );
49
90
  }
50
91
 
51
92
  /**
@@ -73,14 +114,7 @@ export function isolationRefusal(state) {
73
114
  );
74
115
  }
75
116
  const held = leaseHeldByAnother(lease, sessionId, now, settings.leaseHours);
76
- if (held) {
77
- return (
78
- `Another agent (session ${held.sessionId.slice(0, 8)}) is already working in this worktree on ` +
79
- `"${held.branch ?? branch}". Two agents on one branch lose each other's edits. ` +
80
- `Take your own: \`git worktree add ../<slug> -b <branch>\`.`
81
- );
82
- }
83
- return null;
117
+ return held ? heldRefusal(held, state) : null;
84
118
  }
85
119
 
86
120
  export function denyOutput(reason) {
@@ -4,13 +4,17 @@ import {
4
4
  BRANCH,
5
5
  OFF,
6
6
  WORKTREE,
7
+ duration,
7
8
  isolationRefusal,
8
9
  isolationSettings,
9
10
  leaseHeldByAnother,
11
+ leaseState,
12
+ sessionIdOf,
10
13
  worktreeKind,
11
14
  } from "./worktree-isolation.mjs";
12
15
 
13
16
  const NOW = Date.parse("2026-09-20T12:00:00Z");
17
+ const LEASE_FILE = "/repo/.git/worktrees/tasks/qc-agent-lease.json";
14
18
  const base = (overrides = {}) => ({
15
19
  settings: isolationSettings({ isolation: { require: WORKTREE } }),
16
20
  branch: "feat/tasks",
@@ -19,6 +23,9 @@ const base = (overrides = {}) => ({
19
23
  lease: null,
20
24
  sessionId: "session-aaaa",
21
25
  now: NOW,
26
+ leaseFile: LEASE_FILE,
27
+ root: "/repo-tasks",
28
+ qc: "qc",
22
29
  ...overrides,
23
30
  });
24
31
 
@@ -65,6 +72,56 @@ test("an abandoned lease expires, so a crashed session cannot wedge a worktree",
65
72
  assert.equal(isolationRefusal(base({ lease: stale })), null);
66
73
  });
67
74
 
75
+ test("the refusal of a held lease names the file, the holder, its age, its lapse, and both lease commands", () => {
76
+ const lease = { sessionId: "session-bbbb-0000-1111", branch: "feat/tasks", updatedAt: "2026-09-20T11:30:00Z" };
77
+ const reason = isolationRefusal(base({ lease }));
78
+ assert.ok(reason.includes(LEASE_FILE), reason);
79
+ assert.ok(reason.includes("session session-bbbb-0000-1111"), "the holder is named in full, so --session can match it");
80
+ assert.ok(reason.includes("30m ago"), reason);
81
+ assert.ok(reason.includes("lapses at 2026-09-20T19:30:00.000Z, in 7h 30m"), reason);
82
+ assert.ok(reason.includes('`qc lease status "/repo-tasks"`'), reason);
83
+ assert.ok(reason.includes('`qc lease release "/repo-tasks" --session <id>`'), reason);
84
+ assert.ok(reason.includes('`qc lease release "/repo-tasks" --force`'), reason);
85
+ });
86
+
87
+ test("a lease lapses leaseHours after its last write, and not before", () => {
88
+ const lease = { sessionId: "session-bbbb", branch: "feat/tasks", updatedAt: "2026-09-20T11:00:00Z" };
89
+ const fresh = leaseState(lease, NOW, 8);
90
+ assert.deepEqual(
91
+ { holder: fresh.holder, branch: fresh.branch, age: fresh.age, lapsesAt: fresh.lapsesAt, live: fresh.live },
92
+ { holder: "session-bbbb", branch: "feat/tasks", age: 3_600_000, lapsesAt: Date.parse("2026-09-20T19:00:00Z"), live: true },
93
+ );
94
+ assert.equal(leaseState(lease, NOW, 1).live, true, "a lease exactly leaseHours old still binds");
95
+ assert.equal(leaseState(lease, NOW + 1, 1).live, false);
96
+ });
97
+
98
+ test("a lease with no readable holder or time never binds, and never crashes the guard", () => {
99
+ const written = "2026-09-20T11:30:00Z";
100
+ for (const lease of [
101
+ { sessionId: 123, updatedAt: written },
102
+ { sessionId: " ", updatedAt: written },
103
+ { sessionId: "session-bbbb", updatedAt: "yesterday-ish" },
104
+ { sessionId: "session-bbbb", updatedAt: "2026-09-20T13:00:00Z" },
105
+ ]) {
106
+ assert.equal(leaseState(lease, NOW, 8).live, false, JSON.stringify(lease));
107
+ assert.equal(isolationRefusal(base({ lease })), null, JSON.stringify(lease));
108
+ }
109
+ });
110
+
111
+ test("a blank or non-string session id is no session, so it neither holds nor is refused", () => {
112
+ assert.equal(sessionIdOf(" "), null);
113
+ assert.equal(sessionIdOf(42), null);
114
+ assert.equal(sessionIdOf(" session-aaaa "), "session-aaaa");
115
+ const lease = { sessionId: "session-bbbb", branch: "feat/tasks", updatedAt: "2026-09-20T11:30:00Z" };
116
+ assert.equal(isolationRefusal(base({ lease, sessionId: " " })), null);
117
+ });
118
+
119
+ test("a duration reads in whole hours and minutes, and seconds under a minute", () => {
120
+ assert.equal(duration(45_000), "45s");
121
+ assert.equal(duration(30 * 60_000 + 59_000), "30m");
122
+ assert.equal(duration(7 * 3_600_000 + 5 * 60_000), "7h 5m");
123
+ });
124
+
68
125
  test("a detached HEAD is refused, but not mid-rebase when detaching is the point", () => {
69
126
  assert.match(isolationRefusal(base({ branch: "" })), /HEAD is detached/);
70
127
  assert.equal(isolationRefusal(base({ branch: "", inSpecialOperation: true })), null);
package/src/config.mjs CHANGED
@@ -128,6 +128,12 @@ export const defaults = {
128
128
  // Files that may only present, never orchestrate.
129
129
  presenters: "frontend/src/features/*/trigger",
130
130
 
131
+ // Where the test-mirror gate looks. A test in `src` is misplaced; a test in `tests` mirrors a source
132
+ // file there, unless its root is `testOnly`: a package whose code is test support.
133
+ testMirror: {
134
+ roots: [{ src: "frontend/src", tests: "frontend/tests" }],
135
+ },
136
+
131
137
  // A workflow is headless-first: declared by one of these, and proven by a test that
132
138
  // imports none of the view modules. docs/architecture.md.
133
139
  saga: {
@@ -15,7 +15,7 @@ export const gateDescriptions = Object.freeze({
15
15
  "gate-tests": "A repository's own gates each ship a case that must fail",
16
16
  "audit-append-only": "The audit log has no update or delete path in any repository",
17
17
  "frontend-boundaries": "Platform remains a thin substrate and never holds feature domain logic or junk drawer directories",
18
- "test-mirror": "Frontend tests mirror src paths 1:1, and no test is orphaned without a source file",
18
+ "test-mirror": "Tests mirror src paths 1:1 in every configured root, and no test is orphaned without a source file",
19
19
  "enforcement-map": "Every rule names a check, and every check the kit runs is named",
20
20
  "config-floor": "A check the kit ships on is switched off only by naming the decision that says why",
21
21
  "english-source": "Comments, docs and rules are English; another language is data, declared beside its English variant",
@@ -1,47 +1,80 @@
1
- // Test path mirror: every frontend test must mirror a source file in frontend/src.
2
- // Tests in frontend/src/ are disallowed (they must live in frontend/tests/).
3
- // Tests in frontend/tests/ must not be orphaned (a matching source file must exist).
1
+ // Test path mirror: a test lives in its root's tests folder at its source's path, never in src. A folder
2
+ // root matches a source folder, for a block test that spans files; a testOnly root names no source.
4
3
 
5
- const TEST_PATTERN = /\.test\.(tsx?)$/;
4
+ const TEST_SUFFIX = /\.test\.[cm]?[jt]sx?$/;
5
+ const SOURCE_EXTENSION = /\.[cm]?[jt]sx?$/;
6
6
 
7
- /**
8
- * Checks that frontend tests strictly mirror frontend/src/ files and are not orphaned.
9
- *
10
- * @param {string[]} testFiles Relative paths of all test files (e.g. frontend/tests/...)
11
- * @param {string[]} srcFiles Relative paths of all source files (e.g. frontend/src/...)
12
- * @returns {{path: string, rule: string, detail: string}[]}
13
- */
14
- export function checkTestMirror(testFiles, srcFiles) {
15
- const problems = [];
16
- const srcStems = new Set(
17
- srcFiles.map((f) => f.replace(/\.(tsx?)$/, ""))
18
- );
7
+ const folder = (value) => value.replace(/\/+$/, "");
8
+ const holds = (dir, file) => file.startsWith(`${dir}/`);
9
+ const named = (value) => typeof value === "string" && folder(value) !== "";
10
+ const MATCHES = ["file", "folder"];
19
11
 
20
- for (const testFile of testFiles) {
21
- if (testFile.startsWith("frontend/src/")) {
22
- problems.push({
23
- path: testFile,
24
- rule: "unmirrored-test",
25
- detail: `${testFile}: test files must live in frontend/tests/ mirroring the src path`,
26
- });
27
- continue;
12
+ /** The roots as clean folders, or the problems that name each malformed one. */
13
+ function readRoots(roots) {
14
+ if (!Array.isArray(roots)) {
15
+ const detail = `testMirror.roots must be a list of { src, tests, match?, testOnly? }, got ${JSON.stringify(roots)}`;
16
+ return { valid: [], problems: [{ path: "qc.config.json", rule: "invalid-mirror-root", detail }] };
17
+ }
18
+ const valid = [];
19
+ const problems = [];
20
+ roots.forEach((root, index) => {
21
+ const match = root?.match ?? "file";
22
+ if (named(root?.src) && named(root?.tests) && MATCHES.includes(match)) {
23
+ valid.push({ src: folder(root.src), tests: folder(root.tests), match, testOnly: root.testOnly === true });
24
+ return;
28
25
  }
26
+ const detail = `testMirror.roots[${index}] needs a src folder, a tests folder, and a match of ${MATCHES.join(" or ")}, got ${JSON.stringify(root)}`;
27
+ problems.push({ path: "qc.config.json", rule: "invalid-mirror-root", detail });
28
+ });
29
+ return { valid, problems };
30
+ }
29
31
 
30
- if (testFile.startsWith("frontend/tests/")) {
31
- const rel = testFile.slice("frontend/tests/".length);
32
- const stem = rel.replace(TEST_PATTERN, "");
33
- const directSource = `frontend/src/${stem}`;
34
- const indexSource = `frontend/src/${stem}/index`;
32
+ /** Every folder the well-formed roots name, once each: the folders a caller walks for this gate. */
33
+ export function mirrorFolders(roots) {
34
+ const { valid } = readRoots(roots);
35
+ return [...new Set(valid.flatMap((root) => [root.src, root.tests]))];
36
+ }
35
37
 
36
- if (!srcStems.has(directSource) && !srcStems.has(indexSource)) {
37
- problems.push({
38
- path: testFile,
39
- rule: "orphaned-test",
40
- detail: `${testFile}: no matching source file at frontend/src/${stem}.{ts,tsx}`,
41
- });
42
- }
43
- }
38
+ function judge(testFile, root, srcStems, srcFolders) {
39
+ if (!holds(root.tests, testFile)) {
40
+ const detail = `${testFile}: a test in ${root.src}/ lives in ${root.tests}/, at the path that mirrors its source`;
41
+ return { path: testFile, rule: "unmirrored-test", detail };
42
+ }
43
+ if (root.testOnly) return null;
44
+ const stem = testFile.slice(root.tests.length + 1).replace(TEST_SUFFIX, "");
45
+ if (root.match === "folder") {
46
+ const within = stem.includes("/") ? stem.slice(0, stem.lastIndexOf("/")) : "";
47
+ const sourceFolder = within ? `${root.src}/${within}` : root.src;
48
+ if (srcFolders.has(sourceFolder)) return null;
49
+ const detail = `${testFile}: no source folder at ${sourceFolder} for this test in ${root.tests}/`;
50
+ return { path: testFile, rule: "orphaned-test", detail };
44
51
  }
52
+ const source = `${root.src}/${stem}`;
53
+ if (srcStems.has(source) || srcStems.has(`${source}/index`)) return null;
54
+ const detail = `${testFile}: no source at ${source} or ${source}/index for this test in ${root.tests}/`;
55
+ return { path: testFile, rule: "orphaned-test", detail };
56
+ }
45
57
 
58
+ /**
59
+ * A test is judged by the first root whose tests folder holds it, else by the first whose src
60
+ * folder does. A test in no root is not this gate's concern.
61
+ *
62
+ * @param {string[]} testFiles repository-relative paths of the test files
63
+ * @param {string[]} srcFiles repository-relative paths of the source files
64
+ * @param {{src: string, tests: string, match?: "file" | "folder", testOnly?: boolean}[]} roots `testMirror.roots`
65
+ * @returns {{path: string, rule: string, detail: string}[]}
66
+ */
67
+ export function checkTestMirror(testFiles, srcFiles, roots) {
68
+ const { valid, problems } = readRoots(roots);
69
+ const srcStems = new Set(srcFiles.map((file) => file.replace(SOURCE_EXTENSION, "")));
70
+ const srcFolders = new Set();
71
+ for (const file of srcFiles) {
72
+ for (let at = file.lastIndexOf("/"); at > 0; at = file.lastIndexOf("/", at - 1)) srcFolders.add(file.slice(0, at));
73
+ }
74
+ for (const testFile of testFiles) {
75
+ const root = valid.find((each) => holds(each.tests, testFile)) ?? valid.find((each) => holds(each.src, testFile));
76
+ const problem = root ? judge(testFile, root, srcStems, srcFolders) : null;
77
+ if (problem) problems.push(problem);
78
+ }
46
79
  return problems;
47
80
  }
@@ -1,23 +1,28 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
+ import { defaults } from "../config.mjs";
3
4
  import { checkTestMirror } from "./test-mirror.mjs";
4
5
 
6
+ const FRONTEND = [{ src: "frontend/src", tests: "frontend/tests" }];
7
+ const TWO_ROOTS = [...FRONTEND, { src: "backend/src", tests: "backend/tests" }];
8
+ const verdict = (problems) => problems.map(({ path, rule }) => ({ path, rule }));
9
+
5
10
  test("a test perfectly mirroring a source file passes", () => {
6
11
  const tests = ["frontend/tests/features/photos/slices/get-photo.test.ts"];
7
12
  const src = ["frontend/src/features/photos/slices/get-photo.ts"];
8
- assert.deepEqual(checkTestMirror(tests, src), []);
13
+ assert.deepEqual(checkTestMirror(tests, src, FRONTEND), []);
9
14
  });
10
15
 
11
16
  test("a test mirroring a view folder index passes", () => {
12
17
  const tests = ["frontend/tests/features/photos/components/photo-viewer.test.tsx"];
13
18
  const src = ["frontend/src/features/photos/components/photo-viewer/index.ts"];
14
- assert.deepEqual(checkTestMirror(tests, src), []);
19
+ assert.deepEqual(checkTestMirror(tests, src, FRONTEND), []);
15
20
  });
16
21
 
17
22
  test("a test file remaining in frontend/src is flagged as unmirrored", () => {
18
23
  const tests = ["frontend/src/features/photos/slices/get-photo.test.ts"];
19
24
  const src = ["frontend/src/features/photos/slices/get-photo.ts"];
20
- const problems = checkTestMirror(tests, src);
25
+ const problems = checkTestMirror(tests, src, FRONTEND);
21
26
  assert.equal(problems.length, 1);
22
27
  assert.equal(problems[0].rule, "unmirrored-test");
23
28
  });
@@ -25,7 +30,99 @@ test("a test file remaining in frontend/src is flagged as unmirrored", () => {
25
30
  test("an orphaned test with no matching source file is flagged", () => {
26
31
  const tests = ["frontend/tests/features/photos/slices/unknown-slice.test.ts"];
27
32
  const src = ["frontend/src/features/photos/slices/get-photo.ts"];
28
- const problems = checkTestMirror(tests, src);
33
+ const problems = checkTestMirror(tests, src, FRONTEND);
34
+ assert.equal(problems.length, 1);
35
+ assert.equal(problems[0].rule, "orphaned-test");
36
+ });
37
+
38
+ test("with two roots, a colocated backend test fails and a mirrored one passes", () => {
39
+ const tests = ["backend/src/features/tasks/slices/assign.test.ts", "backend/tests/features/tasks/slices/close.test.ts"];
40
+ const src = ["backend/src/features/tasks/slices/assign.ts", "backend/src/features/tasks/slices/close.ts"];
41
+ const problems = checkTestMirror(tests, src, TWO_ROOTS);
42
+ assert.deepEqual(verdict(problems), [{ path: "backend/src/features/tasks/slices/assign.test.ts", rule: "unmirrored-test" }]);
43
+ assert.ok(problems[0].detail.includes("backend/src/") && problems[0].detail.includes("backend/tests/"), problems[0].detail);
44
+ });
45
+
46
+ test("an orphaned test names the root it belongs to", () => {
47
+ const problems = checkTestMirror(["backend/tests/features/tasks/gone.test.ts"], ["frontend/src/features/tasks/gone.ts"], TWO_ROOTS);
48
+ assert.deepEqual(verdict(problems), [{ path: "backend/tests/features/tasks/gone.test.ts", rule: "orphaned-test" }]);
49
+ assert.ok(problems[0].detail.includes("backend/src/features/tasks/gone"), problems[0].detail);
50
+ assert.ok(problems[0].detail.includes("backend/tests/"), problems[0].detail);
51
+ });
52
+
53
+ test("the default config is the one frontend root, and gives today's frontend-only verdict", () => {
54
+ assert.deepEqual(defaults.testMirror.roots, FRONTEND);
55
+ const tests = [
56
+ "frontend/src/features/photos/slices/get-photo.test.ts",
57
+ "frontend/tests/features/photos/slices/get-photo.test.ts",
58
+ "frontend/tests/features/photos/slices/unknown-slice.test.ts",
59
+ "backend/src/features/tasks/slices/assign.test.ts",
60
+ ];
61
+ const src = ["frontend/src/features/photos/slices/get-photo.ts", "backend/src/features/tasks/slices/assign.ts"];
62
+ assert.deepEqual(verdict(checkTestMirror(tests, src, defaults.testMirror.roots)), [
63
+ { path: "frontend/src/features/photos/slices/get-photo.test.ts", rule: "unmirrored-test" },
64
+ { path: "frontend/tests/features/photos/slices/unknown-slice.test.ts", rule: "orphaned-test" },
65
+ ]);
66
+ });
67
+
68
+ test("a testOnly root accepts a test with no source stem", () => {
69
+ const tests = ["packages/testing/tests/interop/cross-tenant.test.ts"];
70
+ const root = { src: "packages/testing/src", tests: "packages/testing/tests" };
71
+ assert.deepEqual(checkTestMirror(tests, [], [{ ...root, testOnly: true }]), []);
72
+ assert.deepEqual(verdict(checkTestMirror(tests, [], [root])), [{ path: tests[0], rule: "orphaned-test" }]);
73
+ });
74
+
75
+ test("a root whose tests folder is its src folder judges a test as a test, so testOnly covers it", () => {
76
+ const root = { src: "packages/testing/src", tests: "packages/testing/src", testOnly: true };
77
+ assert.deepEqual(checkTestMirror(["packages/testing/src/interop.test.ts"], [], [root]), []);
78
+ });
79
+
80
+ test("a root claims its own folder only, not a sibling that shares its prefix", () => {
81
+ assert.deepEqual(checkTestMirror(["frontend/src-legacy/old.test.ts"], [], FRONTEND), []);
82
+ });
83
+
84
+ test("a test and its source match whatever script extension each one carries", () => {
85
+ const tests = ["frontend/tests/platform/format.test.mjs", "frontend/tests/platform/parse.test.js"];
86
+ const src = ["frontend/src/platform/format.mjs", "frontend/src/platform/parse.ts"];
87
+ assert.deepEqual(checkTestMirror(tests, src, FRONTEND), []);
88
+ });
89
+
90
+ test("a root without a src and a tests folder is a problem that names its key, not a silent pass", () => {
91
+ const problems = checkTestMirror(["backend/src/a.test.ts"], [], [{ src: "backend/src", test: "backend/tests" }]);
92
+ assert.deepEqual(verdict(problems), [{ path: "qc.config.json", rule: "invalid-mirror-root" }]);
93
+ assert.ok(problems[0].detail.includes("testMirror.roots[0]"), problems[0].detail);
94
+ });
95
+
96
+ const BACKEND_BY_FOLDER = [{ src: "backend/src", tests: "backend/tests", match: "folder" }];
97
+ const BACKEND_SOURCES = ["backend/src/features/audit-log/schema.ts", "backend/src/features/audit-log/shared/queries.ts"];
98
+
99
+ test("a folder root accepts a block test whose folder mirrors a source folder", () => {
100
+ const problems = checkTestMirror(["backend/tests/features/audit-log/record.test.ts"], BACKEND_SOURCES, BACKEND_BY_FOLDER);
101
+ assert.deepEqual(problems, []);
102
+ });
103
+
104
+ test("a folder root refuses a test whose folder mirrors no source folder", () => {
105
+ const problems = checkTestMirror(["backend/tests/features/gone/record.test.ts"], BACKEND_SOURCES, BACKEND_BY_FOLDER);
29
106
  assert.equal(problems.length, 1);
30
107
  assert.equal(problems[0].rule, "orphaned-test");
108
+ assert.match(problems[0].detail, /backend\/src\/features\/gone/);
109
+ });
110
+
111
+ test("a folder root still refuses a test left beside its source in src", () => {
112
+ const problems = checkTestMirror(["backend/src/features/audit-log/record.test.ts"], BACKEND_SOURCES, BACKEND_BY_FOLDER);
113
+ assert.equal(problems[0].rule, "unmirrored-test");
114
+ });
115
+
116
+ test("a file root still refuses the same block test, and file is the default", () => {
117
+ for (const roots of [[{ src: "backend/src", tests: "backend/tests", match: "file" }], [{ src: "backend/src", tests: "backend/tests" }]]) {
118
+ const problems = checkTestMirror(["backend/tests/features/audit-log/record.test.ts"], BACKEND_SOURCES, roots);
119
+ assert.equal(problems.length, 1);
120
+ assert.equal(problems[0].rule, "orphaned-test");
121
+ }
122
+ });
123
+
124
+ test("a match value other than file or folder is an invalid root", () => {
125
+ const problems = checkTestMirror([], BACKEND_SOURCES, [{ src: "backend/src", tests: "backend/tests", match: "stem" }]);
126
+ assert.equal(problems.length, 1);
127
+ assert.equal(problems[0].rule, "invalid-mirror-root");
31
128
  });
@@ -3,4 +3,22 @@
3
3
  # tenant predicate, route agreement, sagas. Once per push, not once per commit.
4
4
  set -euo pipefail
5
5
  cd "$(git rev-parse --show-toplevel)"
6
+
7
+ # A deletion pushes no commits, so there is nothing to gate. git sends one line per ref as
8
+ # `<local ref> <local oid> <remote ref> <remote oid>`, and a delete carries an all-zero local oid.
9
+ # Only skip when refs were named and every one of them was a delete: no refs on stdin means an
10
+ # invocation this cannot reason about, which is a reason to run the gates, not to skip them.
11
+ named=""
12
+ carries_commits=""
13
+ while read -r _local_ref local_oid _remote_ref _remote_oid; do
14
+ named=yes
15
+ case "$local_oid" in
16
+ *[!0]*) carries_commits=yes ;;
17
+ esac
18
+ done
19
+ if [ -n "$named" ] && [ -z "$carries_commits" ]; then
20
+ echo "pre-push: every ref is a delete, nothing to check"
21
+ exit 0
22
+ fi
23
+
6
24
  npx qc check