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.
@@ -0,0 +1,152 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+ import { appendRecord } from "./ledger.mjs";
9
+ import { decide } from "./worktree-gate.mjs";
10
+
11
+ const HOOK = fileURLToPath(new URL("./worktree-gate.mjs", import.meta.url));
12
+ const BRANCH = "feat/62-x";
13
+ const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" }).trim();
14
+
15
+ /** A main checkout with a pushed main, and a pushed branch in a worktree at `.worktree/kit-62`. */
16
+ function workspace(t, config = {}) {
17
+ const top = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-worktree-gate-")));
18
+ t.after(() => rmSync(top, { recursive: true, force: true }));
19
+ const origin = path.join(top, "origin.git");
20
+ const main = path.join(top, "main");
21
+ const tmp = path.join(top, "tmp");
22
+ mkdirSync(main);
23
+ mkdirSync(tmp);
24
+ git(top, "init", "-q", "--bare", "-b", "main", origin);
25
+ git(main, "init", "-q", "-b", "main");
26
+ for (const [key, value] of [["user.name", "qc"], ["user.email", "qc@example.com"], ["commit.gpgsign", "false"]]) git(main, "config", key, value);
27
+ writeFileSync(path.join(main, ".gitignore"), ".worktree/\n");
28
+ writeFileSync(path.join(main, "qc.config.json"), JSON.stringify(config));
29
+ git(main, "add", ".");
30
+ git(main, "commit", "-q", "-m", "init");
31
+ git(main, "remote", "add", "origin", origin);
32
+ git(main, "push", "-q", "-u", "origin", "main");
33
+ const worktree = path.join(main, ".worktree", "kit-62");
34
+ git(main, "worktree", "add", "-q", "-b", BRANCH, worktree);
35
+ git(worktree, "push", "-q", "-u", "origin", BRANCH);
36
+ const ledger = path.join(main, ".git", "qc", "ledger.jsonl");
37
+ return { top, main, tmp, worktree, ledger };
38
+ }
39
+
40
+ const merge = (extra = {}) => ({ type: "merge", session: "s", pr: 60, repo: "o/r", sha: "abc1234", branch: BRANCH, base: "main", mergedAt: null, issues: [], ...extra });
41
+ const stopCall = (cwd, active = false) => ({ session_id: "s", cwd, hook_event_name: "Stop", stop_hook_active: active });
42
+ const gate = (ws, cwd = ws.main, active = false, projectDir = undefined) => decide(stopCall(cwd, active), { tmp: ws.tmp, projectDir });
43
+ const dropWorktree = (ws) => git(ws.main, "worktree", "remove", "--force", ws.worktree);
44
+ const dropBranch = (ws) => git(ws.main, "branch", "-D", BRANCH);
45
+ const dropRemote = (ws) => git(ws.main, "push", "-q", "origin", "--delete", BRANCH);
46
+
47
+ test("a merged PR whose worktree remains blocks the stop, and names qc worktree remove", (t) => {
48
+ const ws = workspace(t);
49
+ appendRecord(ws.ledger, merge());
50
+ const output = gate(ws);
51
+ assert.equal(output?.decision, "block");
52
+ assert.match(output.reason, /o\/r#60 \(feat\/62-x\): `npx qc worktree remove kit-62`/);
53
+ assert.match(output.reason, /from the main checkout/i);
54
+ });
55
+
56
+ test("a merged PR whose local branch remains blocks the stop, and names git branch -D", (t) => {
57
+ const ws = workspace(t);
58
+ appendRecord(ws.ledger, merge());
59
+ dropWorktree(ws);
60
+ dropRemote(ws);
61
+ const output = gate(ws);
62
+ assert.equal(output?.decision, "block");
63
+ assert.match(output.reason, /`git branch -D feat\/62-x`/);
64
+ assert.doesNotMatch(output.reason, /qc worktree remove|push origin --delete/);
65
+ });
66
+
67
+ test("a merged PR whose remote branch remains blocks the stop, and names git push origin --delete", (t) => {
68
+ const ws = workspace(t);
69
+ appendRecord(ws.ledger, merge());
70
+ dropWorktree(ws);
71
+ dropBranch(ws);
72
+ const output = gate(ws);
73
+ assert.equal(output?.decision, "block");
74
+ assert.match(output.reason, /`git push origin --delete feat\/62-x`/);
75
+ assert.doesNotMatch(output.reason, /branch -D/);
76
+ });
77
+
78
+ test("a merged PR with its worktree, its branch, and its remote branch gone passes", (t) => {
79
+ const ws = workspace(t);
80
+ appendRecord(ws.ledger, merge());
81
+ dropWorktree(ws);
82
+ dropBranch(ws);
83
+ dropRemote(ws);
84
+ assert.equal(gate(ws), null);
85
+ });
86
+
87
+ test("worktree.enforce false lets the stop pass with the worktree in place", (t) => {
88
+ const ws = workspace(t, { worktree: { enforce: false } });
89
+ appendRecord(ws.ledger, merge());
90
+ assert.equal(gate(ws), null);
91
+ });
92
+
93
+ test("a merge of another session, a pending merge, a closed one, and a merge of a protected head pass", (t) => {
94
+ const ws = workspace(t);
95
+ appendRecord(ws.ledger, merge({ session: "other" }));
96
+ appendRecord(ws.ledger, merge({ pending: true }));
97
+ appendRecord(ws.ledger, merge({ closed: true }));
98
+ appendRecord(ws.ledger, merge({ branch: "main", base: "release/1" }));
99
+ assert.equal(gate(ws), null);
100
+ });
101
+
102
+ test("the main checkout on the merged branch is told to switch to the base first", (t) => {
103
+ const ws = workspace(t);
104
+ appendRecord(ws.ledger, merge());
105
+ dropWorktree(ws);
106
+ dropRemote(ws);
107
+ git(ws.main, "switch", "-q", BRANCH);
108
+ const output = gate(ws);
109
+ assert.match(output.reason, /`git switch main`, then `git branch -D feat\/62-x`/);
110
+ });
111
+
112
+ test("a repeat stop with the same leftovers ends with a note, and a changed one blocks again", (t) => {
113
+ const ws = workspace(t);
114
+ appendRecord(ws.ledger, merge());
115
+ assert.equal(gate(ws)?.decision, "block");
116
+ const repeat = gate(ws, ws.main, true);
117
+ assert.equal(repeat?.decision, undefined);
118
+ assert.match(repeat.systemMessage, /same.*kit-62/s);
119
+ dropWorktree(ws);
120
+ dropRemote(ws);
121
+ assert.equal(gate(ws, ws.main, true)?.decision, "block", "a changed text blocks again");
122
+ dropBranch(ws);
123
+ assert.equal(gate(ws, ws.main, true), null);
124
+ assert.deepEqual(readdirSync(path.join(ws.tmp, "qc-worktree-gate")), [], "a clean stop forgets the last block");
125
+ });
126
+
127
+ test("a stop whose cwd is a removed worktree judges its main checkout, and one outside every checkout reads the project dir", (t) => {
128
+ const ws = workspace(t);
129
+ appendRecord(ws.ledger, merge());
130
+ const gone = path.join(ws.main, ".worktree", "kit-61");
131
+ assert.equal(gate(ws, gone)?.decision, "block");
132
+ const outside = path.join(ws.top, "tmp");
133
+ assert.equal(gate(ws, outside), null);
134
+ assert.equal(gate(ws, outside, false, ws.main)?.decision, "block");
135
+ });
136
+
137
+ test("the hook process is silent in a checkout with no merge, and prints the block after one", (t) => {
138
+ const ws = workspace(t);
139
+ const run = () => spawnSync(process.execPath, [HOOK], {
140
+ input: JSON.stringify(stopCall(ws.main)),
141
+ env: { ...process.env, TEMP: ws.tmp, TMP: ws.tmp, TMPDIR: ws.tmp, CLAUDE_PROJECT_DIR: "" },
142
+ encoding: "utf8",
143
+ });
144
+ const quiet = run();
145
+ assert.equal(quiet.status, 0, quiet.stderr);
146
+ assert.equal(quiet.stdout, "");
147
+ appendRecord(ws.ledger, merge());
148
+ const blocked = run();
149
+ assert.equal(blocked.status, 0, blocked.stderr);
150
+ assert.equal(JSON.parse(blocked.stdout).decision, "block");
151
+ assert.ok(existsSync(ws.worktree));
152
+ });
@@ -0,0 +1,27 @@
1
+ // A fragment that reads the worktree rule of QC-015 for the hooks: the folder that holds each worktree,
2
+ // and the ledger that records a merge. It is on wherever `qc.config.json` is, until `worktree.enforce` is false.
3
+
4
+ import { existsSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { CONFIG_FILE, load } from "../config.mjs";
7
+ import { checkoutRootOf } from "./checkout-root.mjs";
8
+ import { commonDirOf, ledgerFileOf } from "./ledger.mjs";
9
+
10
+ /**
11
+ * @returns `{ root, main, folder, ledger, config }` for the checkout that holds `cwd`, where `main` is the main
12
+ * checkout and `folder` is its worktree folder; null when the rule is off or the config cannot be read.
13
+ */
14
+ export function worktreeRuleAt(cwd) {
15
+ const root = checkoutRootOf(cwd);
16
+ if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
17
+ let config;
18
+ try {
19
+ config = load(root);
20
+ } catch {
21
+ return null;
22
+ }
23
+ const common = commonDirOf(root);
24
+ if (config.worktree?.enforce === false || !common) return null;
25
+ const main = path.dirname(common);
26
+ return { root, main, folder: path.join(main, config.worktree.dir), ledger: ledgerFileOf(root), config };
27
+ }
@@ -1,18 +1,20 @@
1
- // A pipeline: `qc worktree add` makes a linked worktree beside the main checkout and installs it.
2
- // `qc worktree remove` deletes one, and deletes its branch only when no commit would be lost.
1
+ // A pipeline: `qc worktree add` makes a linked worktree under `worktree.dir` in the main checkout, and installs it.
2
+ // `qc worktree remove` deletes one, and deletes its branch only when no commit would be lost. QC-015.
3
3
 
4
4
  import { spawnSync } from "node:child_process";
5
- import { existsSync, realpathSync } from "node:fs";
5
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync } from "node:fs";
6
6
  import { rm } from "node:fs/promises";
7
7
  import path from "node:path";
8
+ import { runGh } from "./gh-run.mjs";
8
9
 
9
- export const USAGE = `qc worktree — a linked worktree beside the main checkout
10
+ export const USAGE = `qc worktree — a linked worktree under .worktree/ in the main checkout
10
11
 
11
- qc worktree add <name> <branch> [--from <ref>] fetch, add ../<name> on <branch>, install, print the path
12
- qc worktree remove <name> [--from <ref>] refuse a dirty tree; delete it, then the branch once merged or pushed
12
+ qc worktree add <name> <branch> [--from <ref>] fetch, add .worktree/<name> on <branch>, install, print the path
13
+ qc worktree remove <name> [--from <ref>] refuse a dirty tree; delete it, then the branch once merged, pushed, or a merged PR head
13
14
 
14
15
  --from the ref a new branch starts at, and the ref remove checks a merge against.
15
- The default is worktree.base in qc.config.json. The install is worktree.install.`;
16
+ The default is worktree.base in qc.config.json. The install is worktree.install.
17
+ The folder is worktree.dir. remove also finds a worktree at ../<name>, beside the main checkout.`;
16
18
 
17
19
  function git(cwd, ...args) {
18
20
  const result = spawnSync("git", args, { cwd, encoding: "utf8" });
@@ -31,13 +33,22 @@ export function keyOf(file) {
31
33
  return process.platform === "win32" ? path.resolve(real).toLowerCase() : path.resolve(real);
32
34
  }
33
35
 
34
- function mainCheckout(cwd) {
36
+ function commonDir(cwd) {
35
37
  const common = git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir");
36
- return common.ok ? path.dirname(common.out) : null;
38
+ return common.ok ? common.out : null;
39
+ }
40
+
41
+ /** Adds `<dir>/` to info/exclude when no rule ignores the target, so the main checkout's status stays clean. */
42
+ function ignoreFolder(common, main, dir, target) {
43
+ if (git(main, "check-ignore", "-q", path.relative(main, target).split(path.sep).join("/")).ok) return;
44
+ const exclude = path.join(common, "info", "exclude");
45
+ mkdirSync(path.dirname(exclude), { recursive: true });
46
+ const text = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
47
+ appendFileSync(exclude, `${text === "" || text.endsWith("\n") ? "" : "\n"}${dir.replace(/\/+$/, "")}/\n`);
37
48
  }
38
49
 
39
50
  /** @returns {{path: string, branch?: string}[]} */
40
- function worktrees(main) {
51
+ export function worktrees(main) {
41
52
  return git(main, "worktree", "list", "--porcelain")
42
53
  .out.split(/\n\s*\n/)
43
54
  .map((block) => {
@@ -58,6 +69,7 @@ async function add(config, main, target, branch, from) {
58
69
  console.error(`${target} exists and is not a worktree of this repository.`);
59
70
  return 1;
60
71
  }
72
+ ignoreFolder(commonDir(main), main, config.worktree.dir, target);
61
73
  const fetched = git(main, "fetch", "--quiet");
62
74
  if (!fetched.ok) {
63
75
  console.error(fetched.err);
@@ -85,22 +97,47 @@ async function add(config, main, target, branch, from) {
85
97
  return 0;
86
98
  }
87
99
 
88
- /** A branch goes only when the base holds it, or its upstream holds every commit. */
89
- function settleBranch(main, branch, from) {
100
+ /** The merged PR whose head is `branch` at `tip`, so a squash merge counts. A gh that fails or is absent proves nothing. */
101
+ function mergedPr(main, branch, tip, gh) {
102
+ const out = gh(["pr", "list", "--head", branch, "--state", "merged", "--json", "number,headRefOid"], { cwd: main });
103
+ try {
104
+ const prs = out === null ? [] : JSON.parse(out);
105
+ return (Array.isArray(prs) && prs.find((pr) => tip !== "" && pr?.headRefOid === tip)) || null;
106
+ } catch {
107
+ return null;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * A branch goes when the base holds it, its upstream holds every commit, or a merged PR has it as its head at its tip.
113
+ * The remote branch goes too while it is still at the head of that merged PR.
114
+ */
115
+ function settleBranch(main, branch, from, gh) {
116
+ const tip = git(main, "rev-parse", "--verify", "--quiet", `refs/heads/${branch}`).out;
90
117
  const merged = git(main, "merge-base", "--is-ancestor", branch, from).ok;
91
118
  const upstream = git(main, "rev-parse", "--abbrev-ref", `${branch}@{upstream}`);
92
119
  const pushed = upstream.ok && git(main, "rev-list", "--count", `${upstream.out}..${branch}`).out === "0";
93
- if (!merged && !pushed) return `kept branch ${branch}: ${from} does not hold it, and it has commits no remote holds`;
120
+ const remote = git(main, "ls-remote", "--heads", "origin", `refs/heads/${branch}`);
121
+ const onRemote = remote.ok && tip !== "" && remote.out.split(/\s/)[0] === tip;
122
+ const pr = (!merged && !pushed) || onRemote ? mergedPr(main, branch, tip, gh) : null;
123
+ if (!merged && !pushed && !pr) return `kept branch ${branch}: ${from} does not hold it, and it has commits no remote holds`;
94
124
  const deleted = git(main, "branch", "-D", branch);
95
- return deleted.ok ? `deleted branch ${branch}` : `kept branch ${branch}: ${deleted.err}`;
125
+ const lines = [deleted.ok ? `deleted branch ${branch}` : `kept branch ${branch}: ${deleted.err}`];
126
+ if (pr && onRemote) {
127
+ const gone = git(main, "push", "--quiet", "origin", "--delete", branch);
128
+ lines.push(gone.ok ? `deleted origin/${branch}, the head of merged #${pr.number}` : `kept origin/${branch}: ${gone.err}`);
129
+ }
130
+ return lines.join("\n");
96
131
  }
97
132
 
98
- async function remove(main, target, from) {
133
+ async function remove(main, targets, from, gh) {
134
+ const listed = worktrees(main);
135
+ const found = targets.map((target) => listed.find((entry) => keyOf(entry.path) === keyOf(target))).find(Boolean);
136
+ const target = found?.path ?? targets[0];
99
137
  if (keyOf(target) === keyOf(main)) {
100
138
  console.error("refusing to remove the main checkout.");
101
139
  return 1;
102
140
  }
103
- const found = worktrees(main).find((entry) => keyOf(entry.path) === keyOf(target));
104
141
  if (!found) {
105
142
  if (existsSync(target)) {
106
143
  console.error(`${target} is not a worktree of this repository. Nothing was removed.`);
@@ -119,7 +156,7 @@ async function remove(main, target, from) {
119
156
  await rm(target, { recursive: true, force: true, maxRetries: 5 });
120
157
  }
121
158
  git(main, "worktree", "prune");
122
- if (found.branch) console.log(settleBranch(main, found.branch, from));
159
+ if (found.branch) console.log(settleBranch(main, found.branch, from, gh));
123
160
  console.log(`removed ${target}`);
124
161
  return 0;
125
162
  }
@@ -127,19 +164,21 @@ async function remove(main, target, from) {
127
164
  /**
128
165
  * @param {object} config
129
166
  * @param {string[]} args `add <name> <branch> [--from <ref>]` or `remove <name> [--from <ref>]`
167
+ * @param {{gh?: typeof runGh}} [io] the gh call that proves a squash merge
130
168
  * @returns {Promise<number>} the exit code
131
169
  */
132
- export async function runWorktree(config, args) {
170
+ export async function runWorktree(config, args, { gh = runGh } = {}) {
133
171
  const [command, ...rest] = args;
134
172
  const at = rest.indexOf("--from");
135
173
  const from = at === -1 ? config.worktree?.base ?? "origin/main" : rest[at + 1];
136
174
  const [name, branch] = at === -1 ? rest : [...rest.slice(0, at), ...rest.slice(at + 2)];
137
- const main = mainCheckout(config.root);
175
+ const common = commonDir(config.root);
176
+ const main = common && path.dirname(common);
138
177
  const usable = main && from && name && !/[\\/]/.test(name) && name !== "." && name !== "..";
139
178
  if (!usable || !(command === "remove" || (command === "add" && branch))) {
140
179
  console.error(main ? USAGE : "qc worktree runs inside a git repository.");
141
180
  return 1;
142
181
  }
143
- const target = path.join(path.dirname(main), name);
144
- return command === "add" ? add(config, main, target, branch, from) : remove(main, target, from);
182
+ const inside = path.join(main, config.worktree.dir, name);
183
+ return command === "add" ? add(config, main, inside, branch, from) : remove(main, [inside, path.join(path.dirname(main), name)], from, gh);
145
184
  }
@@ -1,10 +1,12 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
3
  import { execFileSync, spawnSync } from "node:child_process";
4
- import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
6
  import path from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
+ import { load } from "../config.mjs";
9
+ import { runWorktree } from "./worktree.mjs";
8
10
 
9
11
  const QC = fileURLToPath(new URL("./qc.mjs", import.meta.url));
10
12
  const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" }).trim();
@@ -27,8 +29,8 @@ const listedWorktrees = (cwd) =>
27
29
  // The install writes only what git ignores, as pnpm does, so a fresh worktree stays clean.
28
30
  const INSTALL = `node -e "require('fs').mkdirSync('node_modules',{recursive:true})"`;
29
31
 
30
- /** A main checkout at <top>/main with a pushed main branch, so worktrees land inside <top>. */
31
- function fixture() {
32
+ /** A main checkout at <top>/main with a pushed main branch. `worktree` and `ignore` add to its config and its .gitignore. */
33
+ function fixture({ worktree = {}, ignore = "" } = {}) {
32
34
  const top = mkdtempSync(path.join(tmpdir(), "qc-wt-"));
33
35
  const origin = path.join(top, "origin.git");
34
36
  const main = path.join(top, "main");
@@ -38,8 +40,8 @@ function fixture() {
38
40
  git(main, "config", "user.name", "qc");
39
41
  git(main, "config", "user.email", "qc@example.com");
40
42
  git(main, "config", "commit.gpgsign", "false");
41
- writeFileSync(path.join(main, ".gitignore"), "node_modules/\n");
42
- writeFileSync(path.join(main, "qc.config.json"), JSON.stringify({ worktree: { install: INSTALL } }));
43
+ writeFileSync(path.join(main, ".gitignore"), `node_modules/\n${ignore}`);
44
+ writeFileSync(path.join(main, "qc.config.json"), JSON.stringify({ worktree: { install: INSTALL, ...worktree } }));
43
45
  git(main, "add", ".");
44
46
  git(main, "commit", "-q", "-m", "init");
45
47
  git(main, "remote", "add", "origin", origin);
@@ -53,10 +55,12 @@ function added(main, name, branch) {
53
55
  return lastLine(result.stdout);
54
56
  }
55
57
 
56
- test("add makes a worktree beside the main checkout and installs it; remove deletes it and its merged branch", () => {
58
+ test("add makes a worktree under .worktree/ in the main checkout and installs it; remove deletes it and its merged branch", () => {
57
59
  const { top, main } = fixture();
58
60
  const where = added(main, "wt-a", "feat/a");
59
- assert.equal(realpathSync.native(where), realpathSync.native(path.join(top, "wt-a")));
61
+ assert.equal(realpathSync.native(where), realpathSync.native(path.join(main, ".worktree", "wt-a")));
62
+ assert.equal(git(main, "status", "--porcelain"), "", "the worktree folder must be ignored in the main checkout");
63
+ assert.match(readFileSync(path.join(main, ".git", "info", "exclude"), "utf8"), /^\.worktree\/$/m);
60
64
  assert.ok(existsSync(path.join(where, "node_modules")), "the install command did not run in the worktree");
61
65
  assert.equal(git(where, "branch", "--show-current"), "feat/a");
62
66
  assert.equal(added(main, "wt-a", "feat/a"), where, "a second add must find the same worktree");
@@ -125,3 +129,98 @@ test("remove deletes a worktree that holds a path longer than 260 characters", (
125
129
  assert.ok(!listedWorktrees(main).includes(registered), "git still lists the removed worktree");
126
130
  rmSync(top, { recursive: true, force: true });
127
131
  });
132
+
133
+ test("add leaves info/exclude alone when the folder is already ignored, and worktree.dir moves the folder", () => {
134
+ const { top, main } = fixture({ worktree: { dir: "trees" }, ignore: "trees/\n" });
135
+ const exclude = path.join(main, ".git", "info", "exclude");
136
+ const before = existsSync(exclude) ? readFileSync(exclude, "utf8") : null;
137
+ const where = added(main, "wt-d", "feat/d");
138
+ assert.equal(realpathSync.native(where), realpathSync.native(path.join(main, "trees", "wt-d")));
139
+ assert.equal(existsSync(exclude) ? readFileSync(exclude, "utf8") : null, before);
140
+ assert.equal(git(main, "status", "--porcelain"), "");
141
+ rmSync(top, { recursive: true, force: true });
142
+ });
143
+
144
+ test("remove finds a worktree at the sibling path beside the main checkout", () => {
145
+ const { top, main } = fixture();
146
+ const legacy = path.join(top, "wt-old");
147
+ git(main, "worktree", "add", "-q", "-b", "feat/old", legacy, "origin/main");
148
+ const removed = qc(main, "remove", "wt-old");
149
+ assert.equal(removed.status, 0, removed.stderr);
150
+ assert.equal(existsSync(legacy), false);
151
+ assert.ok(!listedWorktrees(main).includes(samePath(legacy)), "git still lists the removed worktree");
152
+ rmSync(top, { recursive: true, force: true });
153
+ });
154
+
155
+ const PR_LIST = ["pr", "list", "--head"];
156
+
157
+ /** A gh stand-in that answers `gh pr list --head` with `prs`, and logs each call. */
158
+ function fakeGh(prs) {
159
+ const calls = [];
160
+ return { calls, gh: (args) => (calls.push(args), args.slice(0, 3).join(" ") === PR_LIST.join(" ") ? JSON.stringify(prs) : null) };
161
+ }
162
+
163
+ /** A worktree whose one commit reached main as a squash, as `gh pr merge --squash` leaves it. */
164
+ function squashed(main, name, branch) {
165
+ const where = added(main, name, branch);
166
+ writeFileSync(path.join(where, "work.txt"), "done\n");
167
+ git(where, "add", "work.txt");
168
+ git(where, "commit", "-q", "-m", "work");
169
+ git(where, "push", "-q", "-u", "origin", branch);
170
+ writeFileSync(path.join(main, "work.txt"), "done\n");
171
+ git(main, "add", "work.txt");
172
+ git(main, "commit", "-q", "-m", "work (#7)");
173
+ git(main, "push", "-q", "origin", "main");
174
+ return { where, tip: git(main, "rev-parse", branch) };
175
+ }
176
+
177
+ const removeIn = (main, name, gh) => runWorktree(load(main), ["remove", name], { gh });
178
+
179
+ test("remove deletes a squash-merged branch whose upstream is gone, on a merged PR with the same head", async () => {
180
+ const { top, main } = fixture();
181
+ const { tip } = squashed(main, "wt-s", "feat/s");
182
+ git(main, "push", "-q", "origin", "--delete", "feat/s");
183
+ git(main, "fetch", "-q", "--prune");
184
+ const { gh, calls } = fakeGh([{ number: 7, headRefOid: tip }]);
185
+ assert.equal(await removeIn(main, "wt-s", gh), 0);
186
+ assert.equal(git(main, "branch", "--list", "feat/s"), "");
187
+ assert.deepEqual(calls[0], ["pr", "list", "--head", "feat/s", "--state", "merged", "--json", "number,headRefOid"]);
188
+ rmSync(top, { recursive: true, force: true });
189
+ });
190
+
191
+ test("remove deletes the remote branch of a merged PR that gh pr merge could not delete", async () => {
192
+ const { top, main } = fixture();
193
+ const { tip } = squashed(main, "wt-r", "feat/r");
194
+ assert.equal(await removeIn(main, "wt-r", fakeGh([{ number: 7, headRefOid: tip }]).gh), 0);
195
+ assert.equal(git(main, "branch", "--list", "feat/r"), "");
196
+ assert.equal(git(main, "ls-remote", "--heads", "origin", "feat/r"), "");
197
+ rmSync(top, { recursive: true, force: true });
198
+ });
199
+
200
+ test("remove keeps a branch with unpushed commits when no merged PR has it as its head", async () => {
201
+ const { top, main } = fixture();
202
+ const where = added(main, "wt-k", "feat/k");
203
+ writeFileSync(path.join(where, "work.txt"), "done\n");
204
+ git(where, "add", "work.txt");
205
+ git(where, "commit", "-q", "-m", "work");
206
+ for (const answer of [[], null]) {
207
+ if (!existsSync(where)) added(main, "wt-k", "feat/k");
208
+ const gh = answer === null ? () => null : fakeGh(answer).gh;
209
+ assert.equal(await removeIn(main, "wt-k", gh), 0);
210
+ assert.notEqual(git(main, "branch", "--list", "feat/k"), "", `kept with gh answering ${JSON.stringify(answer)}`);
211
+ }
212
+ rmSync(top, { recursive: true, force: true });
213
+ });
214
+
215
+ test("remove keeps a branch whose tip moved past the head of its merged PR", async () => {
216
+ const { top, main } = fixture();
217
+ const { where, tip } = squashed(main, "wt-m", "feat/m");
218
+ writeFileSync(path.join(where, "more.txt"), "later\n");
219
+ git(where, "add", "more.txt");
220
+ git(where, "commit", "-q", "-m", "more");
221
+ git(main, "push", "-q", "origin", "--delete", "feat/m");
222
+ git(main, "fetch", "-q", "--prune");
223
+ assert.equal(await removeIn(main, "wt-m", fakeGh([{ number: 7, headRefOid: tip }]).gh), 0);
224
+ assert.notEqual(git(main, "branch", "--list", "feat/m"), "");
225
+ rmSync(top, { recursive: true, force: true });
226
+ });
package/src/config.mjs CHANGED
@@ -256,7 +256,8 @@ export const defaults = {
256
256
 
257
257
  // `qc worktree`. `install` runs in each new worktree. `base` is the default `--from`: the ref a
258
258
  // branch starts at, and the ref `remove` checks a merge against.
259
- worktree: { install: "pnpm install --frozen-lockfile", base: "origin/main" },
259
+ // `dir` holds each worktree, inside the main checkout. `enforce: false` turns off the QC-015 hooks.
260
+ worktree: { install: "pnpm install --frozen-lockfile", base: "origin/main", dir: ".worktree", enforce: true },
260
261
 
261
262
  // Names that must be registered scoped, never singleton.
262
263
  scopedSuffixes: ["Repository", "Saga", "UnitOfWork", "UnitOfWorkFactory"],
@@ -602,6 +603,12 @@ export function readerEntries(registry) {
602
603
  .map(([key, entry]) => ({ key, names: entry.names ?? [], readers: entry.readers ?? [] }));
603
604
  }
604
605
 
606
+ /** `ignores` and the worktree folder, so a repository's own list of ignores still skips each worktree. */
607
+ export function ignoresOf(config) {
608
+ const dir = config.worktree?.dir;
609
+ return dir ? [...config.ignores, `${dir.replace(/\/+$/, "")}/**`] : config.ignores;
610
+ }
611
+
605
612
  export function enabled(map, id) {
606
613
  return map[id] !== false;
607
614
  }
@@ -2,7 +2,7 @@
2
2
  // Thresholds are imported, never restated — quality-thresholds.json is their one home.
3
3
 
4
4
  import qc from "./index.mjs";
5
- import { enabled, load, readerEntries, thresholds } from "../config.mjs";
5
+ import { enabled, ignoresOf, load, readerEntries, thresholds } from "../config.mjs";
6
6
  import { literalRegistries } from "../registries.mjs";
7
7
 
8
8
  /**
@@ -129,7 +129,7 @@ export function preset(options = {}) {
129
129
  const { tseslint, boundaries, sonarjs } = options.plugins ?? {};
130
130
 
131
131
  // No file carries its own exemption: a rule is switched off in config, where a reviewer sees it.
132
- const blocks = [{ ignores: config.ignores }, { linterOptions: { noInlineConfig: true, reportUnusedDisableDirectives: "error" } }];
132
+ const blocks = [{ ignores: ignoresOf(config) }, { linterOptions: { noInlineConfig: true, reportUnusedDisableDirectives: "error" } }];
133
133
 
134
134
  const base = {
135
135
  files: ["**/*.{ts,tsx,mjs}"],
@@ -74,9 +74,11 @@ test("the tooling block turns every qc rule off, so a gate can name what it bans
74
74
  }
75
75
  });
76
76
 
77
- test("ignores come from the config", () => {
77
+ test("ignores come from the config, and a repository list of its own still skips the worktree folder", () => {
78
78
  const blocks = preset({ config: config({ ignores: ["**/generated/**"] }) });
79
- assert.deepEqual(blocks[0].ignores, ["**/generated/**"]);
79
+ assert.deepEqual(blocks[0].ignores, ["**/generated/**", ".worktree/**"]);
80
+ const moved = preset({ config: config({ ignores: [], worktree: { dir: "trees/" } }) });
81
+ assert.deepEqual(moved[0].ignores, ["trees/**"]);
80
82
  });
81
83
 
82
84
  test("the layer block is emitted only when a boundaries plugin is supplied", () => {
@@ -128,11 +128,19 @@ const EXEMPT = /\/\/\s*tenant-predicate:\s*exempt\s*—\s*(.+)/;
128
128
  // A migration file is `<sequence>_<slug>.sql`; the slug names the feature that owns it.
129
129
  const MIGRATION_FILE = /^\d+_(.+)\.sql$/;
130
130
 
131
+ // One pass, left to right: a template literal, a quoted string with escapes, or a comment. A comment
132
+ // is matched to be skipped, so an apostrophe in one opens no string.
133
+ const LITERAL = /`([^`]*)`|'((?:[^'\\\n]|\\.)*)'|"((?:[^"\\\n]|\\.)*)"|\/\/[^\n]*|\/\*[\s\S]*?\*\//g;
134
+ const TEMPLATE_STATEMENT = /\b(select|insert into|update|delete from)\b/i;
135
+ // A quoted string needs the whole shape: a UI label such as "select a folder" opens with a keyword too.
136
+ const QUOTED_STATEMENT = /\bselect\b[^]*\bfrom\b|\binsert\s+into\b|\bupdate\b[^]*\bset\b|\bdelete\s+from\b/i;
137
+
131
138
  function statements(source) {
132
139
  const found = [];
133
- for (const match of source.matchAll(/`([^`]*)`/g)) {
134
- const body = match[1];
135
- if (!/\b(select|insert into|update|delete from)\b/i.test(body)) continue;
140
+ for (const match of source.matchAll(LITERAL)) {
141
+ const body = match[1] ?? match[2] ?? match[3];
142
+ if (body === undefined) continue;
143
+ if (!(match[1] === undefined ? QUOTED_STATEMENT : TEMPLATE_STATEMENT).test(body)) continue;
136
144
  const preamble = source.slice(Math.max(0, match.index - 400), match.index);
137
145
  const lastLines = preamble.split("\n").slice(-4).join("\n");
138
146
  found.push({
@@ -6,6 +6,7 @@ import {
6
6
  declaredColumns,
7
7
  migrationNames,
8
8
  schemaTables,
9
+ sqlStatements,
9
10
  tableOwners,
10
11
  usedIdentifiers,
11
12
  } from "./sql-identifiers.mjs";
@@ -189,6 +190,44 @@ test("a migration filename with an underscore names a hyphenated feature", () =>
189
190
  assert.equal(owners.get("projects"), "identity-tenancy");
190
191
  });
191
192
 
193
+ const crossFeature = (source) => {
194
+ const owners = tableOwners([{ file: "0002_projects.sql", sql: ddl }]);
195
+ return checkSqlIdentifiers(declaredColumns([ddl]), [{ path: "r.ts", source, feature: "pins" }], owners);
196
+ };
197
+
198
+ test("a double-quoted statement reading another feature's table is named", () => {
199
+ const problems = crossFeature('const q = "select id from projects where tenant_id = $1";');
200
+ assert.deepEqual(problems.map((problem) => problem.rule), ["cross-feature-table"]);
201
+ });
202
+
203
+ test("a single-quoted statement reading another feature's table is named", () => {
204
+ const problems = crossFeature("const q = 'select id from projects where tenant_id = $1';");
205
+ assert.deepEqual(problems.map((problem) => problem.rule), ["cross-feature-table"]);
206
+ });
207
+
208
+ test("an escaped quote inside a quoted statement does not end it", () => {
209
+ const problems = crossFeature(`const q = "select id from projects where code = \\"x\\" and tenant_id = $1";`);
210
+ assert.deepEqual(problems.map((problem) => problem.rule), ["cross-feature-table"]);
211
+ });
212
+
213
+ test("a UI label that starts with a SQL keyword is not a statement", () => {
214
+ const source = `const label = "select a folder"; const hint = 'update your profile'; const cta = "delete the folder";`;
215
+ assert.deepEqual(sqlStatements(source), []);
216
+ assert.deepEqual(crossFeature(source), []);
217
+ });
218
+
219
+ test("an apostrophe in a comment opens no string", () => {
220
+ const source = `// don't read it
221
+ const q = "select id from projects where tenant_id = $1";`;
222
+ assert.equal(sqlStatements(source).length, 1);
223
+ });
224
+
225
+ test("the exemption comment above a quoted statement is kept", () => {
226
+ const source = `// tenant-predicate: exempt — a share is found by its secret
227
+ const q = "select id from projects where code = $1";`;
228
+ assert.equal(sqlStatements(source)[0].exemption, "a share is found by its secret");
229
+ });
230
+
192
231
  test("a recursive common table expression binds its own name", () => {
193
232
  const tables = declaredColumns([ddl]);
194
233
  const source = resource(
@@ -5,6 +5,7 @@
5
5
  "reporters": ["console"],
6
6
  "ignore": [
7
7
  "**/node_modules/**",
8
+ "**/.worktree/**",
8
9
  "**/dist/**",
9
10
  "**/*.test.*",
10
11
  "**/*.generated.*",
@@ -70,3 +70,4 @@ portable ones; delete any that do not apply and add your own rather than renumbe
70
70
  | QC-007 | A rule that cannot name its check is deleted or converted into one | `docs/enforcement.md` carries the map |
71
71
  | QC-008 | A change is rewritten in place, as if it had always been that way | No supersession trail, no deprecation note, no "what this replaces". The repository states what is true now; git holds the history |
72
72
  | QC-010 | Headless-first command and saga architecture | Every multi-step workflow is an executable pipeline or command callable headlessly without a browser. UI components are thin presenters invoking these workflows. Headless tests verify state transitions, idempotency, and compensations |
73
+ | QC-015 | A worktree lives in `.worktree/<name>` inside the main checkout, and a merged pull request leaves no worktree and no branch | `qc worktree add` makes each worktree there, and git ignores the folder. A `git worktree add` to another path is refused. A turn that merged a pull request ends only after the worktree, the local branch, and the remote branch of its head are gone. A merged pull request at the branch tip proves a squash merge. `worktree.enforce: false` turns the hooks off. A test run inside `.worktree/<name>/` can resolve a missing dependency from the `node_modules` of the main checkout, which hides it, so CI in a clean checkout is the dependency check |
@@ -72,6 +72,16 @@ recorded.
72
72
  | The controller edits only its own paths | `controller-guard.mjs` |
73
73
  | A plan task names its files, a test step, and a commit step, within the budget | `qc plan-check`, and `plan-stop.mjs` |
74
74
 
75
+ ## Worktrees — QC-015
76
+
77
+ These hooks are on wherever `qc.config.json` is. `"worktree": { "enforce": false }` turns them off.
78
+
79
+ | Rule | Check |
80
+ |---|---|
81
+ | A worktree is one folder directly under `worktree.dir` of the main checkout | `bash-command-guard.mjs`, on `PreToolUse` of `Bash` and `PowerShell` |
82
+ | A pull request this session merged leaves no worktree, local branch, or remote branch on its head | `worktree-gate.mjs`, on `Stop`, from the merge record of `merge-guard.mjs` |
83
+ | A squash-merged branch is deleted | `qc worktree remove`, on a merged pull request whose head is the branch at its tip |
84
+
75
85
  ## File length
76
86
 
77
87
  A block is one file, and the gate is `filelength` in `quality-thresholds.json`. Blanks and comments