crysk 0.0.0 → 0.3.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 (233) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +611 -3
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/SKILL-y8rv8msh.md +134 -0
  10. package/dist/SKILL-ygka1bs0.md +515 -0
  11. package/dist/adjudicator-dtg2axnh.md +86 -0
  12. package/dist/admission-config.example-a9vqmmad.json +9 -0
  13. package/dist/ci-admission-camfbx2b.md +122 -0
  14. package/dist/ci-admission-qk9r9taq.md +124 -0
  15. package/dist/cli.js +42501 -0
  16. package/dist/consolidate-ac0mnfyj.md +24 -0
  17. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  18. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  19. package/dist/deep-review-parity-0ec904db.md +120 -0
  20. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  21. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  22. package/dist/index.js +20190 -0
  23. package/dist/opencode-ci-7b0be64p.md +141 -0
  24. package/dist/review-refuter-j4e9gezy.md +71 -0
  25. package/dist/scout-yvp153q7.md +140 -0
  26. package/dist/summarizer-zca44nxa.md +18 -0
  27. package/dist/workflow-w1g9szna.yml +151 -0
  28. package/package.json +81 -4
  29. package/prompts/consolidate.md +24 -0
  30. package/prompts/default/PROVENANCE.md +18 -0
  31. package/prompts/default/deep-review-lifecycle.md +362 -0
  32. package/prompts/default/deep-review-logic.md +156 -0
  33. package/prompts/default/deep-review-parity.md +120 -0
  34. package/prompts/default/deep-review-reliability.md +125 -0
  35. package/prompts/default/deep-review-resilience.md +118 -0
  36. package/prompts/default/review-refuter.md +71 -0
  37. package/prompts/scout.md +140 -0
  38. package/prompts/summarizer.md +18 -0
  39. package/skills/crysk/SKILL.md +74 -0
  40. package/skills/crysk-ci-setup/SKILL.md +134 -0
  41. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  42. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  43. package/skills/crysk-ci-setup/references/ci-admission.md +124 -0
  44. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  45. package/skills/crysk-loop/SKILL.md +515 -0
  46. package/skills/crysk-loop/adjudicator.md +86 -0
  47. package/skills/crysk-pr/SKILL.md +66 -0
  48. package/src/agent-env.ts +1084 -0
  49. package/src/asset-manifest.ts +83 -0
  50. package/src/assets.d.ts +6 -0
  51. package/src/assets.ts +183 -0
  52. package/src/brand-paths.ts +155 -0
  53. package/src/brand.ts +255 -0
  54. package/src/ci/admission-ledger.ts +350 -0
  55. package/src/ci/classify-error.ts +73 -0
  56. package/src/ci/cli-record.ts +271 -0
  57. package/src/ci/force-comment.ts +39 -0
  58. package/src/ci/gates.ts +945 -0
  59. package/src/ci/outcome.ts +2181 -0
  60. package/src/ci/override.ts +187 -0
  61. package/src/ci/publish.ts +1639 -0
  62. package/src/ci/reporter.ts +626 -0
  63. package/src/ci/review-admission.ts +910 -0
  64. package/src/ci/review-levels.ts +310 -0
  65. package/src/ci/review-policy.ts +18 -0
  66. package/src/ci/review-risk.ts +184 -0
  67. package/src/ci/setup.ts +844 -0
  68. package/src/ci/trigger.ts +1353 -0
  69. package/src/cli.ts +348 -0
  70. package/src/commands/activity.ts +67 -0
  71. package/src/commands/ci-setup-questions.ts +397 -0
  72. package/src/commands/ci-setup.ts +381 -0
  73. package/src/commands/config.ts +99 -0
  74. package/src/commands/doctor.ts +108 -0
  75. package/src/commands/init.ts +139 -0
  76. package/src/commands/mcp.ts +10 -0
  77. package/src/commands/menu.ts +129 -0
  78. package/src/commands/post.ts +302 -0
  79. package/src/commands/skills.ts +83 -0
  80. package/src/commands/status.ts +173 -0
  81. package/src/commands/triage.ts +342 -0
  82. package/src/commands/uninstall.ts +37 -0
  83. package/src/commands/upgrade.ts +214 -0
  84. package/src/commands/usage.ts +98 -0
  85. package/src/compare/compare.ts +28 -0
  86. package/src/compare/floor-test.ts +471 -0
  87. package/src/compare/martian-adapter.ts +80 -0
  88. package/src/config/config.ts +267 -0
  89. package/src/corpus/corpus.ts +1094 -0
  90. package/src/corpus/preflight.ts +1789 -0
  91. package/src/diversity/accounting.ts +90 -0
  92. package/src/diversity/adjudication.ts +145 -0
  93. package/src/diversity/admission.ts +60 -0
  94. package/src/diversity/benchmark.ts +195 -0
  95. package/src/diversity/clustering.ts +285 -0
  96. package/src/diversity/errors.ts +7 -0
  97. package/src/diversity/identity.ts +285 -0
  98. package/src/diversity/index.ts +11 -0
  99. package/src/diversity/pipeline-integration.ts +448 -0
  100. package/src/diversity/projection.ts +57 -0
  101. package/src/diversity/self-contained.ts +68 -0
  102. package/src/diversity/target-validation.ts +179 -0
  103. package/src/doctor-migration.ts +209 -0
  104. package/src/doctor.ts +723 -0
  105. package/src/errors.ts +83 -0
  106. package/src/execution/admission.ts +75 -0
  107. package/src/execution/atomic-write.ts +35 -0
  108. package/src/execution/attempt-evidence.ts +415 -0
  109. package/src/execution/bucket-id.ts +136 -0
  110. package/src/execution/concurrency-limiter.ts +175 -0
  111. package/src/execution/contracts.ts +443 -0
  112. package/src/execution/failure-classification.ts +42 -0
  113. package/src/execution/failure-policy.ts +240 -0
  114. package/src/execution/harness.ts +2548 -0
  115. package/src/execution/settlement.ts +348 -0
  116. package/src/execution/spawned-process.ts +66 -0
  117. package/src/execution/spend-limiter.ts +424 -0
  118. package/src/execution/step-artifacts.ts +55 -0
  119. package/src/execution/usage-normalized.ts +469 -0
  120. package/src/git/git.ts +396 -0
  121. package/src/git/identity.ts +64 -0
  122. package/src/git/refs.ts +140 -0
  123. package/src/home-preflight.ts +443 -0
  124. package/src/home.ts +243 -0
  125. package/src/ignore-file.ts +336 -0
  126. package/src/ignore-read.ts +118 -0
  127. package/src/index.ts +34 -0
  128. package/src/legacy-launchd.ts +29 -0
  129. package/src/mcp/mcp.ts +150 -0
  130. package/src/mcp/preflight.ts +407 -0
  131. package/src/menu-context.ts +192 -0
  132. package/src/model/catalog.ts +251 -0
  133. package/src/model/exec-snapshots.ts +390 -0
  134. package/src/model/free-discovery.ts +302 -0
  135. package/src/model/provider-capabilities.ts +814 -0
  136. package/src/model/routing.ts +600 -0
  137. package/src/pr/admission.ts +984 -0
  138. package/src/pr/answered-findings.ts +169 -0
  139. package/src/pr/ci-admission-gate.ts +743 -0
  140. package/src/pr/ci-publish.ts +76 -0
  141. package/src/pr/discovery.ts +432 -0
  142. package/src/pr/inline.ts +507 -0
  143. package/src/pr/plan.ts +366 -0
  144. package/src/pr/posting.ts +115 -0
  145. package/src/pr/pr-status.ts +845 -0
  146. package/src/pr/pr.ts +3642 -0
  147. package/src/pr/preflight.ts +1031 -0
  148. package/src/pr/publish-outcome.ts +361 -0
  149. package/src/pr/range.ts +119 -0
  150. package/src/pr/reverts-preflight.ts +606 -0
  151. package/src/pr/reverts.ts +377 -0
  152. package/src/pr/review-pr.ts +927 -0
  153. package/src/pr/status.ts +154 -0
  154. package/src/pr/target.ts +388 -0
  155. package/src/pr/teardown.ts +437 -0
  156. package/src/pr/worktree-setup.ts +60 -0
  157. package/src/production-runtime.ts +1877 -0
  158. package/src/progress.ts +487 -0
  159. package/src/rereview/adjudicate.ts +89 -0
  160. package/src/rereview/classify.ts +362 -0
  161. package/src/rereview/identity.ts +211 -0
  162. package/src/rereview/plan.ts +308 -0
  163. package/src/rereview/prepare.ts +1025 -0
  164. package/src/rereview/state.ts +767 -0
  165. package/src/rereview/verify.ts +241 -0
  166. package/src/review/boundary.ts +105 -0
  167. package/src/review/consolidate.ts +246 -0
  168. package/src/review/dedupe.ts +368 -0
  169. package/src/review/drafts.ts +448 -0
  170. package/src/review/findings-conformance.ts +120 -0
  171. package/src/review/findings.ts +714 -0
  172. package/src/review/pipeline.ts +3977 -0
  173. package/src/review/preflight.ts +3575 -0
  174. package/src/review/prompt-set.ts +177 -0
  175. package/src/review/proof-refs.ts +187 -0
  176. package/src/review/report.ts +1821 -0
  177. package/src/review/review.ts +490 -0
  178. package/src/review/root-cause.ts +120 -0
  179. package/src/review/route-preflight.ts +289 -0
  180. package/src/review/run.ts +601 -0
  181. package/src/review/scout.ts +323 -0
  182. package/src/review/size-gate.ts +595 -0
  183. package/src/review/spec.ts +235 -0
  184. package/src/review/step-runner.ts +233 -0
  185. package/src/runner-authority.ts +596 -0
  186. package/src/security/binding-policy.ts +115 -0
  187. package/src/security/credential-broker.ts +773 -0
  188. package/src/security/evidence-redaction.ts +62 -0
  189. package/src/security/execution-authority.ts +27 -0
  190. package/src/security/redact.ts +71 -0
  191. package/src/security/workspace-read-broker.ts +466 -0
  192. package/src/server/client.ts +190 -0
  193. package/src/server/preflight.ts +217 -0
  194. package/src/server/server.ts +327 -0
  195. package/src/signal-handler.ts +50 -0
  196. package/src/store/activity.ts +413 -0
  197. package/src/store/backfill-preflight.ts +49 -0
  198. package/src/store/backfill.ts +141 -0
  199. package/src/store/gc-preflight.ts +206 -0
  200. package/src/store/gc.ts +424 -0
  201. package/src/store/metrics-preflight.ts +229 -0
  202. package/src/store/metrics.ts +236 -0
  203. package/src/store/preflight.ts +748 -0
  204. package/src/store/store.ts +693 -0
  205. package/src/system-tools.ts +355 -0
  206. package/src/transport-registry.ts +1124 -0
  207. package/src/transports/claude-code-cli.ts +1348 -0
  208. package/src/transports/opencode-admission.ts +515 -0
  209. package/src/transports/opencode-client.ts +3328 -0
  210. package/src/transports/opencode-evidence.ts +557 -0
  211. package/src/transports/opencode-mcp.ts +248 -0
  212. package/src/transports/opencode-sdk.ts +2294 -0
  213. package/src/transports/opencode-server.ts +535 -0
  214. package/src/triage/adjudication.ts +113 -0
  215. package/src/triage/reply.ts +125 -0
  216. package/src/triage/triage.ts +255 -0
  217. package/src/ui/activity.ts +173 -0
  218. package/src/ui/config-edit.ts +816 -0
  219. package/src/ui/config.ts +462 -0
  220. package/src/ui/menu.ts +1325 -0
  221. package/src/ui/plan.ts +1039 -0
  222. package/src/ui/primitives.ts +300 -0
  223. package/src/ui/progress.ts +298 -0
  224. package/src/ui/result.ts +552 -0
  225. package/src/ui/review-menu.ts +312 -0
  226. package/src/ui/select.ts +528 -0
  227. package/src/ui/tree.ts +178 -0
  228. package/src/uninstaller.ts +479 -0
  229. package/src/updater.ts +836 -0
  230. package/src/usage.ts +77 -0
  231. package/src/watch/preflight.ts +1389 -0
  232. package/src/watch/watch.ts +1235 -0
  233. package/src/wizard.ts +877 -0
@@ -0,0 +1,206 @@
1
+ // Worktree GC decisions (W3 / GitHub #18), pure so the keep/collect table
2
+ // is testable offline. store/gc.ts is the I/O shell: it scans ~/.prhero/repos,
3
+ // asks gh for PR state, and runs `git worktree remove --force`.
4
+ //
5
+ // Unbounded accumulation is not allowed. Collect when the PR is merged or
6
+ // closed, OR when the tree has sat idle longer than 72h, whichever first.
7
+ // Skip an in-flight tree (a live pid on the sibling lock). Never rm -rf.
8
+
9
+ import path from "node:path";
10
+ import type { SelfInvocation } from "../assets";
11
+ import { GC_TTL_HOURS, prheroLayout } from "../home-preflight";
12
+
13
+ export type PrLifecycle = "open" | "merged" | "closed" | "unknown";
14
+ export type GcAction = "keep" | "collect";
15
+
16
+ export interface GcInput {
17
+ prState: PrLifecycle;
18
+ // Last successful review, from registry.json. Null means no stamp.
19
+ lastReviewAtMs: number | null;
20
+ // Directory mtime of the worktree itself, used only when the stamp is
21
+ // missing. Null means we could not stat it either — treat as expired.
22
+ dirMtimeMs: number | null;
23
+ nowMs: number;
24
+ ttlHours?: number;
25
+ inFlight: boolean;
26
+ }
27
+
28
+ export interface GcDecision {
29
+ action: GcAction;
30
+ reason: string;
31
+ }
32
+
33
+ const HOUR_MS = 60 * 60 * 1000;
34
+
35
+ // Bound every `gh pr view` so a stalled GitHub cannot pin a review lock
36
+ // or watch.lock forever. Timed-out views become `unknown` and still
37
+ // apply TTL (same as a failed gh).
38
+ export const GH_PR_VIEW_TIMEOUT_MS = 15_000;
39
+
40
+ export function decideGc(input: GcInput): GcDecision {
41
+ if (input.inFlight) {
42
+ return { action: "keep", reason: "in-flight (live lock)" };
43
+ }
44
+ if (input.prState === "merged" || input.prState === "closed") {
45
+ return {
46
+ action: "collect",
47
+ reason: `PR is ${input.prState}`,
48
+ };
49
+ }
50
+ const ttlHours = input.ttlHours ?? GC_TTL_HOURS;
51
+ const idleFrom = input.lastReviewAtMs ?? input.dirMtimeMs;
52
+ if (idleFrom === null) {
53
+ return {
54
+ action: "collect",
55
+ reason: `idle longer than ${ttlHours}h (no stamp, no mtime)`,
56
+ };
57
+ }
58
+ const idleHours = (input.nowMs - idleFrom) / HOUR_MS;
59
+ if (idleHours > ttlHours) {
60
+ return {
61
+ action: "collect",
62
+ reason: `idle longer than ${ttlHours}h`,
63
+ };
64
+ }
65
+ return { action: "keep", reason: "open and within TTL" };
66
+ }
67
+
68
+ // `pr-1724` → 1724. Anything else (including the sibling `.lock` file) is
69
+ // not a worktree we own.
70
+ export function parseWorktreePr(dirName: string): number | null {
71
+ const match = /^pr-(\d+)$/.exec(dirName);
72
+ if (match === null) return null;
73
+ const n = Number(match[1]);
74
+ return Number.isInteger(n) && n >= 1 ? n : null;
75
+ }
76
+
77
+ export function parseGhPrState(raw: string): PrLifecycle {
78
+ let parsed: unknown;
79
+ try {
80
+ parsed = JSON.parse(raw);
81
+ } catch {
82
+ return "unknown";
83
+ }
84
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
85
+ return "unknown";
86
+ }
87
+ const state = (parsed as Record<string, unknown>).state;
88
+ if (typeof state !== "string") return "unknown";
89
+ const upper = state.toUpperCase();
90
+ if (upper === "OPEN") return "open";
91
+ if (upper === "MERGED") return "merged";
92
+ if (upper === "CLOSED") return "closed";
93
+ return "unknown";
94
+ }
95
+
96
+ // The only argv `git -C <owner>` may receive for teardown. Tests pin
97
+ // `--force` and the absence of `rm`. The path is an argument, never
98
+ // interpolated into a shell string.
99
+ export function worktreeRemoveArgs(worktreePath: string): string[] {
100
+ return ["worktree", "remove", "--force", worktreePath];
101
+ }
102
+
103
+ // ---------------------------------------------------------------------------
104
+ // launchd agent (macOS). Rendering is pure string-out so a test can pin
105
+ // the exact plist; loading it is store/gc.ts's job. Separate label and log from
106
+ // the watcher: this agent runs `pr-hero gc` (no reviews, no watch.json).
107
+
108
+ export const GC_LAUNCHD_LABEL = "io.crysk.gc";
109
+
110
+ export function gcPlistPath(home: string): string {
111
+ return path.join(
112
+ home,
113
+ "Library",
114
+ "LaunchAgents",
115
+ `${GC_LAUNCHD_LABEL}.plist`,
116
+ );
117
+ }
118
+
119
+ export function gcLaunchdLogPath(home: string): string {
120
+ return path.join(prheroLayout(home).dir, "gc-launchd.log");
121
+ }
122
+
123
+ export interface GcPlistInput {
124
+ // The engine's OWN invocation (assets.ts's selfInvocation()), not a fixed
125
+ // runtime + entry-script pair. A compiled binary IS the entry and
126
+ // contributes no script path at all, which the pair had no way to say: it
127
+ // rendered `<binary> /$bunfs/root/cli.ts gc`, a path that exists on no
128
+ // machine, and launchd re-ran that unknown-command failure every interval
129
+ // forever while `gc install` reported success.
130
+ //
131
+ // Absolute by construction (selfInvocation resolves both halves), which is
132
+ // what launchd needs: it starts agents with a bare-bones PATH
133
+ // (/usr/bin:/bin) that has never heard of bun or pr-hero, so a bare name
134
+ // that resolves in every terminal resolves in nothing launchd starts.
135
+ invocation: SelfInvocation;
136
+ intervalSeconds: number;
137
+ logPath: string;
138
+ pathEnv: string;
139
+ }
140
+
141
+ export function renderGcPlist(input: GcPlistInput): string {
142
+ const programArguments = [input.invocation.command, ...input.invocation.args];
143
+ const lines = [
144
+ `<?xml version="1.0" encoding="UTF-8"?>`,
145
+ `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
146
+ `<plist version="1.0">`,
147
+ `<dict>`,
148
+ ` <key>Label</key>`,
149
+ ` <string>${GC_LAUNCHD_LABEL}</string>`,
150
+ ` <key>ProgramArguments</key>`,
151
+ ` <array>`,
152
+ ...[...programArguments, "gc"].map(
153
+ (arg) => ` <string>${xmlEscape(arg)}</string>`,
154
+ ),
155
+ ` </array>`,
156
+ ` <key>StartInterval</key>`,
157
+ ` <integer>${input.intervalSeconds}</integer>`,
158
+ ` <key>StandardOutPath</key>`,
159
+ ` <string>${xmlEscape(input.logPath)}</string>`,
160
+ ` <key>StandardErrorPath</key>`,
161
+ ` <string>${xmlEscape(input.logPath)}</string>`,
162
+ ` <key>EnvironmentVariables</key>`,
163
+ ` <dict>`,
164
+ ` <key>PATH</key>`,
165
+ ` <string>${xmlEscape(input.pathEnv)}</string>`,
166
+ ` </dict>`,
167
+ `</dict>`,
168
+ `</plist>`,
169
+ ];
170
+ return `${lines.join("\n")}\n`;
171
+ }
172
+
173
+ function xmlEscape(text: string): string {
174
+ return text
175
+ .replaceAll("&", "&amp;")
176
+ .replaceAll("<", "&lt;")
177
+ .replaceAll(">", "&gt;");
178
+ }
179
+
180
+ export interface GcStatusFacts {
181
+ plistPath: string;
182
+ logPath: string;
183
+ installed: boolean;
184
+ intervalSeconds: number | null;
185
+ }
186
+
187
+ export function renderGcStatus(facts: GcStatusFacts): string[] {
188
+ const row = (label: string, value: string): string =>
189
+ ` ${label.padEnd(13)}${value}`;
190
+ const launchd = facts.installed
191
+ ? facts.intervalSeconds === null
192
+ ? `installed (${facts.plistPath}, interval unreadable)`
193
+ : `installed — one tick every ${formatGcInterval(facts.intervalSeconds)}`
194
+ : 'not installed — run "crysk gc install" to start sweeping';
195
+ return [
196
+ "crysk gc — status",
197
+ "",
198
+ row("launchd", launchd),
199
+ row("plist", facts.plistPath),
200
+ row("tick output", facts.logPath),
201
+ ];
202
+ }
203
+
204
+ function formatGcInterval(seconds: number): string {
205
+ return seconds % 60 === 0 ? `${seconds / 60} min` : `${seconds}s`;
206
+ }
@@ -0,0 +1,424 @@
1
+ // Worktree GC I/O (W3 / GitHub #18). Scans ~/.prhero/repos/*/worktrees,
2
+ // asks gh for PR state, and tears trees down with `git worktree remove
3
+ // --force` only. Decisions live in store/gc-preflight.ts. Also sweeps the
4
+ // verified execution snapshots crashed runs left in $TMPDIR (#303).
5
+ //
6
+ // Same git-runner rule as the other shells: args as an ARRAY, never an
7
+ // interpolated shell string. Never rm -rf — a live codegraph daemon holds
8
+ // .codegraph/daemon.sock.
9
+
10
+ import { existsSync } from "node:fs";
11
+ import { mkdir, readdir, rm, stat } from "node:fs/promises";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import { git } from "#git/git";
15
+ import {
16
+ type SnapshotSweepReport,
17
+ sweepStaleExecutionSnapshots,
18
+ } from "#model/exec-snapshots";
19
+ import { type CliOptions, DEFAULT_GC_INTERVAL_MIN } from "#review/preflight";
20
+ import { log } from "#ui/primitives";
21
+ import { parsePlistInterval } from "#watch/preflight";
22
+ import {
23
+ isNpxCacheInvocation,
24
+ NPX_REGISTRATION_REFUSED,
25
+ selfInvocation,
26
+ } from "../assets";
27
+ import { CliError } from "../errors";
28
+ import {
29
+ acquirePidLock,
30
+ releasePidLock,
31
+ resolveRepoHome,
32
+ worktreeInFlight,
33
+ } from "../home";
34
+ import {
35
+ parseRepoRegistry,
36
+ prheroLayout,
37
+ type RepoRegistry,
38
+ repoHomePaths,
39
+ worktreeLockPath,
40
+ } from "../home-preflight";
41
+ import { LEGACY_GC_LAUNCHD_LABEL, retireLegacyAgent } from "../legacy-launchd";
42
+ import {
43
+ decideGc,
44
+ GC_LAUNCHD_LABEL,
45
+ GH_PR_VIEW_TIMEOUT_MS,
46
+ gcLaunchdLogPath,
47
+ gcPlistPath,
48
+ type PrLifecycle,
49
+ parseGhPrState,
50
+ parseWorktreePr,
51
+ renderGcPlist,
52
+ renderGcStatus,
53
+ worktreeRemoveArgs,
54
+ } from "./gc-preflight";
55
+
56
+ async function ghPrStateJson(cwd: string, pr: number): Promise<string | null> {
57
+ const proc = Bun.spawn(["gh", "pr", "view", String(pr), "--json", "state"], {
58
+ cwd,
59
+ stdout: "pipe",
60
+ stderr: "pipe",
61
+ timeout: GH_PR_VIEW_TIMEOUT_MS,
62
+ });
63
+ const [stdout, , exitCode] = await Promise.all([
64
+ new Response(proc.stdout).text(),
65
+ new Response(proc.stderr).text(),
66
+ proc.exited,
67
+ ]);
68
+ if (exitCode !== 0) return null;
69
+ return stdout;
70
+ }
71
+
72
+ interface DiscoveredWorktree {
73
+ repoId: string;
74
+ pr: number;
75
+ worktreePath: string;
76
+ lockPath: string;
77
+ registry: RepoRegistry;
78
+ dirMtimeMs: number | null;
79
+ }
80
+
81
+ async function discoverWorktrees(
82
+ home: string,
83
+ onlyRepoId: string | undefined,
84
+ ): Promise<DiscoveredWorktree[]> {
85
+ const reposDir = prheroLayout(home).reposDir;
86
+ if (!existsSync(reposDir)) return [];
87
+ const found: DiscoveredWorktree[] = [];
88
+ const glob = new Bun.Glob("**/registry.json");
89
+ for await (const rel of glob.scan({ cwd: reposDir })) {
90
+ const registryPath = path.join(reposDir, rel);
91
+ let registry: RepoRegistry;
92
+ try {
93
+ registry = parseRepoRegistry(await Bun.file(registryPath).text());
94
+ } catch {
95
+ continue;
96
+ }
97
+ if (onlyRepoId !== undefined && registry.canonical_remote !== onlyRepoId) {
98
+ continue;
99
+ }
100
+ const paths = repoHomePaths(home, registry.canonical_remote);
101
+ if (!existsSync(paths.worktrees)) continue;
102
+ for (const entry of await readdir(paths.worktrees, {
103
+ withFileTypes: true,
104
+ })) {
105
+ if (!entry.isDirectory()) continue;
106
+ const pr = parseWorktreePr(entry.name);
107
+ if (pr === null) continue;
108
+ const worktreePath = path.join(paths.worktrees, entry.name);
109
+ let dirMtimeMs: number | null = null;
110
+ try {
111
+ dirMtimeMs = (await stat(worktreePath)).mtimeMs;
112
+ } catch {
113
+ dirMtimeMs = null;
114
+ }
115
+ found.push({
116
+ repoId: registry.canonical_remote,
117
+ pr,
118
+ worktreePath,
119
+ lockPath: worktreeLockPath(home, registry.canonical_remote, pr),
120
+ registry,
121
+ dirMtimeMs,
122
+ });
123
+ }
124
+ }
125
+ found.sort((a, b) =>
126
+ a.repoId === b.repoId ? a.pr - b.pr : a.repoId.localeCompare(b.repoId),
127
+ );
128
+ return found;
129
+ }
130
+
131
+ function stampMs(registry: RepoRegistry, pr: number): number | null {
132
+ const stamp = registry.worktrees[String(pr)]?.last_review_at;
133
+ if (stamp === undefined) return null;
134
+ const parsed = Date.parse(stamp);
135
+ return Number.isNaN(parsed) ? null : parsed;
136
+ }
137
+
138
+ export async function runGc(input: {
139
+ home: string;
140
+ repoId?: string;
141
+ dryRun: boolean;
142
+ nowMs?: number;
143
+ silent?: boolean;
144
+ }): Promise<{ collected: number; kept: number; failed: number }> {
145
+ const nowMs = input.nowMs ?? Date.now();
146
+ const trees = await discoverWorktrees(input.home, input.repoId);
147
+ let collected = 0;
148
+ let kept = 0;
149
+ let failed = 0;
150
+ for (const tree of trees) {
151
+ let prState: PrLifecycle = "unknown";
152
+ const raw = await ghPrStateJson(tree.registry.git_dir_owner, tree.pr);
153
+ if (raw !== null) {
154
+ prState = parseGhPrState(raw);
155
+ } else if (!input.silent) {
156
+ log(
157
+ `gc: gh pr view ${tree.pr} failed for ${tree.repoId}; applying TTL only`,
158
+ );
159
+ }
160
+ const decision = decideGc({
161
+ prState,
162
+ lastReviewAtMs: stampMs(tree.registry, tree.pr),
163
+ dirMtimeMs: tree.dirMtimeMs,
164
+ nowMs,
165
+ inFlight: worktreeInFlight(tree.lockPath),
166
+ });
167
+ if (!input.silent) {
168
+ log(
169
+ `${decision.action.padEnd(8)} pr-${tree.pr} ${tree.repoId} ${decision.reason}`,
170
+ );
171
+ }
172
+ if (decision.action === "keep") {
173
+ kept++;
174
+ continue;
175
+ }
176
+ if (input.dryRun) {
177
+ collected++;
178
+ continue;
179
+ }
180
+ // Collect is check-then-act unless we hold this PR's lock across the
181
+ // remove: a review can acquirePidLock in the gap and then have its
182
+ // tree yanked. A live holder fails loud — treat that as in-flight.
183
+ try {
184
+ await acquirePidLock(tree.lockPath);
185
+ } catch (error) {
186
+ if (
187
+ error instanceof CliError &&
188
+ error.message.startsWith("lock held by pid")
189
+ ) {
190
+ kept++;
191
+ if (!input.silent) {
192
+ log(`keep pr-${tree.pr} ${tree.repoId} in-flight (live lock)`);
193
+ }
194
+ continue;
195
+ }
196
+ throw error;
197
+ }
198
+ try {
199
+ const removed = await git(
200
+ tree.registry.git_dir_owner,
201
+ worktreeRemoveArgs(tree.worktreePath),
202
+ );
203
+ if (!removed.ok) {
204
+ failed++;
205
+ if (!input.silent) {
206
+ log(
207
+ `gc: git worktree remove --force ${tree.worktreePath} failed: ` +
208
+ removed.stderr.trim(),
209
+ );
210
+ }
211
+ continue;
212
+ }
213
+ collected++;
214
+ } finally {
215
+ await releasePidLock(tree.lockPath);
216
+ }
217
+ }
218
+ return { collected, kept, failed };
219
+ }
220
+
221
+ function formatBytes(bytes: number): string {
222
+ const units = ["KB", "MB", "GB", "TB"];
223
+ if (bytes < 1024) return `${bytes} B`;
224
+ let value = bytes / 1024;
225
+ let unit = 0;
226
+ // Compare the value as it will be DISPLAYED: 1048575 bytes is 1023.999 KB,
227
+ // which toFixed(1) rounds to "1024.0 KB" — it must print as "1.0 MB".
228
+ while (Number(value.toFixed(1)) >= 1024 && unit < units.length - 1) {
229
+ value /= 1024;
230
+ unit++;
231
+ }
232
+ return `${value.toFixed(1)} ${units[unit]}`;
233
+ }
234
+
235
+ export function renderSnapshotGcLine(
236
+ report: SnapshotSweepReport,
237
+ dryRun: boolean,
238
+ ): string {
239
+ const verb = dryRun
240
+ ? "dry run: exec snapshots would remove"
241
+ : "gc: exec snapshots removed";
242
+ return (
243
+ `${verb} ${report.removed} (${formatBytes(report.removedBytes)}), keep ${report.kept}` +
244
+ (report.failed > 0 ? `, ${report.failed} failed` : "")
245
+ );
246
+ }
247
+
248
+ // #303: the crash backstop for snapshots no process released — SIGKILL,
249
+ // a crash, default-signal death. Same rules as the opportunistic sweep (dead
250
+ // owner pid or older than 6 h; never another user's entry), but unthrottled
251
+ // and reported. Best-effort: a snapshot that cannot be removed is counted
252
+ // in the line, never a reason to fail the worktree gc around it. Never
253
+ // throws: gcCommand runs it from a `finally`, where a throw would replace
254
+ // the worktree gc's own error.
255
+ export async function gcExecutionSnapshots(input: {
256
+ readonly dryRun: boolean;
257
+ readonly snapshotBase?: string;
258
+ }): Promise<string> {
259
+ try {
260
+ const report = await sweepStaleExecutionSnapshots({
261
+ snapshotBase: input.snapshotBase,
262
+ dryRun: input.dryRun,
263
+ });
264
+ return renderSnapshotGcLine(report, input.dryRun);
265
+ } catch (error) {
266
+ return `gc: exec snapshot sweep failed: ${(error as Error).message}`;
267
+ }
268
+ }
269
+
270
+ export async function gcCommand(options: CliOptions): Promise<number> {
271
+ if (options.gc === "install") {
272
+ return gcInstall(options.interval ?? DEFAULT_GC_INTERVAL_MIN);
273
+ }
274
+ if (options.gc === "uninstall") return gcUninstall();
275
+ if (options.gc === "status") return gcStatus();
276
+
277
+ const home = os.homedir();
278
+ let result: Awaited<ReturnType<typeof runGc>>;
279
+ try {
280
+ // parseArgs defaults --repo to ".". For gc that means "the whole home",
281
+ // not "the current checkout" — scoping takes an explicit path.
282
+ let repoId: string | undefined;
283
+ if (options.repo !== ".") {
284
+ const resolved = await resolveRepoHome({
285
+ home,
286
+ operatorRoot: path.resolve(options.repo),
287
+ persist: false,
288
+ });
289
+ repoId = resolved.repoId;
290
+ }
291
+ result = await runGc({
292
+ home,
293
+ repoId,
294
+ dryRun: options.dryRun,
295
+ });
296
+ const verb = options.dryRun ? "dry run: would collect" : "gc: collected";
297
+ log(
298
+ `${verb} ${result.collected}, keep ${result.kept}` +
299
+ (result.failed > 0 ? `, ${result.failed} failed` : ""),
300
+ );
301
+ } finally {
302
+ // #303: the snapshot sweep is the launchd backstop for SIGKILL/crash
303
+ // leftovers, so it runs even when the worktree half throws (a scoped
304
+ // --repo without origin, an fs or lock error) — and before the worktree
305
+ // failure throw below. It never throws, so it cannot mask that error.
306
+ log(await gcExecutionSnapshots({ dryRun: options.dryRun }));
307
+ }
308
+ if (!options.dryRun && result.failed > 0) {
309
+ throw new CliError(
310
+ `gc failed to remove ${result.failed} worktree(s); see stderr`,
311
+ );
312
+ }
313
+ return 0;
314
+ }
315
+
316
+ async function run(
317
+ args: string[],
318
+ ): Promise<{ ok: boolean; stdout: string; stderr: string }> {
319
+ const proc = Bun.spawn(args, { stdout: "pipe", stderr: "pipe" });
320
+ const [stdout, stderr, exitCode] = await Promise.all([
321
+ new Response(proc.stdout).text(),
322
+ new Response(proc.stderr).text(),
323
+ proc.exited,
324
+ ]);
325
+ return { ok: exitCode === 0, stdout, stderr };
326
+ }
327
+
328
+ async function gcInstall(intervalMin: number): Promise<number> {
329
+ if (process.platform !== "darwin") {
330
+ throw new CliError(
331
+ "gc install renders a macOS launchd agent. On other systems run " +
332
+ "`crysk gc` from cron.",
333
+ );
334
+ }
335
+ // selfInvocation(), not a hand-built runtime + src/cli.ts pair: the pair
336
+ // is only correct for a source checkout, and the compiled binary it was
337
+ // wrong for is the one users install. Checked before any write, so a refused
338
+ // install leaves nothing on disk.
339
+ const invocation = selfInvocation();
340
+ if (isNpxCacheInvocation(invocation)) {
341
+ throw new CliError(NPX_REGISTRATION_REFUSED);
342
+ }
343
+ const home = os.homedir();
344
+ const plistPath = gcPlistPath(home);
345
+ const logPath = gcLaunchdLogPath(home);
346
+ await mkdir(prheroLayout(home).dir, { recursive: true });
347
+ await mkdir(path.dirname(plistPath), { recursive: true });
348
+ const plist = renderGcPlist({
349
+ invocation,
350
+ intervalSeconds: intervalMin * 60,
351
+ logPath,
352
+ pathEnv: process.env.PATH ?? "",
353
+ });
354
+ if (existsSync(plistPath)) {
355
+ const unloaded = await run(["launchctl", "unload", "-w", plistPath]);
356
+ log(
357
+ unloaded.ok
358
+ ? `unloaded previous ${GC_LAUNCHD_LABEL}`
359
+ : "previous plist present but not loaded (fine, replacing it)",
360
+ );
361
+ }
362
+ await retireLegacyAgent({
363
+ home,
364
+ legacyLabel: LEGACY_GC_LAUNCHD_LABEL,
365
+ run,
366
+ log,
367
+ });
368
+ await Bun.write(plistPath, plist);
369
+ const loaded = await run(["launchctl", "load", "-w", plistPath]);
370
+ if (!loaded.ok) {
371
+ throw new CliError(
372
+ `launchctl load -w ${plistPath} failed: ${loaded.stderr.trim()}`,
373
+ );
374
+ }
375
+ log(`wrote ${plistPath}`);
376
+ log(`loaded ${GC_LAUNCHD_LABEL} — one tick every ${intervalMin} min`);
377
+ log(`tick output: ${logPath}`);
378
+ return 0;
379
+ }
380
+
381
+ async function gcUninstall(): Promise<number> {
382
+ if (process.platform !== "darwin") {
383
+ throw new CliError(
384
+ "gc uninstall manages a macOS launchd agent; there is nothing to " +
385
+ "uninstall on this system.",
386
+ );
387
+ }
388
+ const plistPath = gcPlistPath(os.homedir());
389
+ await retireLegacyAgent({
390
+ home: os.homedir(),
391
+ legacyLabel: LEGACY_GC_LAUNCHD_LABEL,
392
+ run,
393
+ log,
394
+ });
395
+ if (!existsSync(plistPath)) {
396
+ log(`nothing installed (no ${plistPath})`);
397
+ return 0;
398
+ }
399
+ const unloaded = await run(["launchctl", "unload", "-w", plistPath]);
400
+ log(
401
+ unloaded.ok
402
+ ? `unloaded ${GC_LAUNCHD_LABEL}`
403
+ : `plist present but not loaded: ${unloaded.stderr.trim() || "(no detail)"}`,
404
+ );
405
+ await rm(plistPath, { force: true });
406
+ log(`removed ${plistPath}`);
407
+ return 0;
408
+ }
409
+
410
+ async function gcStatus(): Promise<number> {
411
+ const home = os.homedir();
412
+ const plistPath = gcPlistPath(home);
413
+ const installed = existsSync(plistPath);
414
+ const lines = renderGcStatus({
415
+ plistPath,
416
+ logPath: gcLaunchdLogPath(home),
417
+ installed,
418
+ intervalSeconds: installed
419
+ ? parsePlistInterval(await Bun.file(plistPath).text())
420
+ : null,
421
+ });
422
+ for (const line of lines) log(line);
423
+ return 0;
424
+ }