rungate 0.3.0 → 0.4.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 (49) hide show
  1. package/lib/ac-quality.ts +119 -0
  2. package/lib/brief-precedence.ts +114 -0
  3. package/lib/ci-checkout.ts +27 -1
  4. package/lib/compliance-backfill.ts +16 -4
  5. package/lib/compliance-report.ts +109 -8
  6. package/lib/config-loader.ts +129 -5
  7. package/lib/config-readers.ts +86 -0
  8. package/lib/conformity.ts +520 -27
  9. package/lib/context-docs.ts +182 -0
  10. package/lib/create-brief.ts +22 -17
  11. package/lib/create-sc.ts +55 -33
  12. package/lib/decomposition-waves.ts +197 -0
  13. package/lib/doc-scan-targets.ts +435 -0
  14. package/lib/gate-check-audit.ts +190 -0
  15. package/lib/generators/agents-md.ts +10 -5
  16. package/lib/issue-extraction.ts +368 -0
  17. package/lib/organize.ts +129 -40
  18. package/lib/package-closure.ts +111 -0
  19. package/lib/phase2-decomposition.ts +270 -0
  20. package/lib/prior-branch.ts +24 -1
  21. package/lib/project-aliases.ts +100 -0
  22. package/lib/prove-label-gate.ts +93 -0
  23. package/lib/release-preflight.ts +225 -15
  24. package/lib/rungate-schema.ts +36 -2
  25. package/lib/sc-cover.ts +92 -1
  26. package/lib/sc-ids.ts +151 -0
  27. package/lib/scaffold/pre-push-hook.ts +165 -0
  28. package/lib/scaffold/rehearsal.ts +330 -0
  29. package/lib/scaffold/steps.ts +175 -122
  30. package/lib/scaffold/write-steps.ts +167 -0
  31. package/lib/scope-denylist.ts +258 -0
  32. package/lib/scratch-cleanup.ts +198 -0
  33. package/lib/scratch-roots.ts +94 -0
  34. package/lib/task-completion-checks.ts +50 -3
  35. package/lib/typescript-project.ts +233 -0
  36. package/lib/validators/spec-validators.ts +23 -34
  37. package/lib/verified-push.ts +179 -2
  38. package/lib/workflow-security.ts +51 -7
  39. package/lib/worktree-cleanup.ts +318 -20
  40. package/lib/worktree-repo.ts +465 -0
  41. package/package.json +8 -2
  42. package/scripts/audit-specs.ts +134 -37
  43. package/scripts/audit-transcript.ts +259 -0
  44. package/scripts/create-sc.ts +15 -1
  45. package/scripts/detect-sc-drift.ts +200 -0
  46. package/scripts/extract-constraints.ts +16 -36
  47. package/scripts/scaffold-project.ts +26 -136
  48. package/scripts/split-spec.ts +315 -0
  49. package/scripts/sync-sc-status.ts +751 -0
@@ -9,19 +9,59 @@
9
9
  * GitHub issue #564
10
10
  */
11
11
 
12
- import { readdirSync, statSync, existsSync } from "fs";
13
- import { join } from "path";
12
+ import { readdirSync, realpathSync, statSync, existsSync, readFileSync, rmSync } from "fs";
13
+ import { join, isAbsolute } from "path";
14
14
  import { spawnSync } from "child_process";
15
15
 
16
16
  export interface CleanupResult {
17
17
  removed: string[];
18
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
+ /**
29
+ * Checkouts git has no registration for (#436).
30
+ *
31
+ * A directory whose `.git` file names an admin directory that does not
32
+ * exist. `git worktree remove` cannot touch it — git does not know it is a
33
+ * worktree — so every pass pushed it to `errors` and moved on. That was the
34
+ * conservative behaviour and it was also permanent: an error that recurs on
35
+ * every SessionStart and can never be resolved is indistinguishable from a
36
+ * log line, which is how a 6.2 MB leftover sat in the report for weeks.
37
+ *
38
+ * Its own bucket, so "git could not answer" stays distinct from "there is
39
+ * nothing to ask git about".
40
+ */
41
+ orphaned: string[];
19
42
  errors: string[];
20
43
  }
21
44
 
22
45
  export interface CleanupOptions {
23
46
  projectRoot: string;
24
47
  maxAgeMs?: number;
48
+ /**
49
+ * Delete orphaned checkouts rather than only reporting them (#436 SC-5).
50
+ *
51
+ * **Default off, and that is the decision rather than an oversight.** This
52
+ * function's governing asymmetry, already written into the merge check two
53
+ * hundred lines below, is that treating "not merged" as unsafe costs disk
54
+ * and treating "merged" as safe can delete work. An orphan is the case
55
+ * where the question cannot be asked at all: the admin directory is gone,
56
+ * so `git status` cannot run, and nothing can establish whether the
57
+ * checkout holds work that exists nowhere else.
58
+ *
59
+ * Removing it would therefore be a recursive delete of content this
60
+ * function has explicitly failed to classify, run unprompted at
61
+ * SessionStart. So the automatic pass reports; an operator who has looked
62
+ * passes `removeOrphans: true`. `hooks/StaleTTLCleanup.hook.ts` does not.
63
+ */
64
+ removeOrphans?: boolean;
25
65
  }
26
66
 
27
67
  /**
@@ -72,6 +112,204 @@ export function unpushedKeepReason(
72
112
  return null;
73
113
  }
74
114
 
115
+ /** What `origin` knows about a branch. `unpushedCommitCount` collapses two of these. */
116
+ export type OriginState =
117
+ /** The repo has no `origin`, so "pushed" is not a question that applies. */
118
+ | { kind: "no-origin" }
119
+ /** A git invocation failed. Not a verdict. */
120
+ | { kind: "unknown" }
121
+ /** Commits exist here and nowhere else. */
122
+ | { kind: "ahead"; count: number }
123
+ /** Every commit on the branch is also on an `origin/*` ref. */
124
+ | { kind: "on-origin" };
125
+
126
+ export function originState(projectRoot: string, branch: string): OriginState {
127
+ const remotes = spawnSync("git", ["remote"], { cwd: projectRoot, encoding: "utf-8", timeout: 5000 });
128
+ if (remotes.status !== 0) return { kind: "unknown" };
129
+ if (!remotes.stdout.split("\n").map(r => r.trim()).includes("origin")) return { kind: "no-origin" };
130
+
131
+ const count = spawnSync("git", ["rev-list", "--count", branch, "--not", "--remotes=origin"], {
132
+ cwd: projectRoot, encoding: "utf-8", timeout: 10_000,
133
+ });
134
+ if (count.status !== 0) return { kind: "unknown" };
135
+ const n = parseInt(count.stdout.trim(), 10);
136
+ if (!Number.isFinite(n)) return { kind: "unknown" };
137
+ return n > 0 ? { kind: "ahead", count: n } : { kind: "on-origin" };
138
+ }
139
+
140
+ /**
141
+ * Why a clean, unlocked worktree must be kept, or null to remove it (#431).
142
+ *
143
+ * ## Why "unmerged" stopped being a reason on its own
144
+ *
145
+ * 149 worktrees had accumulated here, 71 of them clean and unmerged, the
146
+ * oldest 13.7 days old, and the cleanup removed none of them for weeks. The
147
+ * rule was "never remove an unmerged branch", which reads as prudence and is
148
+ * actually the wrong question: **`git worktree remove` deletes a checkout,
149
+ * not a branch.** The ref survives, its commits survive, and `git checkout`
150
+ * brings it all back. Nothing is lost.
151
+ *
152
+ * What CAN be lost is work that exists in exactly one place: uncommitted
153
+ * changes — checked before this is called — and commits that never reached
154
+ * origin. So the real safety property is "is every commit on this branch
155
+ * also somewhere else", and asking it directly both protects more (an
156
+ * unpushed branch merged into a local-only main was removable before) and
157
+ * permits more (an unmerged fan-out branch fully pushed is just a stale
158
+ * directory).
159
+ *
160
+ * `merged` is still load-bearing in exactly one case: a repo with no
161
+ * `origin` at all, where "also somewhere else" has no meaning and the only
162
+ * remaining evidence is that main contains the work. Without that arm this
163
+ * change would delete unmerged local-only work, which is the regression that
164
+ * gets a safety check reverted — and `unpushedCommitCount` returns `0` for a
165
+ * remote-less repo, so it would have looked exactly like a pushed branch.
166
+ *
167
+ * One exported binding, so there is one thing to mutate.
168
+ */
169
+ export function removalKeepReason(
170
+ entry: string,
171
+ branch: string,
172
+ merged: boolean,
173
+ origin: OriginState,
174
+ ): string | null {
175
+ switch (origin.kind) {
176
+ case "unknown":
177
+ return `${entry} (could not tell whether ${branch} is on origin)`;
178
+ case "ahead":
179
+ return `${entry} (${origin.count} commit(s) on ${branch} not on origin)`;
180
+ case "no-origin":
181
+ return merged ? null : `${entry} (no origin remote, and ${branch} is not merged into main)`;
182
+ case "on-origin":
183
+ // Merged or not. The branch ref is not touched by `worktree remove`.
184
+ return null;
185
+ }
186
+ }
187
+
188
+ /**
189
+ * The worktree paths git reports as locked, or `null` if it could not say.
190
+ *
191
+ * `null` is not an empty set. An unreadable listing means every claim is
192
+ * invisible, and the caller keeps everything rather than treating silence as
193
+ * permission — the same rule `unpushedCommitCount` follows for `null`.
194
+ */
195
+ export function lockedWorktreePaths(projectRoot: string): Set<string> | null {
196
+ const list = spawnSync("git", ["worktree", "list", "--porcelain"], {
197
+ cwd: projectRoot, encoding: "utf-8", timeout: 15_000,
198
+ });
199
+ if (list.status !== 0) return null;
200
+
201
+ const paths = new Set<string>();
202
+ let current: string | null = null;
203
+ for (const line of list.stdout.split("\n")) {
204
+ if (line.startsWith("worktree ")) current = line.slice("worktree ".length).trim();
205
+ else if (line.startsWith("locked") && current) paths.add(realPath(current));
206
+ }
207
+ return paths;
208
+ }
209
+
210
+ /**
211
+ * Why a worktree must be kept on the strength of locks alone, or null (#431).
212
+ *
213
+ * One exported binding for the same reason `unpushedKeepReason` is one: the
214
+ * `null` arm — git could not list the worktrees, so every claim is
215
+ * invisible — needs git to fail, which no fixture can stage. Inline, all
216
+ * three lock mutations scored ZERO red, including reverting the realpath
217
+ * comparison that makes the check work at all on macOS. Driven directly,
218
+ * each arm is a case.
219
+ *
220
+ * `null` keeps everything. An empty set means "nothing is claimed" and
221
+ * would licence removing all of it, so the two must not collapse.
222
+ */
223
+ export function lockKeepReason(
224
+ entry: string,
225
+ worktreePath: string,
226
+ locked: ReadonlySet<string> | null,
227
+ ): string | null {
228
+ if (locked === null) return `${entry} (could not read which worktrees are locked)`;
229
+ // Resolved on BOTH sides. git reports worktree paths with symlinks
230
+ // resolved; the caller builds this one with `join`. On macOS the temp
231
+ // directory is under a `/var` → `/private/var` symlink, so a raw
232
+ // comparison never matches and the check is inert on the platform it was
233
+ // written on.
234
+ return locked.has(realPath(worktreePath)) ? `${entry} (locked)` : null;
235
+ }
236
+
237
+ /**
238
+ * A path with symlinks resolved, or the path itself if it cannot be read.
239
+ *
240
+ * git reports worktree paths resolved. On macOS the system temp directory —
241
+ * and therefore every fixture in the suite — lives under `/var`, which is a
242
+ * symlink to `/private/var`, so a set built from git's output and probed
243
+ * with a `join()`ed path never matches. The lock check would have been
244
+ * silently inert on the platform it was written on: a guard that cannot see
245
+ * what it guards, which is the defect class this file keeps meeting.
246
+ *
247
+ * Falling back to the raw path on failure is deliberate. A miss here means
248
+ * a lock is not seen, so it must not ALSO swallow the error silently — the
249
+ * caller keeps anything it cannot classify, and an unreadable path fails
250
+ * the `existsSync`/`statSync` above long before this matters.
251
+ */
252
+ function realPath(p: string): string {
253
+ try {
254
+ return realpathSync(p);
255
+ } catch {
256
+ return p;
257
+ }
258
+ }
259
+
260
+ /**
261
+ * The admin directory a checkout's `.git` file names, when that directory is
262
+ * gone — otherwise `null` (#436).
263
+ *
264
+ * A linked worktree's `.git` is a FILE reading `gitdir: <path>`. When
265
+ * `git worktree prune` removes the registration but leaves the checkout, that
266
+ * path stops existing and every git command run inside the directory fails
267
+ * with "not a git repository". Nothing else produces that state, which is why
268
+ * the test is the gitdir rather than the status failure: a status that fails
269
+ * for any OTHER reason is still an error, because something unexplained
270
+ * happened and this function has no business deleting anything over it.
271
+ *
272
+ * Three things are deliberately NOT orphans:
273
+ *
274
+ * - no `.git` at all — it was never a worktree, and whatever it is, it is
275
+ * not this function's to delete;
276
+ * - a `.git` DIRECTORY — that is a whole repository someone put here, not a
277
+ * linked checkout;
278
+ * - a gitdir that exists — the registration is intact and the ordinary
279
+ * path applies.
280
+ *
281
+ * One exported binding, so there is one thing to mutate.
282
+ */
283
+ export function orphanedGitdir(worktreePath: string): string | null {
284
+ const dotGit = join(worktreePath, ".git");
285
+
286
+ // ONE decider for "is there a readable `.git` FILE here", and it is this
287
+ // read. The first draft asked the same question twice more — a `statSync`
288
+ // whose catch meant "no .git", and an `isFile()` meaning "a real
289
+ // repository" — and the mutation battery is what showed they were the same
290
+ // question: dropping `isFile()` measured 0 of 47 red, because a directory
291
+ // makes this read throw EISDIR and a missing path makes it throw ENOENT,
292
+ // so the read already returned null for both. Two of the three could be
293
+ // deleted and no test could tell. See
294
+ // `.claude/rules/checks-must-be-able-to-fail.md`, fourth shape.
295
+ //
296
+ // The direction the catch fails in is the safe one: null means "not an
297
+ // orphan", and the only thing downstream does with an orphan is offer to
298
+ // delete it.
299
+ let contents: string;
300
+ try {
301
+ contents = readFileSync(dotGit, "utf-8");
302
+ } catch {
303
+ return null; // absent, a directory, or unreadable — none of them is an orphan
304
+ }
305
+
306
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(contents);
307
+ if (!m) return null; // not the shape git writes; do not guess
308
+ const gitdir = m[1]!;
309
+ const resolved = isAbsolute(gitdir) ? gitdir : join(worktreePath, gitdir);
310
+ return existsSync(resolved) ? null : resolved;
311
+ }
312
+
75
313
  /**
76
314
  * Clean up stale git worktrees from .claude/worktrees/.
77
315
  *
@@ -83,9 +321,23 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
83
321
  const result: CleanupResult = {
84
322
  removed: [],
85
323
  kept: [],
324
+ skipped: [],
325
+ orphaned: [],
86
326
  errors: [],
87
327
  };
88
328
 
329
+ // `git worktree lock` is the one durable claim a running job can make on a
330
+ // worktree, and it is git's own — `worktree remove` refuses a locked tree
331
+ // regardless of what this function decides (#431). Read once, up front,
332
+ // because the per-entry alternative is 149 subprocesses.
333
+ //
334
+ // Read from the porcelain listing rather than by probing for the admin
335
+ // file: a lock recorded in a form this function does not recognise would
336
+ // look unlocked, and "I did not see a claim" must not be how a claim gets
337
+ // ignored. A listing that cannot be read leaves the set null, and a null
338
+ // set keeps everything.
339
+ const locked = lockedWorktreePaths(projectRoot);
340
+
89
341
  const worktreesDir = join(projectRoot, ".claude", "worktrees");
90
342
 
91
343
  // Early exit if directory doesn't exist
@@ -109,13 +361,18 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
109
361
  // Skip if not a directory
110
362
  try {
111
363
  const stat = statSync(worktreePath);
112
- if (!stat.isDirectory()) continue;
364
+ if (!stat.isDirectory()) {
365
+ result.skipped.push(`${entry} (not a directory)`);
366
+ continue;
367
+ }
113
368
 
114
369
  // Check age filter if provided
115
370
  if (maxAgeMs !== undefined) {
116
371
  const ageMs = now - stat.mtimeMs;
117
372
  if (ageMs < maxAgeMs) {
118
- // Too new, skip
373
+ // Too new to judge. Recorded, because an entry counted in neither
374
+ // bucket is how the printed totals stopped adding up (#431).
375
+ result.skipped.push(`${entry} (younger than the age filter)`);
119
376
  continue;
120
377
  }
121
378
  }
@@ -124,6 +381,44 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
124
381
  continue;
125
382
  }
126
383
 
384
+ // A locked worktree is a claim by something still using it. git refuses
385
+ // to remove one anyway; recording it as KEPT rather than letting the
386
+ // removal fail into `errors` keeps "something owns this" distinct from
387
+ // "the removal broke" (#431).
388
+ const lockReason = lockKeepReason(entry, worktreePath, locked);
389
+ if (lockReason) {
390
+ result.kept.push(lockReason);
391
+ continue;
392
+ }
393
+
394
+ // #436: git has no registration for this checkout, so every command run
395
+ // inside it fails and `git worktree remove` cannot touch it. Asked BEFORE
396
+ // the status call, because the status call is the thing that fails — and
397
+ // classifying on the failure rather than on the cause would also swallow
398
+ // every other reason git might refuse.
399
+ //
400
+ // The path deleted is the one THIS function built, two lines up, from
401
+ // `join(worktreesDir, entry)`. Not the gitdir read out of the `.git`
402
+ // file, which is attacker-controlled in the sense that matters: it is
403
+ // content, and content must never steer a recursive delete.
404
+ const missingGitdir = orphanedGitdir(worktreePath);
405
+ if (missingGitdir !== null) {
406
+ if (!opts.removeOrphans) {
407
+ result.orphaned.push(
408
+ `${entry} (git has no registration — ${missingGitdir} is gone; ` +
409
+ `nothing can read whether this checkout holds unique work, so it is reported rather than deleted)`,
410
+ );
411
+ continue;
412
+ }
413
+ try {
414
+ rmSync(worktreePath, { recursive: true, force: true });
415
+ result.orphaned.push(`${entry} (removed — git had no registration)`);
416
+ } catch (err) {
417
+ result.errors.push(`Failed to remove orphaned ${entry}: ${err}`);
418
+ }
419
+ continue;
420
+ }
421
+
127
422
  // Check for uncommitted changes
128
423
  const statusCheck = spawnSync("git", ["status", "--porcelain"], {
129
424
  cwd: worktreePath,
@@ -197,21 +492,14 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
197
492
  continue;
198
493
  }
199
494
 
200
- if (mergeCheck.status !== 0) {
201
- // Branch not merged — keep it
202
- result.kept.push(`${entry} (unmerged branch: ${branchName})`);
203
- continue;
204
- }
205
-
206
- // Merged into LOCAL main is not the same as safe to delete (#232).
207
- //
208
- // A branch merged into a main that was never pushed exists in exactly one
209
- // place on earth, and this function runs unattended from a SessionStart
210
- // hook. #228 and #232 are both about work that was correct and became
211
- // unreachable; removing a worktree whose commits are not on origin is the
212
- // same loss with a tidier name.
213
- const keepReason = unpushedKeepReason(
214
- entry, branchName, unpushedCommitCount(projectRoot, branchName),
495
+ // Merged into LOCAL main is not the same as safe to delete (#232), and
496
+ // UNmerged is not the same as unsafe to delete (#431). Both questions go
497
+ // to one decider, because they were two `if`s in a row and the first one
498
+ // short-circuited the second — the unmerged arm returned before the
499
+ // origin check ever ran, so the weaker proxy was deciding everything and
500
+ // the stronger property was dead code for every branch that needed it.
501
+ const keepReason = removalKeepReason(
502
+ entry, branchName, mergeCheck.status === 0, originState(projectRoot, branchName),
215
503
  );
216
504
  if (keepReason) {
217
505
  result.kept.push(keepReason);
@@ -244,7 +532,17 @@ export async function cleanupWorktrees(opts: CleanupOptions): Promise<CleanupRes
244
532
  }
245
533
 
246
534
  // Log summary
247
- console.log(`Worktree cleanup: ${result.removed.length} removed, ${result.kept.length} kept`);
535
+ // All FIVE buckets. `removed + kept + skipped + orphaned + errors` is the
536
+ // number of entries examined, which is the property
537
+ // test/worktree-cleanup-orphans asserts — a summary that cannot be
538
+ // reconciled against the directory is how 149 worktrees hid behind
539
+ // "144 kept" (#431). #436 added `orphaned` and this line in the same
540
+ // change, because a bucket missing from the total is that defect again.
541
+ console.log(
542
+ `Worktree cleanup: ${result.removed.length} removed, ${result.kept.length} kept, ` +
543
+ `${result.skipped.length} skipped, ${result.orphaned.length} orphaned, ` +
544
+ `${result.errors.length} error(s)`,
545
+ );
248
546
 
249
547
  return result;
250
548
  }