architecture-harness 0.18.2 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/package.json +1 -1
  2. package/src/cli/bash-command-guard.mjs +60 -11
  3. package/src/cli/bash-command-guard.test.mjs +66 -0
  4. package/src/cli/check-input.mjs +24 -0
  5. package/src/cli/check.mjs +2 -2
  6. package/src/cli/cli.test.mjs +50 -1
  7. package/src/cli/dispatch-guard.test.mjs +6 -23
  8. package/src/cli/dispatch-reminder.mjs +3 -3
  9. package/src/cli/dispatch-reminder.test.mjs +15 -10
  10. package/src/cli/dispatch.mjs +4 -3
  11. package/src/cli/dispatch.test.mjs +25 -17
  12. package/src/cli/explore-guard.mjs +11 -87
  13. package/src/cli/explore-guard.test.mjs +34 -97
  14. package/src/cli/explore-hint.mjs +3 -3
  15. package/src/cli/explore-hint.test.mjs +14 -5
  16. package/src/cli/init.mjs +12 -0
  17. package/src/cli/merge-guard.mjs +4 -0
  18. package/src/cli/merge-guard.test.mjs +21 -2
  19. package/src/cli/plugin-agents.test.mjs +4 -4
  20. package/src/cli/powershell-command.mjs +1 -1
  21. package/src/cli/qc.mjs +9 -4
  22. package/src/cli/workflow-hooks.test.mjs +1 -0
  23. package/src/cli/worktree-gate.mjs +117 -0
  24. package/src/cli/worktree-gate.test.mjs +152 -0
  25. package/src/cli/worktree-settings.mjs +27 -0
  26. package/src/cli/worktree.mjs +60 -21
  27. package/src/cli/worktree.test.mjs +106 -7
  28. package/src/config.mjs +19 -13
  29. package/src/eslint/preset.mjs +2 -2
  30. package/src/eslint/preset.test.mjs +4 -2
  31. package/src/gates/sql-identifiers.mjs +11 -3
  32. package/src/gates/sql-identifiers.test.mjs +39 -0
  33. package/templates/.jscpd.json +1 -0
  34. package/templates/docs/decisions.md +1 -0
  35. package/templates/docs/enforcement.md +10 -0
  36. package/templates/githooks/pre-commit +8 -6
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env node
2
+ // The Stop trigger of QC-015: a PR this session merged leaves no worktree, local branch, or remote branch on its
3
+ // head. It reads the merge records of the ledger, and runs git only for a merge of this session.
4
+
5
+ import { spawnSync } from "node:child_process";
6
+ import { createHash } from "node:crypto";
7
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import { globMatcher } from "../glob.mjs";
12
+ import { fileSafe } from "./edit-batch-state.mjs";
13
+ import { readLedger } from "./ledger.mjs";
14
+ import { keyOf, worktrees } from "./worktree.mjs";
15
+ import { worktreeRuleAt } from "./worktree-settings.mjs";
16
+
17
+ const GIT_TIMEOUT_MS = 20_000;
18
+
19
+ function git(cwd, ...args) {
20
+ const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, timeout: GIT_TIMEOUT_MS });
21
+ return { ok: result.status === 0, out: (result.stdout ?? "").trim() };
22
+ }
23
+
24
+ /** The settled merges of this session, one per head branch, less each head that is long-lived by config. */
25
+ function mergesOf(records, session, config) {
26
+ const longLived = globMatcher([...(config.swarm?.isolation?.protectedBranches ?? []), ...(config.branches?.allow ?? [])]);
27
+ const byBranch = new Map();
28
+ for (const record of records) {
29
+ if (record.type !== "merge" || record.session !== session || record.pending || record.closed) continue;
30
+ if (typeof record.branch === "string" && record.branch !== "" && !longLived(record.branch)) byBranch.set(record.branch, record);
31
+ }
32
+ return [...byBranch.values()];
33
+ }
34
+
35
+ /** The commands that remove what a merged head leaves, or none when nothing is left. */
36
+ function cleanupOf(merge, { main, folder }) {
37
+ const { branch } = merge;
38
+ const tree = worktrees(main).find((entry) => entry.branch === branch);
39
+ const local = git(main, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).ok;
40
+ const remote = git(main, "ls-remote", "--heads", "origin", `refs/heads/${branch}`);
41
+ const steps = [];
42
+ if (tree && keyOf(tree.path) === keyOf(main)) steps.push(`\`git switch ${merge.base ?? "main"}\``, `\`git branch -D ${branch}\``);
43
+ else if (tree && [folder, path.dirname(main)].some((parent) => keyOf(path.dirname(tree.path)) === keyOf(parent))) {
44
+ // `remove` deletes the local branch, and the remote one at the head of a merged PR.
45
+ return [`\`npx qc worktree remove ${path.basename(tree.path)}\``];
46
+ } else if (tree) steps.push(`\`git worktree remove ${tree.path}\``, `\`git branch -D ${branch}\``);
47
+ else if (local) steps.push(`\`git branch -D ${branch}\``);
48
+ if (remote.ok && remote.out !== "") steps.push(`\`git push origin --delete ${branch}\``);
49
+ return steps;
50
+ }
51
+
52
+ const memoryOf = (tmp, session) => path.join(tmp, "qc-worktree-gate", `${fileSafe(session)}.last`);
53
+ const hashOf = (text) => createHash("sha256").update(text).digest("hex");
54
+
55
+ function lastBlock(file) {
56
+ try {
57
+ return readFileSync(file, "utf8");
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ /** The verdict on one Stop. @returns the hook output, or null to let the turn end with no message. */
64
+ export function decide(call, { tmp = os.tmpdir(), projectDir = process.env.CLAUDE_PROJECT_DIR } = {}) {
65
+ if (call.hook_event_name !== "Stop") return null;
66
+ const rule = worktreeRuleAt(call.cwd ?? process.cwd()) ?? (projectDir ? worktreeRuleAt(projectDir) : null);
67
+ if (!rule) return null;
68
+ const session = call.session_id ?? "session";
69
+ let records;
70
+ try {
71
+ records = readLedger(rule.ledger);
72
+ } catch {
73
+ return null;
74
+ }
75
+ const lines = mergesOf(records, session, rule.config)
76
+ .map((merge) => ({ merge, steps: cleanupOf(merge, rule) }))
77
+ .filter(({ steps }) => steps.length > 0)
78
+ .map(({ merge, steps }) => `- ${merge.repo}#${merge.pr} (${merge.branch}): ${steps.join(", then ")}`);
79
+ const memory = memoryOf(tmp, session);
80
+ if (lines.length === 0) {
81
+ rmSync(memory, { force: true });
82
+ return null;
83
+ }
84
+ const reason = [
85
+ `Worktree check: a PR this session merged leaves its worktree or its branch. From the main checkout (${rule.main}), run:`,
86
+ ...lines,
87
+ ].join("\n");
88
+ // A repeat stop with the same leftovers ends with a note, so a removal the agent cannot run never loops.
89
+ const note = { systemMessage: `Worktree check: the same leftovers as at the last block remain. Remove them by hand: ${lines[0].slice(2)}` };
90
+ if (call.stop_hook_active === true && lastBlock(memory) === hashOf(reason)) return note;
91
+ try {
92
+ mkdirSync(path.dirname(memory), { recursive: true });
93
+ writeFileSync(memory, hashOf(reason));
94
+ } catch {
95
+ // With no memory, a repeat stop cannot tell a change, so it ends with the note.
96
+ if (call.stop_hook_active === true) return note;
97
+ }
98
+ return { decision: "block", reason };
99
+ }
100
+
101
+ async function readStdin() {
102
+ let data = "";
103
+ for await (const chunk of process.stdin) data += chunk;
104
+ return data;
105
+ }
106
+
107
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
108
+ if (isEntryPoint) {
109
+ let call = null;
110
+ try {
111
+ call = JSON.parse(await readStdin());
112
+ } catch {
113
+ // Not hook input, so there is no merge to follow up.
114
+ }
115
+ const output = call ? decide(call) : null;
116
+ if (output) process.stdout.write(JSON.stringify(output));
117
+ }
@@ -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"],
@@ -492,21 +493,20 @@ export const dispatchDefaults = {
492
493
  implementerSlots: 1,
493
494
  // The model families each type's named `model` may carry. `"*"` covers every other type.
494
495
  models: {
495
- "sdd-planner": ["opus"],
496
- "architecture:sdd-planner": ["opus"],
497
- "sdd-branch-reviewer": ["opus"],
498
- "architecture:sdd-branch-reviewer": ["opus"],
499
- "sdd-implementer": ["sonnet"],
500
- "architecture:sdd-implementer": ["sonnet"],
501
- "sdd-reviewer": ["sonnet"],
502
- "architecture:sdd-reviewer": ["sonnet"],
503
- "*": ["sonnet", "haiku"],
496
+ "sdd-planner": ["gpt-6.1-sol"],
497
+ "architecture:sdd-planner": ["gpt-6.1-sol"],
498
+ "sdd-branch-reviewer": ["gpt-6.1-sol"],
499
+ "architecture:sdd-branch-reviewer": ["gpt-6.1-sol"],
500
+ "sdd-implementer": ["gpt-6.1-sol"],
501
+ "architecture:sdd-implementer": ["gpt-6.1-sol"],
502
+ "sdd-reviewer": ["gpt-6.1-sol"],
503
+ "architecture:sdd-reviewer": ["gpt-6.1-sol"],
504
+ "*": ["gpt-6.1-sol"],
504
505
  },
505
506
  };
506
507
 
507
- // The model families the guard knows. A model string's family is the first of these it
508
- // contains, lower-cased, so a new release under an existing family needs no kit change.
509
- export const MODEL_FAMILIES = ["opus", "sonnet", "haiku", "fable"];
508
+ // GPT uses an exact model id; Claude families remain available for repository overrides.
509
+ export const MODEL_FAMILIES = ["gpt-6.1-sol", "opus", "sonnet", "haiku", "fable"];
510
510
 
511
511
  // What each key of `swarm.explore` means when a repository omits it. The kit names no tool; a
512
512
  // repository lists its own index, call graph or summarizer in `tools` and `summarizer`.
@@ -602,6 +602,12 @@ export function readerEntries(registry) {
602
602
  .map(([key, entry]) => ({ key, names: entry.names ?? [], readers: entry.readers ?? [] }));
603
603
  }
604
604
 
605
+ /** `ignores` and the worktree folder, so a repository's own list of ignores still skips each worktree. */
606
+ export function ignoresOf(config) {
607
+ const dir = config.worktree?.dir;
608
+ return dir ? [...config.ignores, `${dir.replace(/\/+$/, "")}/**`] : config.ignores;
609
+ }
610
+
605
611
  export function enabled(map, id) {
606
612
  return map[id] !== false;
607
613
  }