rungate 0.8.13 → 0.8.16

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 (88) hide show
  1. package/README.md +182 -0
  2. package/gates/.gate-salt +1 -1
  3. package/hooks/HarnessAFKGate.hook.ts +5 -1
  4. package/hooks/HookCurrency.hook.ts +11 -8
  5. package/hooks/MergeGuard.hook.ts +7 -1
  6. package/hooks/StaleTTLCleanup.hook.ts +4 -4
  7. package/hooks/VerifyPhaseLock.hook.ts +3 -3
  8. package/hooks/lib/findWorkflow.ts +3 -2
  9. package/hooks/lib/paths.ts +14 -2
  10. package/hooks/lib/utils.ts +23 -3
  11. package/lib/active-milestone.ts +50 -0
  12. package/lib/ai-review-rounds.ts +99 -0
  13. package/lib/ai-review-suppression.ts +200 -21
  14. package/lib/bash-write-guard.ts +397 -23
  15. package/lib/board-flow.ts +280 -0
  16. package/lib/board-lane-health.ts +578 -0
  17. package/lib/board-mirror.ts +136 -39
  18. package/lib/board-ready-fanout.ts +297 -14
  19. package/lib/board-ready-rule.ts +1211 -0
  20. package/lib/board-throughput.ts +136 -0
  21. package/lib/board-walkthrough.ts +240 -0
  22. package/lib/body-evidence.ts +203 -0
  23. package/lib/branch-protection.ts +399 -9
  24. package/lib/bun-version.ts +36 -0
  25. package/lib/cli-commands.ts +75 -4
  26. package/lib/closing-reference-audit.ts +307 -6
  27. package/lib/config-loader.ts +254 -25
  28. package/lib/config-readers.ts +170 -10
  29. package/lib/config-trackable.ts +96 -57
  30. package/lib/conformity.ts +121 -7
  31. package/lib/create-sc.ts +25 -2
  32. package/lib/derived-spec.ts +21 -9
  33. package/lib/filing-compliance.ts +367 -0
  34. package/lib/filing-plan.ts +47 -21
  35. package/lib/finding-arbiter.ts +79 -5
  36. package/lib/finding-jury.ts +43 -4
  37. package/lib/finding-promotion.ts +1123 -0
  38. package/lib/generators/agents-md.ts +149 -0
  39. package/lib/git-isolation.ts +137 -1
  40. package/lib/github-api-base.ts +66 -0
  41. package/lib/github.ts +194 -9
  42. package/lib/graphql-cursor.ts +80 -0
  43. package/lib/hook-scopes.ts +78 -0
  44. package/lib/issue-create-override.ts +415 -3
  45. package/lib/issue-decomposition.ts +124 -7
  46. package/lib/issue-extraction.ts +9 -7
  47. package/lib/issue-file-overlap.ts +373 -0
  48. package/lib/issue-filing-gate.ts +1109 -52
  49. package/lib/issue-repair.ts +90 -9
  50. package/lib/issue-shape.ts +199 -0
  51. package/lib/live-issues.ts +31 -2
  52. package/lib/local-work.ts +423 -0
  53. package/lib/markdown-fence.ts +134 -0
  54. package/lib/milestone-title.ts +46 -0
  55. package/lib/scaffold/ai-review-findings.ts +148 -3
  56. package/lib/scaffold/ai-review-step.ts +65 -5
  57. package/lib/scaffold/ai-review-unmeasured-workflow.ts +3 -0
  58. package/lib/scaffold/steps.ts +115 -9
  59. package/lib/source-census.ts +108 -0
  60. package/lib/spec-deps.ts +55 -11
  61. package/lib/spec-placement.ts +203 -13
  62. package/lib/spec-registry.ts +75 -16
  63. package/lib/spec-source.ts +609 -0
  64. package/lib/spec-write-sweep.ts +4 -0
  65. package/lib/stage-ladder.ts +896 -3
  66. package/lib/state-claim-readings.ts +252 -0
  67. package/lib/success-doc.ts +7 -6
  68. package/lib/test-command-positions.ts +135 -1
  69. package/lib/work-status.ts +551 -0
  70. package/lib/worktree-repo.ts +14 -2
  71. package/package.json +7 -1
  72. package/scripts/ai-review-findings.ts +8 -13
  73. package/scripts/ai-review-threads.ts +16 -17
  74. package/scripts/audit-closing-references.ts +330 -0
  75. package/scripts/audit-specs.ts +59 -103
  76. package/scripts/board-conformance.ts +747 -40
  77. package/scripts/board-mirror.ts +594 -13
  78. package/scripts/board-ready.ts +979 -0
  79. package/scripts/board-snapshot.ts +464 -12
  80. package/scripts/claim-files.ts +578 -0
  81. package/scripts/criterion-inventory.ts +526 -50
  82. package/scripts/finding-promotion.ts +547 -0
  83. package/scripts/generate-code-map.ts +1 -1
  84. package/scripts/plan-issues.ts +279 -40
  85. package/scripts/plan-spec.ts +105 -3
  86. package/scripts/sync-sc-status.ts +147 -7
  87. package/scripts/worktree-census.ts +958 -0
  88. package/scripts/worktree-sweep.ts +269 -0
@@ -0,0 +1,269 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Remove the worktrees the census reads ABANDONED, wherever they live (#2022).
4
+ *
5
+ * `cleanupWorktrees` in `lib/worktree-cleanup.ts` reads one directory,
6
+ * `<repo>/.claude/worktrees/`. Session worktrees here are cut as siblings of
7
+ * the main checkout (`~/Projects/rg-wt-*`), so none of them was ever examined
8
+ * and 36 accumulated. And `hooks/StaleTTLCleanup.hook.ts` skipped everything
9
+ * when the session started outside a repository, which is where sessions here
10
+ * usually start.
11
+ *
12
+ * ## What this decides: nothing
13
+ *
14
+ * `scripts/worktree-census.ts` is the reading and `verdictFor` is its one
15
+ * decider — merged pull request at the exact commit held, a clean status that
16
+ * was actually read, no process holding a file, nothing modified inside the
17
+ * declared age, and anything unreadable is UNMEASURED rather than ABANDONED.
18
+ * This file takes that verdict and acts on the ABANDONED rows only. It asks
19
+ * no question of its own, so there is no second decider for a mutation of the
20
+ * first to hide behind; `test/worktree-sweep.test.ts` asserts the verdict is
21
+ * read in exactly one place.
22
+ *
23
+ * ## What it must never do
24
+ *
25
+ * - **No `--force`.** `git worktree remove` without it refuses a tree with
26
+ * modified or untracked files, so a worktree that turned dirty between the
27
+ * census and the removal is refused by git itself, not by a check of ours.
28
+ * - **No `prune`.** It drops the registration of every worktree whose
29
+ * directory is gone, not only ours (`.claude/rules/parallel-sessions.md`).
30
+ * - **No recursive delete.** git removes the directory or nothing does.
31
+ *
32
+ * Usage:
33
+ * bun scripts/worktree-sweep.ts [--under <dir>] [--older-than 7d]
34
+ *
35
+ * `--under` is the launch directory: the repository it is inside, or, when it
36
+ * is inside none, each primary checkout directly under it that has a linked
37
+ * worktree. stdout carries one line per repository that had something to
38
+ * report; the session-start hook appends it to the stale-cleanup log.
39
+ */
40
+
41
+ import { execFileSync, spawn } from "child_process";
42
+ import { closeSync, existsSync, lstatSync, openSync, readdirSync } from "fs";
43
+ import { dirname, join } from "path";
44
+ import { gitIsolatedArgs, gitIsolatedEnv } from "../lib/git-isolation";
45
+ import {
46
+ census,
47
+ couldNotRead,
48
+ parseDuration,
49
+ parseWorktreeList,
50
+ readLsof,
51
+ readPullRequests,
52
+ readWorktreeList,
53
+ type CensusResult,
54
+ type Measured,
55
+ type PullRequest,
56
+ } from "./worktree-census";
57
+
58
+ /** The one place this script runs `git`, isolated the way the census is. */
59
+ function sweepGit(args: readonly string[]): string {
60
+ return execFileSync("git", gitIsolatedArgs(args), {
61
+ encoding: "utf-8",
62
+ stdio: ["pipe", "pipe", "pipe"],
63
+ env: gitIsolatedEnv(),
64
+ }).trim();
65
+ }
66
+
67
+ /** A worktree the census read ABANDONED, and the commit it held when it was read. */
68
+ export interface Target {
69
+ path: string;
70
+ head: string | null;
71
+ }
72
+
73
+ /** The rows the census read ABANDONED. The verdict is read here and nowhere else. */
74
+ export function sweepTargets(result: CensusResult): Target[] {
75
+ return result.rows
76
+ .filter(row => row.verdict === "ABANDONED")
77
+ .map(row => ({ path: row.path, head: row.head }));
78
+ }
79
+
80
+ export interface RemoveOutcome {
81
+ removed: string[];
82
+ refused: Array<{ path: string; why: string }>;
83
+ }
84
+
85
+ /**
86
+ * `git worktree remove` for each target, never forced, so git's own refusal
87
+ * stands for a tree that turned dirty after the census.
88
+ *
89
+ * A tree that gained a COMMIT is clean again, so git has nothing to refuse,
90
+ * and that commit is on no other ref (review round 1 of #2023). So the head is
91
+ * read again first and must still be the one the census matched against the
92
+ * merged pull request. This is not a second verdict: it asks only whether the
93
+ * reading still describes the tree, and an unreadable head is a refusal.
94
+ */
95
+ export function removeWorktrees(repo: string, targets: readonly Target[]): RemoveOutcome {
96
+ const out: RemoveOutcome = { removed: [], refused: [] };
97
+ for (const { path, head } of targets) {
98
+ let now = "";
99
+ try {
100
+ now = sweepGit(["-C", path, "rev-parse", "HEAD"]);
101
+ } catch {
102
+ out.refused.push({ path, why: "HEAD could not be read again before removal" });
103
+ continue;
104
+ }
105
+ if (!head || now !== head) {
106
+ out.refused.push({ path, why: `HEAD moved since the census (${head ?? "none"} -> ${now})` });
107
+ continue;
108
+ }
109
+ try {
110
+ sweepGit(["-C", repo, "worktree", "remove", path]);
111
+ out.removed.push(path);
112
+ } catch (e) {
113
+ const why = String((e as { stderr?: string }).stderr || (e as Error).message || "")
114
+ .split("\n").filter(Boolean)[0] ?? "git refused";
115
+ out.refused.push({ path, why });
116
+ }
117
+ }
118
+ return out;
119
+ }
120
+
121
+ export interface SweepOptions {
122
+ olderThanMs: number;
123
+ nowMs: number;
124
+ maxEntries: number;
125
+ pulls: Measured<PullRequest[]>;
126
+ lsof: Measured<string>;
127
+ }
128
+
129
+ export function sweepRepo(repo: string, opts: SweepOptions): { census: CensusResult; outcome: RemoveOutcome } {
130
+ const records = parseWorktreeList(readWorktreeList(repo));
131
+ const result = census(records, { repo, ...opts });
132
+ return { census: result, outcome: removeWorktrees(repo, sweepTargets(result)) };
133
+ }
134
+
135
+ /** The main checkout of the repository `dir` is inside, or null when it is inside none. */
136
+ function mainCheckoutOf(dir: string): string | null {
137
+ try {
138
+ const common = sweepGit(["-C", dir, "rev-parse", "--path-format=absolute", "--git-common-dir"]);
139
+ return common ? dirname(common) : null;
140
+ } catch {
141
+ return null;
142
+ }
143
+ }
144
+
145
+ function hasLinkedWorktree(repo: string): boolean {
146
+ try {
147
+ return parseWorktreeList(readWorktreeList(repo)).length > 1;
148
+ } catch {
149
+ return false;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Which repositories a launch directory sweeps.
155
+ *
156
+ * Inside a repository: its main checkout, reached from a linked worktree too.
157
+ * Outside any: each child whose `.git` is a DIRECTORY — a primary checkout,
158
+ * not a linked worktree, whose `.git` is a file. Either way only a repository
159
+ * with a linked worktree is returned, so one with nothing to sweep costs no
160
+ * `gh` call at SessionStart.
161
+ */
162
+ export function reposToSweep(launchDir: string): string[] {
163
+ const inside = mainCheckoutOf(launchDir);
164
+ if (inside) return hasLinkedWorktree(inside) ? [inside] : [];
165
+ let children: string[];
166
+ try {
167
+ children = readdirSync(launchDir);
168
+ } catch {
169
+ return [];
170
+ }
171
+ const repos: string[] = [];
172
+ for (const name of children.sort()) {
173
+ const dir = join(launchDir, name);
174
+ const dotGit = join(dir, ".git");
175
+ try {
176
+ if (!existsSync(dotGit) || !lstatSync(dotGit).isDirectory()) continue;
177
+ } catch {
178
+ continue;
179
+ }
180
+ if (hasLinkedWorktree(dir)) repos.push(dir);
181
+ }
182
+ return repos;
183
+ }
184
+
185
+ /** `owner/name` from a GitHub remote URL, or null for anything else. */
186
+ export function originSlug(url: string): string | null {
187
+ const m = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(url.trim());
188
+ return m ? `${m[1]}/${m[2]}` : null;
189
+ }
190
+
191
+ function pullsFor(repo: string): Measured<PullRequest[]> {
192
+ let url = "";
193
+ try {
194
+ url = sweepGit(["-C", repo, "remote", "get-url", "origin"]);
195
+ } catch {
196
+ return couldNotRead<PullRequest[]>("no origin remote, so no pull request can be asked about");
197
+ }
198
+ const slug = originSlug(url);
199
+ if (!slug) return couldNotRead<PullRequest[]>(`origin ${url} is not a GitHub remote`);
200
+ return readPullRequests(slug);
201
+ }
202
+
203
+ /**
204
+ * Start a sweep in the background and return at once.
205
+ *
206
+ * Detached so SessionStart never waits on `gh` and `lsof`; its output is
207
+ * appended to `logPath`, the stale-cleanup log the hook already writes.
208
+ *
209
+ * The launch directory is read HERE, not passed by the hook:
210
+ * `test/unit/worktree-cleanup-merge.test.ts` holds the hook to one
211
+ * `process.cwd()`, the one that seeds `repoRootFrom` (#68).
212
+ */
213
+ export function spawnSweep(logPath: string, launchDir: string = process.cwd()): void {
214
+ const fd = openSync(logPath, "a");
215
+ try {
216
+ spawn(process.execPath, [import.meta.path, "--under", launchDir], {
217
+ cwd: launchDir,
218
+ detached: true,
219
+ stdio: ["ignore", fd, fd],
220
+ }).unref();
221
+ } finally {
222
+ closeSync(fd);
223
+ }
224
+ }
225
+
226
+ export function main(argv: string[]): number {
227
+ let under = process.cwd();
228
+ // The census's own default. An unattended delete is no place for a tighter
229
+ // threshold than the report a human reads (review round 1 of #2023).
230
+ let olderThanMs = parseDuration("7d");
231
+ for (let i = 0; i < argv.length; i++) {
232
+ if (argv[i] === "--under" && argv[i + 1]) under = argv[++i];
233
+ else if (argv[i] === "--older-than" && argv[i + 1]) olderThanMs = parseDuration(argv[++i]);
234
+ else throw new Error(`unknown argument: ${argv[i]}`);
235
+ }
236
+ const lsof = readLsof();
237
+ const stamp = new Date().toISOString();
238
+ let removed = 0;
239
+ for (const repo of reposToSweep(under)) {
240
+ try {
241
+ const { census: c, outcome } = sweepRepo(repo, {
242
+ olderThanMs, nowMs: Date.now(), maxEntries: 20000, pulls: pullsFor(repo), lsof,
243
+ });
244
+ removed += outcome.removed.length;
245
+ const unmeasured = c.counts.unmeasured;
246
+ if (outcome.removed.length || outcome.refused.length || unmeasured) {
247
+ process.stdout.write(
248
+ `${stamp} WORKTREE sweep [${repo}]: removed ${outcome.removed.length}` +
249
+ (outcome.removed.length ? ` (${outcome.removed.join(", ")})` : "") +
250
+ `, refused ${outcome.refused.length}` +
251
+ outcome.refused.map(r => ` [${r.path}: ${r.why}]`).join("") +
252
+ `, ${unmeasured} UNMEASURED of ${c.counts.total}\n`,
253
+ );
254
+ }
255
+ } catch (e) {
256
+ process.stdout.write(`${stamp} WORKTREE sweep [${repo}] error: ${String((e as Error).message).split("\n")[0]}\n`);
257
+ }
258
+ }
259
+ return removed;
260
+ }
261
+
262
+ if (import.meta.main) {
263
+ try {
264
+ main(process.argv.slice(2));
265
+ } catch (e) {
266
+ process.stderr.write(`worktree-sweep: ${(e as Error).message}\n`);
267
+ process.exitCode = 2;
268
+ }
269
+ }