rungate 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/brief-precedence.ts +114 -0
  11. package/lib/canary.ts +117 -0
  12. package/lib/check-registry.ts +226 -0
  13. package/lib/ci-checkout.ts +426 -0
  14. package/lib/cli-commands.ts +137 -0
  15. package/lib/compliance-backfill.ts +232 -0
  16. package/lib/compliance-report.ts +605 -0
  17. package/lib/compliance.ts +361 -0
  18. package/lib/config-loader.ts +255 -0
  19. package/lib/config-readers.ts +86 -0
  20. package/lib/conformity.ts +2161 -137
  21. package/lib/container-provenance.ts +230 -0
  22. package/lib/create-brief.ts +150 -0
  23. package/lib/create-sc.ts +267 -0
  24. package/lib/decomposition-waves.ts +197 -0
  25. package/lib/deep-merge.ts +69 -0
  26. package/lib/dev-liveness.ts +214 -0
  27. package/lib/directive-extractor.ts +210 -0
  28. package/lib/distribution-standing.ts +113 -0
  29. package/lib/doc-hygiene.ts +238 -0
  30. package/lib/eval-criteria.ts +6 -0
  31. package/lib/evidence-portability.ts +123 -0
  32. package/lib/evidence-prevalidator.ts +390 -0
  33. package/lib/evidence-required.ts +150 -0
  34. package/lib/evidence-satisfiability.ts +288 -0
  35. package/lib/frontmatter.ts +163 -0
  36. package/lib/gap-scanner.ts +348 -0
  37. package/lib/gate-check-audit.ts +190 -0
  38. package/lib/gate-enforcement.ts +366 -0
  39. package/lib/generators/agent-briefs.ts +136 -0
  40. package/lib/generators/agents-md.ts +511 -0
  41. package/lib/generators/code-map.ts +60 -0
  42. package/lib/generators/types.ts +184 -0
  43. package/lib/git-ref-normalizer.ts +107 -0
  44. package/lib/github.ts +539 -0
  45. package/lib/harness-identity.ts +63 -0
  46. package/lib/hill-climb.ts +164 -0
  47. package/lib/instruction-effectiveness.ts +131 -0
  48. package/lib/issue-closure-audit.ts +225 -0
  49. package/lib/issue-create-override.ts +343 -0
  50. package/lib/issue-extraction.ts +368 -0
  51. package/lib/js-top-level-code.ts +250 -0
  52. package/lib/liveness-contradiction.ts +149 -0
  53. package/lib/organize.ts +505 -0
  54. package/lib/paths.ts +197 -6
  55. package/lib/phase2-decomposition.ts +270 -0
  56. package/lib/post-fix-verify.ts +157 -0
  57. package/lib/prior-branch.ts +512 -0
  58. package/lib/project-state-shape.ts +166 -0
  59. package/lib/promote-outputs.ts +156 -0
  60. package/lib/prove-label-gate.ts +128 -0
  61. package/lib/reachability.ts +302 -0
  62. package/lib/release-preflight.ts +288 -0
  63. package/lib/rule-health-pipeline.ts +264 -0
  64. package/lib/rule-health-trend.ts +161 -0
  65. package/lib/rule-provenance.ts +149 -0
  66. package/lib/rule-registry.ts +128 -0
  67. package/lib/rungate-schema.ts +127 -5
  68. package/lib/sc-claim-forms.ts +179 -0
  69. package/lib/sc-cover.ts +150 -0
  70. package/lib/sc-guard.ts +157 -0
  71. package/lib/sc-ids.ts +344 -0
  72. package/lib/scaffold/defaults.ts +165 -0
  73. package/lib/scaffold/managed-workflow.ts +370 -0
  74. package/lib/scaffold/owned-files.ts +265 -0
  75. package/lib/scaffold/pre-push-hook.ts +165 -0
  76. package/lib/scaffold/steps.ts +2621 -0
  77. package/lib/scanner.ts +701 -0
  78. package/lib/scope-denylist.ts +258 -0
  79. package/lib/screenshot-upload.ts +73 -0
  80. package/lib/secret-patterns.ts +112 -0
  81. package/lib/security-verdict.ts +616 -0
  82. package/lib/signal-phrases.ts +1 -0
  83. package/lib/spec-change-conformity.ts +80 -0
  84. package/lib/spec-files.ts +62 -0
  85. package/lib/spec-registry.ts +133 -0
  86. package/lib/spec-updater.ts +96 -0
  87. package/lib/stale-cleanup.ts +224 -0
  88. package/lib/stale-issue-scanner.ts +36 -0
  89. package/lib/strip-js-comments.ts +269 -0
  90. package/lib/suite-measurement.ts +228 -0
  91. package/lib/task-completion-checks.ts +224 -0
  92. package/lib/test-suite-lock.ts +1136 -0
  93. package/lib/transcript-checker.ts +1140 -0
  94. package/lib/typescript-project.ts +233 -0
  95. package/lib/validators/spec-validators.ts +171 -0
  96. package/lib/verdict-capture.ts +73 -0
  97. package/lib/verified-push.ts +535 -0
  98. package/lib/workflow-security.ts +174 -0
  99. package/lib/worktree-cleanup.ts +432 -0
  100. package/lib/worktree-collect.ts +283 -0
  101. package/lib/worktree-isolation.ts +82 -0
  102. package/lib/worktree-repo.ts +300 -0
  103. package/package.json +27 -3
  104. package/prompts/ac-adversary.md +14 -2
  105. package/prompts/aditi.md +5 -0
  106. package/prompts/blast-radius.md +5 -0
  107. package/prompts/container-verify.md +5 -0
  108. package/prompts/discovery.md +4 -0
  109. package/prompts/environment.md +5 -0
  110. package/prompts/evidence-hierarchy.md +5 -0
  111. package/prompts/evidence-validator.md +11 -0
  112. package/prompts/marcus.md +5 -0
  113. package/prompts/prevention.md +5 -0
  114. package/prompts/prove-reproducer.md +12 -0
  115. package/prompts/quinn-decision-tree.md +5 -0
  116. package/prompts/quinn-ui-brief.md +5 -0
  117. package/prompts/quinn.md +5 -0
  118. package/prompts/rca.md +5 -0
  119. package/prompts/read-before-write.md +4 -0
  120. package/prompts/regression.md +5 -0
  121. package/prompts/serena.md +5 -0
  122. package/scripts/audit-specs.ts +464 -0
  123. package/scripts/convert-spec.ts +293 -0
  124. package/scripts/create-sc.ts +92 -0
  125. package/scripts/create-spec.ts +166 -0
  126. package/scripts/extract-constraints.ts +4 -3
  127. package/scripts/generate-code-map.ts +1 -1
  128. package/scripts/scaffold-project.ts +138 -1426
  129. package/scripts/sync-spec-tests.ts +211 -126
@@ -0,0 +1,174 @@
1
+ import { createHash, timingSafeEqual } from "crypto";
2
+
3
+ const SHELL_METACHARACTERS = /[;&|$`\n\r"'\\(){}[\]<>!~*?#]/;
4
+ const PATH_TRAVERSAL = /\.\.($|[/\\])/;
5
+ const NULL_BYTE = /\x00/;
6
+
7
+ export function buildSafeGitAdd(filesChanged: string[]): string {
8
+ const validated = validateFilePaths(filesChanged);
9
+ if (validated.rejected.length > 0) {
10
+ throw new Error(
11
+ `Rejected unsafe file paths: ${validated.rejected.join(", ")}`,
12
+ );
13
+ }
14
+ if (validated.valid.length === 0) throw new Error("No valid files to stage");
15
+ return `git add ${validated.valid.map((f) => `'${f.replace(/'/g, "'\\''")}'`).join(" ")}`;
16
+ }
17
+
18
+ export function validateFilePaths(
19
+ paths: string[],
20
+ ): { valid: string[]; rejected: string[] } {
21
+ const valid: string[] = [];
22
+ const rejected: string[] = [];
23
+ for (const p of paths) {
24
+ if (
25
+ SHELL_METACHARACTERS.test(p) ||
26
+ PATH_TRAVERSAL.test(p) ||
27
+ NULL_BYTE.test(p) ||
28
+ p.startsWith("/") ||
29
+ p.length > 500
30
+ ) {
31
+ rejected.push(p);
32
+ } else {
33
+ valid.push(p);
34
+ }
35
+ }
36
+ return { valid, rejected };
37
+ }
38
+
39
+ /**
40
+ * Whether a string is safe to interpolate into a git or `gh` command as a
41
+ * branch name.
42
+ *
43
+ * #136 made branch names flow from the run into commands: the PR head is now
44
+ * `${shipBranch}` rather than something a checkout is asked for at the time.
45
+ * That is the right direction — an agent recovering from a failed push chose
46
+ * `HEAD:main` once — but the value still reaches a shell, and it originates
47
+ * from an agent's reply or from a PR listing, neither of which this process
48
+ * wrote.
49
+ *
50
+ * Git's own rules are looser than this (`git check-ref-format`). The extra
51
+ * strictness is deliberate: every character git allows but this rejects is
52
+ * one that means something to a shell, and no branch this harness creates
53
+ * needs any of them.
54
+ */
55
+ const SAFE_BRANCH = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
56
+
57
+ export function isSafeBranchName(name: unknown): name is string {
58
+ if (typeof name !== "string" || name.length === 0 || name.length > 255) return false;
59
+ if (!SAFE_BRANCH.test(name)) return false;
60
+ // Git's own refusals, and the ones that matter here: `..` would let a
61
+ // branch argument climb out of a refspec, and a leading `-` would be read
62
+ // as a flag by git and by gh alike.
63
+ if (name.includes("..") || name.includes("//") || name.endsWith("/") || name.endsWith(".lock")) return false;
64
+ return true;
65
+ }
66
+
67
+ export function resolveEvidencePath(
68
+ basePath: string,
69
+ evidencePath: string,
70
+ ): string {
71
+ if (NULL_BYTE.test(evidencePath)) {
72
+ throw new Error(`Evidence path contains null byte: ${evidencePath}`);
73
+ }
74
+ if (PATH_TRAVERSAL.test(evidencePath)) {
75
+ throw new Error(`Evidence path contains traversal: ${evidencePath}`);
76
+ }
77
+ if (evidencePath.startsWith("/")) {
78
+ throw new Error(`Evidence path is absolute: ${evidencePath}`);
79
+ }
80
+ const resolved = `${basePath}/${evidencePath}`;
81
+ if (!resolved.startsWith(basePath)) {
82
+ throw new Error(`Evidence path escapes base: ${resolved}`);
83
+ }
84
+ return resolved;
85
+ }
86
+
87
+ export function validateEvidenceCommand(command: string): {
88
+ safe: boolean;
89
+ reason?: string;
90
+ } {
91
+ if (NULL_BYTE.test(command)) {
92
+ return { safe: false, reason: "Command contains null byte" };
93
+ }
94
+ const dangerous = [
95
+ /rm\s+-rf/,
96
+ />\s*\/dev/,
97
+ /mkfs/,
98
+ /dd\s+if=/,
99
+ /chmod\s+777/,
100
+ /curl.*\|\s*(bash|sh)/,
101
+ ];
102
+ for (const pattern of dangerous) {
103
+ if (pattern.test(command)) {
104
+ return { safe: false, reason: `Dangerous pattern: ${pattern.source}` };
105
+ }
106
+ }
107
+ // Heuristic denylist — blocks known-dangerous patterns but not a security gate
108
+ // for arbitrary command execution. Evidence commands are controlled by Discovery,
109
+ // not external input, so denylist is defense-in-depth, not the primary control.
110
+ return { safe: true };
111
+ }
112
+
113
+ export function buildSafeSSHCommand(
114
+ host: string,
115
+ command: string,
116
+ ): string[] {
117
+ if (SHELL_METACHARACTERS.test(host)) {
118
+ throw new Error(`SSH host contains shell metacharacters: ${host}`);
119
+ }
120
+ if (host.startsWith("-")) {
121
+ throw new Error(`SSH host starts with dash (option injection): ${host}`);
122
+ }
123
+ return [
124
+ "ssh",
125
+ "-o",
126
+ "ConnectTimeout=5",
127
+ "-o",
128
+ "StrictHostKeyChecking=no",
129
+ "--",
130
+ host,
131
+ command,
132
+ ];
133
+ }
134
+
135
+ interface ACForHash {
136
+ id: string;
137
+ type: string;
138
+ statement: string;
139
+ specElement?: string;
140
+ threshold?: { op: string; value: unknown };
141
+ evidenceMethod?: { type: string; command?: string };
142
+ }
143
+
144
+ export function computeACHash(
145
+ acs: ACForHash[],
146
+ excludeFields: (keyof ACForHash)[] = [],
147
+ ): string {
148
+ const normalized = acs
149
+ .map((ac) => {
150
+ const filtered: Record<string, unknown> = {};
151
+ for (const [key, value] of Object.entries(ac)) {
152
+ if (!excludeFields.includes(key as keyof ACForHash)) {
153
+ filtered[key] = value;
154
+ }
155
+ }
156
+ return filtered;
157
+ })
158
+ .sort((a, b) =>
159
+ JSON.stringify(a).localeCompare(JSON.stringify(b)),
160
+ );
161
+ return createHash("sha256").update(JSON.stringify(normalized)).digest("hex");
162
+ }
163
+
164
+ export function verifyACHash(
165
+ acs: ACForHash[],
166
+ expectedHash: string,
167
+ excludeFields: (keyof ACForHash)[] = [],
168
+ ): boolean {
169
+ const computed = computeACHash(acs, excludeFields);
170
+ const computedBuf = Buffer.from(computed, "utf-8");
171
+ const expectedBuf = Buffer.from(expectedHash, "utf-8");
172
+ if (computedBuf.length !== expectedBuf.length) return false;
173
+ return timingSafeEqual(computedBuf, expectedBuf);
174
+ }
@@ -0,0 +1,432 @@
1
+ /**
2
+ * Worktree cleanup — removes stale git worktrees from .claude/worktrees/
3
+ *
4
+ * Safety-first design:
5
+ * - NEVER removes worktrees with uncommitted changes
6
+ * - NEVER removes worktrees with unmerged branches
7
+ * - Optionally filters by age (maxAgeMs)
8
+ *
9
+ * GitHub issue #564
10
+ */
11
+
12
+ import { readdirSync, realpathSync, statSync, existsSync } from "fs";
13
+ import { join } from "path";
14
+ import { spawnSync } from "child_process";
15
+
16
+ export interface CleanupResult {
17
+ removed: string[];
18
+ kept: string[];
19
+ /**
20
+ * Entries the run never judged — too new, or not a directory (#431).
21
+ *
22
+ * These used to `continue` without being recorded anywhere, so
23
+ * `removed + kept` did not add up to the number of entries and the printed
24
+ * line said "144 kept" against 149 worktrees. A bucket that exists only as
25
+ * the gap between two other numbers is a bucket nobody reconciles.
26
+ */
27
+ skipped: string[];
28
+ errors: string[];
29
+ }
30
+
31
+ export interface CleanupOptions {
32
+ projectRoot: string;
33
+ maxAgeMs?: number;
34
+ }
35
+
36
+ /**
37
+ * How many commits on `branch` no `origin/*` ref contains (#232).
38
+ *
39
+ * `0` is the claim "every commit here is also on origin". `null` is the
40
+ * absence of a claim and the caller keeps the worktree — "I could not tell"
41
+ * is not grounds for `git worktree remove --force`.
42
+ *
43
+ * A repo with no `origin` remote returns `0` rather than the branch's whole
44
+ * length. There is nowhere for the work to have been pushed TO, so the
45
+ * question does not apply, and answering it literally would stop cleanup
46
+ * dead in every local-only checkout — which is the regression that gets a
47
+ * safety check reverted.
48
+ */
49
+ export function unpushedCommitCount(projectRoot: string, branch: string): number | null {
50
+ const remotes = spawnSync("git", ["remote"], {
51
+ cwd: projectRoot, encoding: "utf-8", timeout: 5000,
52
+ });
53
+ if (remotes.status !== 0) return null;
54
+ if (!remotes.stdout.split("\n").map(r => r.trim()).includes("origin")) return 0;
55
+
56
+ const count = spawnSync("git", ["rev-list", "--count", branch, "--not", "--remotes=origin"], {
57
+ cwd: projectRoot, encoding: "utf-8", timeout: 10_000,
58
+ });
59
+ if (count.status !== 0) return null;
60
+ const n = parseInt(count.stdout.trim(), 10);
61
+ return Number.isFinite(n) ? n : null;
62
+ }
63
+
64
+ /**
65
+ * Why this worktree must be kept, given what the origin check answered, or
66
+ * null to go ahead and remove it (#232).
67
+ *
68
+ * One exported binding rather than two branches inline, because the `null`
69
+ * arm is the one no fixture can reach: it needs git to fail between the
70
+ * branch read and the rev-list, which is real — a branch deleted in that
71
+ * window — and not something a test can stage. Inline, removing that arm
72
+ * scored ZERO red; here it is driven directly.
73
+ */
74
+ export function unpushedKeepReason(
75
+ entry: string,
76
+ branch: string,
77
+ unpushed: number | null,
78
+ ): string | null {
79
+ if (unpushed === null) return `${entry} (could not tell whether ${branch} is on origin)`;
80
+ if (unpushed > 0) return `${entry} (${unpushed} commit(s) on ${branch} not on origin)`;
81
+ return null;
82
+ }
83
+
84
+ /** What `origin` knows about a branch. `unpushedCommitCount` collapses two of these. */
85
+ export type OriginState =
86
+ /** The repo has no `origin`, so "pushed" is not a question that applies. */
87
+ | { kind: "no-origin" }
88
+ /** A git invocation failed. Not a verdict. */
89
+ | { kind: "unknown" }
90
+ /** Commits exist here and nowhere else. */
91
+ | { kind: "ahead"; count: number }
92
+ /** Every commit on the branch is also on an `origin/*` ref. */
93
+ | { kind: "on-origin" };
94
+
95
+ export function originState(projectRoot: string, branch: string): OriginState {
96
+ const remotes = spawnSync("git", ["remote"], { cwd: projectRoot, encoding: "utf-8", timeout: 5000 });
97
+ if (remotes.status !== 0) return { kind: "unknown" };
98
+ if (!remotes.stdout.split("\n").map(r => r.trim()).includes("origin")) return { kind: "no-origin" };
99
+
100
+ const count = spawnSync("git", ["rev-list", "--count", branch, "--not", "--remotes=origin"], {
101
+ cwd: projectRoot, encoding: "utf-8", timeout: 10_000,
102
+ });
103
+ if (count.status !== 0) return { kind: "unknown" };
104
+ const n = parseInt(count.stdout.trim(), 10);
105
+ if (!Number.isFinite(n)) return { kind: "unknown" };
106
+ return n > 0 ? { kind: "ahead", count: n } : { kind: "on-origin" };
107
+ }
108
+
109
+ /**
110
+ * Why a clean, unlocked worktree must be kept, or null to remove it (#431).
111
+ *
112
+ * ## Why "unmerged" stopped being a reason on its own
113
+ *
114
+ * 149 worktrees had accumulated here, 71 of them clean and unmerged, the
115
+ * oldest 13.7 days old, and the cleanup removed none of them for weeks. The
116
+ * rule was "never remove an unmerged branch", which reads as prudence and is
117
+ * actually the wrong question: **`git worktree remove` deletes a checkout,
118
+ * not a branch.** The ref survives, its commits survive, and `git checkout`
119
+ * brings it all back. Nothing is lost.
120
+ *
121
+ * What CAN be lost is work that exists in exactly one place: uncommitted
122
+ * changes — checked before this is called — and commits that never reached
123
+ * origin. So the real safety property is "is every commit on this branch
124
+ * also somewhere else", and asking it directly both protects more (an
125
+ * unpushed branch merged into a local-only main was removable before) and
126
+ * permits more (an unmerged fan-out branch fully pushed is just a stale
127
+ * directory).
128
+ *
129
+ * `merged` is still load-bearing in exactly one case: a repo with no
130
+ * `origin` at all, where "also somewhere else" has no meaning and the only
131
+ * remaining evidence is that main contains the work. Without that arm this
132
+ * change would delete unmerged local-only work, which is the regression that
133
+ * gets a safety check reverted — and `unpushedCommitCount` returns `0` for a
134
+ * remote-less repo, so it would have looked exactly like a pushed branch.
135
+ *
136
+ * One exported binding, so there is one thing to mutate.
137
+ */
138
+ export function removalKeepReason(
139
+ entry: string,
140
+ branch: string,
141
+ merged: boolean,
142
+ origin: OriginState,
143
+ ): string | null {
144
+ switch (origin.kind) {
145
+ case "unknown":
146
+ return `${entry} (could not tell whether ${branch} is on origin)`;
147
+ case "ahead":
148
+ return `${entry} (${origin.count} commit(s) on ${branch} not on origin)`;
149
+ case "no-origin":
150
+ return merged ? null : `${entry} (no origin remote, and ${branch} is not merged into main)`;
151
+ case "on-origin":
152
+ // Merged or not. The branch ref is not touched by `worktree remove`.
153
+ return null;
154
+ }
155
+ }
156
+
157
+ /**
158
+ * The worktree paths git reports as locked, or `null` if it could not say.
159
+ *
160
+ * `null` is not an empty set. An unreadable listing means every claim is
161
+ * invisible, and the caller keeps everything rather than treating silence as
162
+ * permission — the same rule `unpushedCommitCount` follows for `null`.
163
+ */
164
+ export function lockedWorktreePaths(projectRoot: string): Set<string> | null {
165
+ const list = spawnSync("git", ["worktree", "list", "--porcelain"], {
166
+ cwd: projectRoot, encoding: "utf-8", timeout: 15_000,
167
+ });
168
+ if (list.status !== 0) return null;
169
+
170
+ const paths = new Set<string>();
171
+ let current: string | null = null;
172
+ for (const line of list.stdout.split("\n")) {
173
+ if (line.startsWith("worktree ")) current = line.slice("worktree ".length).trim();
174
+ else if (line.startsWith("locked") && current) paths.add(realPath(current));
175
+ }
176
+ return paths;
177
+ }
178
+
179
+ /**
180
+ * Why a worktree must be kept on the strength of locks alone, or null (#431).
181
+ *
182
+ * One exported binding for the same reason `unpushedKeepReason` is one: the
183
+ * `null` arm — git could not list the worktrees, so every claim is
184
+ * invisible — needs git to fail, which no fixture can stage. Inline, all
185
+ * three lock mutations scored ZERO red, including reverting the realpath
186
+ * comparison that makes the check work at all on macOS. Driven directly,
187
+ * each arm is a case.
188
+ *
189
+ * `null` keeps everything. An empty set means "nothing is claimed" and
190
+ * would licence removing all of it, so the two must not collapse.
191
+ */
192
+ export function lockKeepReason(
193
+ entry: string,
194
+ worktreePath: string,
195
+ locked: ReadonlySet<string> | null,
196
+ ): string | null {
197
+ if (locked === null) return `${entry} (could not read which worktrees are locked)`;
198
+ // Resolved on BOTH sides. git reports worktree paths with symlinks
199
+ // resolved; the caller builds this one with `join`. On macOS the temp
200
+ // directory is under a `/var` → `/private/var` symlink, so a raw
201
+ // comparison never matches and the check is inert on the platform it was
202
+ // written on.
203
+ return locked.has(realPath(worktreePath)) ? `${entry} (locked)` : null;
204
+ }
205
+
206
+ /**
207
+ * A path with symlinks resolved, or the path itself if it cannot be read.
208
+ *
209
+ * git reports worktree paths resolved. On macOS the system temp directory —
210
+ * and therefore every fixture in the suite — lives under `/var`, which is a
211
+ * symlink to `/private/var`, so a set built from git's output and probed
212
+ * with a `join()`ed path never matches. The lock check would have been
213
+ * silently inert on the platform it was written on: a guard that cannot see
214
+ * what it guards, which is the defect class this file keeps meeting.
215
+ *
216
+ * Falling back to the raw path on failure is deliberate. A miss here means
217
+ * a lock is not seen, so it must not ALSO swallow the error silently — the
218
+ * caller keeps anything it cannot classify, and an unreadable path fails
219
+ * the `existsSync`/`statSync` above long before this matters.
220
+ */
221
+ function realPath(p: string): string {
222
+ try {
223
+ return realpathSync(p);
224
+ } catch {
225
+ return p;
226
+ }
227
+ }
228
+
229
+ /**
230
+ * Clean up stale git worktrees from .claude/worktrees/.
231
+ *
232
+ * @param opts - Cleanup options with projectRoot and optional maxAgeMs filter
233
+ * @returns CleanupResult with removed, kept, and errors arrays
234
+ */
235
+ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupResult> {
236
+ const { projectRoot, maxAgeMs } = opts;
237
+ const result: CleanupResult = {
238
+ removed: [],
239
+ kept: [],
240
+ skipped: [],
241
+ errors: [],
242
+ };
243
+
244
+ // `git worktree lock` is the one durable claim a running job can make on a
245
+ // worktree, and it is git's own — `worktree remove` refuses a locked tree
246
+ // regardless of what this function decides (#431). Read once, up front,
247
+ // because the per-entry alternative is 149 subprocesses.
248
+ //
249
+ // Read from the porcelain listing rather than by probing for the admin
250
+ // file: a lock recorded in a form this function does not recognise would
251
+ // look unlocked, and "I did not see a claim" must not be how a claim gets
252
+ // ignored. A listing that cannot be read leaves the set null, and a null
253
+ // set keeps everything.
254
+ const locked = lockedWorktreePaths(projectRoot);
255
+
256
+ const worktreesDir = join(projectRoot, ".claude", "worktrees");
257
+
258
+ // Early exit if directory doesn't exist
259
+ if (!existsSync(worktreesDir)) {
260
+ return result;
261
+ }
262
+
263
+ let entries: string[];
264
+ try {
265
+ entries = readdirSync(worktreesDir);
266
+ } catch (err) {
267
+ result.errors.push(`Failed to read worktrees directory: ${err}`);
268
+ return result;
269
+ }
270
+
271
+ const now = Date.now();
272
+
273
+ for (const entry of entries) {
274
+ const worktreePath = join(worktreesDir, entry);
275
+
276
+ // Skip if not a directory
277
+ try {
278
+ const stat = statSync(worktreePath);
279
+ if (!stat.isDirectory()) {
280
+ result.skipped.push(`${entry} (not a directory)`);
281
+ continue;
282
+ }
283
+
284
+ // Check age filter if provided
285
+ if (maxAgeMs !== undefined) {
286
+ const ageMs = now - stat.mtimeMs;
287
+ if (ageMs < maxAgeMs) {
288
+ // Too new to judge. Recorded, because an entry counted in neither
289
+ // bucket is how the printed totals stopped adding up (#431).
290
+ result.skipped.push(`${entry} (younger than the age filter)`);
291
+ continue;
292
+ }
293
+ }
294
+ } catch (err) {
295
+ result.errors.push(`Failed to stat ${entry}: ${err}`);
296
+ continue;
297
+ }
298
+
299
+ // A locked worktree is a claim by something still using it. git refuses
300
+ // to remove one anyway; recording it as KEPT rather than letting the
301
+ // removal fail into `errors` keeps "something owns this" distinct from
302
+ // "the removal broke" (#431).
303
+ const lockReason = lockKeepReason(entry, worktreePath, locked);
304
+ if (lockReason) {
305
+ result.kept.push(lockReason);
306
+ continue;
307
+ }
308
+
309
+ // Check for uncommitted changes
310
+ const statusCheck = spawnSync("git", ["status", "--porcelain"], {
311
+ cwd: worktreePath,
312
+ encoding: "utf-8",
313
+ timeout: 5000,
314
+ });
315
+
316
+ if (statusCheck.status !== 0) {
317
+ result.errors.push(`Failed to check git status for ${entry}: ${statusCheck.stderr}`);
318
+ continue;
319
+ }
320
+
321
+ if (statusCheck.stdout.trim() !== "") {
322
+ // Has uncommitted changes — keep it
323
+ result.kept.push(`${entry} (uncommitted changes)`);
324
+ continue;
325
+ }
326
+
327
+ // Get branch name
328
+ const branchCheck = spawnSync("git", ["-C", worktreePath, "branch", "--show-current"], {
329
+ cwd: projectRoot,
330
+ encoding: "utf-8",
331
+ timeout: 5000,
332
+ });
333
+
334
+ if (branchCheck.status !== 0) {
335
+ result.errors.push(`Failed to get branch name for ${entry}: ${branchCheck.stderr}`);
336
+ continue;
337
+ }
338
+
339
+ const branchName = branchCheck.stdout.trim();
340
+ if (!branchName) {
341
+ // Detached HEAD or no branch — keep it
342
+ result.kept.push(`${entry} (detached HEAD)`);
343
+ continue;
344
+ }
345
+
346
+ // Is the branch merged into main? (#68)
347
+ //
348
+ // This used to parse `git branch --merged main` display output, stripping
349
+ // a leading `*`. Git also prefixes `+ ` on any branch checked out in a
350
+ // LINKED WORKTREE — which is, by definition, every branch this function
351
+ // evaluates. So entries came out as "+ 24-doc-hygiene-infra", never
352
+ // matched the bare name, every candidate was classified unmerged, and the
353
+ // function removed nothing for its entire existence. 36 worktrees and
354
+ // 243 MB accumulated behind it.
355
+ //
356
+ // Ask git the question directly instead. `--is-ancestor` is a predicate
357
+ // with an exit status, so there is no display output to parse and no
358
+ // decoration to strip — the whole class of prefix bug goes away rather
359
+ // than this one instance of it.
360
+ //
361
+ // Argument order is load-bearing and inverting it is catastrophic: this
362
+ // asks whether BRANCH is an ancestor of main. Reversed, every branch cut
363
+ // from main would look merged and cleanup would delete unmerged work.
364
+ // test/unit/worktree-cleanup-merge.test.ts pins both directions.
365
+ const mergeCheck = spawnSync("git", ["merge-base", "--is-ancestor", branchName, "main"], {
366
+ cwd: projectRoot,
367
+ encoding: "utf-8",
368
+ timeout: 5000,
369
+ });
370
+
371
+ // Exit 0 = merged, 1 = not merged. Anything else (128: bad revision, no
372
+ // `main`, not a repo) is an error, NOT a verdict — treating it as "not
373
+ // merged" would be safe here, but treating it as merged would delete work,
374
+ // and silently swallowing it is how the original bug stayed invisible.
375
+ if (mergeCheck.status !== 0 && mergeCheck.status !== 1) {
376
+ result.errors.push(
377
+ `Failed to check merge status for ${entry}: git exited ${mergeCheck.status}: ${mergeCheck.stderr.trim()}`,
378
+ );
379
+ continue;
380
+ }
381
+
382
+ // Merged into LOCAL main is not the same as safe to delete (#232), and
383
+ // UNmerged is not the same as unsafe to delete (#431). Both questions go
384
+ // to one decider, because they were two `if`s in a row and the first one
385
+ // short-circuited the second — the unmerged arm returned before the
386
+ // origin check ever ran, so the weaker proxy was deciding everything and
387
+ // the stronger property was dead code for every branch that needed it.
388
+ const keepReason = removalKeepReason(
389
+ entry, branchName, mergeCheck.status === 0, originState(projectRoot, branchName),
390
+ );
391
+ if (keepReason) {
392
+ result.kept.push(keepReason);
393
+ continue;
394
+ }
395
+
396
+ // All safety checks passed — remove the worktree
397
+ const removeResult = spawnSync("git", ["worktree", "remove", "--force", worktreePath], {
398
+ cwd: projectRoot,
399
+ encoding: "utf-8",
400
+ timeout: 15000,
401
+ });
402
+
403
+ if (removeResult.status !== 0) {
404
+ result.errors.push(`Failed to remove ${entry}: ${removeResult.stderr}`);
405
+ } else {
406
+ result.removed.push(entry);
407
+ }
408
+ }
409
+
410
+ // Prune worktree references
411
+ const pruneResult = spawnSync("git", ["worktree", "prune"], {
412
+ cwd: projectRoot,
413
+ encoding: "utf-8",
414
+ timeout: 5000,
415
+ });
416
+
417
+ if (pruneResult.status !== 0) {
418
+ result.errors.push(`Failed to prune worktree references: ${pruneResult.stderr}`);
419
+ }
420
+
421
+ // Log summary
422
+ // All four buckets. `removed + kept + skipped + errors` is the number of
423
+ // entries examined, which is the property test/worktree-cleanup-orphans
424
+ // asserts — a summary that cannot be reconciled against the directory is
425
+ // how 149 worktrees hid behind "144 kept" (#431).
426
+ console.log(
427
+ `Worktree cleanup: ${result.removed.length} removed, ${result.kept.length} kept, ` +
428
+ `${result.skipped.length} skipped, ${result.errors.length} error(s)`,
429
+ );
430
+
431
+ return result;
432
+ }