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,1235 @@
1
+ // The watcher's I/O shell (ROADMAP B3): config read, git/gh calls, the
2
+ // runs-root scan, the comment fetch, the lockfile, the append-only log, the
3
+ // review spawn, the macOS notification, and launchd install/uninstall —
4
+ // every side effect `pr-hero watch` needs. Same contract as cli.ts and
5
+ // pr/pr.ts: untested by construction, and every decision it acts on is a pure
6
+ // function in watch/preflight.ts, where the tests live.
7
+ //
8
+ // The tick never daemonizes. launchd (or cron) is the supervisor and the
9
+ // scheduler; one invocation is one pass over the configured repos, at most
10
+ // one spawned review, then exit.
11
+
12
+ import { existsSync } from "node:fs";
13
+ import { appendFile, mkdir, readdir, rm } from "node:fs/promises";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import { git, resolveRepoRoot } from "#git/git";
17
+ import {
18
+ fetchCommitStatuses,
19
+ fetchPrComments,
20
+ ghPrFiles,
21
+ ghPrList,
22
+ ghRepoWebUrl,
23
+ postCommitStatus,
24
+ } from "#pr/pr";
25
+ import {
26
+ commitStatusRequest,
27
+ IN_FLIGHT_TTL_MS,
28
+ isInFlightCommitStatus,
29
+ LOCAL_COMMIT_STATUS_CONTEXT,
30
+ latestStatusInContext,
31
+ prHtmlUrl,
32
+ RUN_STATUS_CONTEXTS,
33
+ } from "#pr/preflight";
34
+ import { validateFindingsDocument } from "#review/findings";
35
+ import {
36
+ type CliOptions,
37
+ DEFAULT_WATCH_INTERVAL_MIN,
38
+ type NumstatFile,
39
+ } from "#review/preflight";
40
+ import {
41
+ DEFAULT_SIZE_GATE,
42
+ evaluateSizeGate,
43
+ evaluateSizeGateAggregate,
44
+ type SizeGateConfig,
45
+ sizeGateConfig,
46
+ } from "#review/size-gate";
47
+ import { runGc } from "#store/gc";
48
+ import {
49
+ box,
50
+ log,
51
+ row,
52
+ section,
53
+ shortPath,
54
+ shortSha,
55
+ styleEnabled,
56
+ terminalWidth,
57
+ } from "#ui/primitives";
58
+ import {
59
+ isNpxCacheInvocation,
60
+ NPX_REGISTRATION_REFUSED,
61
+ selfInvocation,
62
+ } from "../assets";
63
+ import { CliError } from "../errors";
64
+ import { resolveRepoHome } from "../home";
65
+ import type { IgnoreRule } from "../ignore-file";
66
+ import {
67
+ type IgnoreFileReadResult,
68
+ readLocalIgnoreRules,
69
+ } from "../ignore-read";
70
+ import {
71
+ LEGACY_WATCH_LAUNCHD_LABEL,
72
+ retireLegacyAgent,
73
+ } from "../legacy-launchd";
74
+ import {
75
+ countAttempts,
76
+ countLaunchedToday,
77
+ decideTick,
78
+ expandTilde,
79
+ findingsTierCounts,
80
+ lastLogActivity,
81
+ latestRunDirName,
82
+ launchedLine,
83
+ localIsoTimestamp,
84
+ logLine,
85
+ markerCommentSeen,
86
+ markerDeclaredHeads,
87
+ osascriptNotifyArgs,
88
+ outcomeLine,
89
+ outcomeNotificationText,
90
+ type PrheroHomePaths,
91
+ parseLockPid,
92
+ parsePipelineMeta,
93
+ parsePlistInterval,
94
+ parsePrFiles,
95
+ parsePrList,
96
+ parseWatchConfig,
97
+ pendingReviewsToSettle,
98
+ preLaunchExclusionVeto,
99
+ prheroHomePaths,
100
+ type ReviewOutcome,
101
+ type RunDirFact,
102
+ removeWatchRepo,
103
+ renderWatchPlist,
104
+ renderWatchStatus,
105
+ skipLine,
106
+ type TickDecision,
107
+ type TickLaunch,
108
+ type TickRepoFacts,
109
+ tickGate,
110
+ upsertWatchRepo,
111
+ WATCH_LAUNCHD_LABEL,
112
+ type WatchConfig,
113
+ } from "./preflight";
114
+
115
+ async function run(
116
+ args: string[],
117
+ ): Promise<{ ok: boolean; stdout: string; stderr: string }> {
118
+ const proc = Bun.spawn(args, { stdout: "pipe", stderr: "pipe" });
119
+ const [stdout, stderr, exitCode] = await Promise.all([
120
+ new Response(proc.stdout).text(),
121
+ new Response(proc.stderr).text(),
122
+ proc.exited,
123
+ ]);
124
+ return { ok: exitCode === 0, stdout, stderr };
125
+ }
126
+
127
+ export async function watchCommand(options: CliOptions): Promise<number> {
128
+ if (options.watch === "install") {
129
+ return watchInstall(options.interval ?? DEFAULT_WATCH_INTERVAL_MIN);
130
+ }
131
+ if (options.watch === "uninstall") return watchUninstall();
132
+ if (options.watch === "add") return watchAdd(options);
133
+ if (options.watch === "remove") return watchRemove(options);
134
+ if (options.watch === "status") return watchStatus();
135
+ return watchOnce(options.dryRun);
136
+ }
137
+
138
+ // ---------------------------------------------------------------------------
139
+ // The tick.
140
+
141
+ // The DI seam gatherRepoFacts needs to be unit-testable (prheroignore Phase
142
+ // 6, design D6): one shape per I/O call it makes, mirroring RereviewGit's
143
+ // pattern (src/rereview/prepare.ts) rather than inventing a new one. Every
144
+ // OTHER I/O gatherRepoFacts touches — resolveRepoHome, scanRunDirs,
145
+ // fetchPrComments, fetchCommitStatuses — is left as real I/O on purpose: a
146
+ // candidate that clears the size gate reaches those unconditionally, and a
147
+ // throwaway tmpdir git repo already exercises resolveRepoHome/scanRunDirs
148
+ // faithfully offline (test/watch/watch.test.ts). Faking the comments/statuses
149
+ // fetch too would need a live-looking `gh` response for every eligible
150
+ // candidate an offline test can never safely construct, so test/watch/watch.test.ts
151
+ // deliberately never lets a fixture PR become eligible through
152
+ // gatherRepoFacts itself — see that file's own header comment.
153
+ export interface WatchIo {
154
+ git: (
155
+ repo: string,
156
+ args: string[],
157
+ ) => Promise<{ ok: boolean; stdout: string; stderr: string }>;
158
+ ghPrList: (repoRoot: string) => Promise<string>;
159
+ ghPrFiles: (repoRoot: string, pr: number) => Promise<string>;
160
+ readIgnoreFile: (root: string) => Promise<IgnoreFileReadResult>;
161
+ }
162
+
163
+ // Production wiring: the real subprocess/gh/fs calls this module already
164
+ // carries. Tests construct their own WatchIo (or a narrower Pick<...>) with
165
+ // scripted fakes instead.
166
+ const productionWatchIo: WatchIo = {
167
+ git,
168
+ ghPrList,
169
+ ghPrFiles,
170
+ readIgnoreFile: readLocalIgnoreRules,
171
+ };
172
+
173
+ export interface WatchedRepoFacts extends TickRepoFacts {
174
+ // TickRepoFacts.path is the resolved toplevel; the runs root rides along
175
+ // for the post-run outcome scan.
176
+ runsRoot: string;
177
+ // The repo's own size-gate thresholds, carried to the SPAWN. See the WHY
178
+ // on the review args in runTick: the spawned CLI re-runs the gate on the
179
+ // real numstat, and it must be told the same numbers this tick used.
180
+ maxChangedLines: number;
181
+ maxChangedFiles: number;
182
+ // The MERGED exclude rules (builtins + this repo's own `.prheroignore`)
183
+ // gatherRepoFacts already read and built via sizeGateConfig() — carried
184
+ // alongside the two limits above so applyPreLaunchVeto can rebuild the
185
+ // EXACT same SizeGateConfig without a second `.prheroignore` read.
186
+ excludeRules: IgnoreRule[];
187
+ }
188
+
189
+ async function watchOnce(dryRun: boolean): Promise<number> {
190
+ const paths = prheroHomePaths(os.homedir());
191
+ if (!existsSync(paths.watchConfigPath)) {
192
+ throw new CliError(
193
+ `no watch config at ${paths.watchConfigPath} — the watcher reviews (and ` +
194
+ "spends money on) exactly the repos listed there, so it refuses to " +
195
+ "guess. Opt a repo in with `crysk watch add` (run inside the " +
196
+ "repo, or with --repo <path>).",
197
+ );
198
+ }
199
+ const config = parseWatchConfig(await Bun.file(paths.watchConfigPath).text());
200
+
201
+ const now = new Date();
202
+ const ts = localIsoTimestamp(now);
203
+ const dayPrefix = ts.slice(0, 10);
204
+ const localMinutes = now.getHours() * 60 + now.getMinutes();
205
+ const logText = existsSync(paths.logPath)
206
+ ? await Bun.file(paths.logPath).text()
207
+ : "";
208
+ const gateInput = {
209
+ window: config.window,
210
+ localMinutes,
211
+ dailyCap: config.dailyCap,
212
+ launchedToday: countLaunchedToday(logText, dayPrefix),
213
+ };
214
+
215
+ // The real tick checks the gate BEFORE any git or gh call: a closed
216
+ // window or a spent cap must cost nothing, because launchd fires this
217
+ // every N minutes all day. The dry run deliberately keeps going — its
218
+ // whole point is the full picture.
219
+ if (!dryRun) {
220
+ const gate = tickGate(gateInput);
221
+ if (gate !== "open") {
222
+ await mkdir(paths.dir, { recursive: true });
223
+ await appendLog(
224
+ paths.logPath,
225
+ logLine(
226
+ ts,
227
+ gate === "window-closed"
228
+ ? `tick idle reason=window-closed window=${config.window?.start}-${config.window?.end}`
229
+ : `tick idle reason=cap-reached launched=${gateInput.launchedToday} cap=${config.dailyCap}`,
230
+ ),
231
+ );
232
+ return 0;
233
+ }
234
+ // The lockfile — advisory, PID-holding, stolen when dead. launchd is
235
+ // already single-instance per label; this covers cron and hand-run
236
+ // ticks overlapping a slow review.
237
+ const holder = await lockHolder(paths.lockPath);
238
+ if (holder !== null) {
239
+ await mkdir(paths.dir, { recursive: true });
240
+ await appendLog(
241
+ paths.logPath,
242
+ logLine(ts, `tick skipped reason=lock-held pid=${holder}`),
243
+ );
244
+ return 0;
245
+ }
246
+ await mkdir(paths.dir, { recursive: true });
247
+ await Bun.write(paths.lockPath, `${process.pid}\n`);
248
+ }
249
+
250
+ try {
251
+ if (!dryRun) {
252
+ // Each `gh pr view` is bounded (GH_PR_VIEW_TIMEOUT_MS) so a stall
253
+ // cannot pin watch.lock and silence every later tick.
254
+ await runGc({ home: os.homedir(), dryRun: false });
255
+ }
256
+ const repos = await gatherRepoFacts(
257
+ config,
258
+ os.homedir(),
259
+ productionWatchIo,
260
+ );
261
+ const decision = decideTick({ ...gateInput, repos });
262
+ if (dryRun) {
263
+ printDryRun(paths, config, gateInput.launchedToday, decision, repos);
264
+ return 0;
265
+ }
266
+ return await runTick(paths, decision, repos, productionWatchIo.ghPrFiles);
267
+ } finally {
268
+ if (!dryRun) await rm(paths.lockPath, { force: true });
269
+ }
270
+ }
271
+
272
+ // Reads everything the pure decision needs, per configured repo. Read-only
273
+ // throughout (gh api GETs, git rev-parse, artifact reads) — safe for the
274
+ // dry run by construction.
275
+ export async function gatherRepoFacts(
276
+ config: WatchConfig,
277
+ home: string,
278
+ io: WatchIo,
279
+ ): Promise<WatchedRepoFacts[]> {
280
+ const repos: WatchedRepoFacts[] = [];
281
+ for (const entry of config.repos) {
282
+ const expanded = expandTilde(entry.path, home);
283
+ const toplevel = await io.git(expanded, ["rev-parse", "--show-toplevel"]);
284
+ if (!toplevel.ok) {
285
+ throw new CliError(
286
+ `watch.json repo ${entry.path} is not a git repository ` +
287
+ `(${expanded}): ${toplevel.stderr.trim()}`,
288
+ );
289
+ }
290
+ const repoRoot = toplevel.stdout.trim();
291
+ const repoHome = await resolveRepoHome({
292
+ home,
293
+ operatorRoot: repoRoot,
294
+ persist: false,
295
+ });
296
+ const runsRoot = repoHome.paths.runs;
297
+ // One unreadable run dir must not stop the other repos. The repo whose
298
+ // reviewed-local set cannot be read is left out of this tick entirely, so
299
+ // nothing is launched for it (a misread would re-review and re-bill); the
300
+ // error is logged every tick until the operator fixes that run dir.
301
+ let runDirs: Awaited<ReturnType<typeof scanRunDirs>>;
302
+ try {
303
+ runDirs = await scanRunDirs(runsRoot);
304
+ } catch (error) {
305
+ if (!(error instanceof CliError)) throw error;
306
+ log(`watch: skipping ${entry.path} this tick: ${error.message}`);
307
+ continue;
308
+ }
309
+ const prs = parsePrList(await io.ghPrList(repoRoot));
310
+
311
+ // The remote guard costs one gh call per PR, so it only runs for
312
+ // candidates the free checks have not already killed — the pure
313
+ // decision treats an unfetched PR as unguarded. "Free" depends on the
314
+ // re-arm policy: under on_push only a SAME-head local review kills a
315
+ // candidate, while the one-review-per-PR default is done after ANY
316
+ // local review of that number (reviewed-prior-head from local facts
317
+ // alone), so its comments fetch is skipped too.
318
+ //
319
+ // `.prheroignore` is read ONCE per repo, here, from the operator's own
320
+ // working tree — never a base ref. This is NOT the CI base-ref case
321
+ // (design D1-D3, cli.ts): CI reads from a ref the PR author cannot
322
+ // influence because the PR author supplies the checkout being reviewed.
323
+ // The watcher runs from an OPERATOR's own machine, against repos that
324
+ // operator explicitly opted into `pr-hero watch add` — there is no PR
325
+ // author supplying this checkout, so the operator's own working tree IS
326
+ // the trusted source here, the same way local (non-CI) review already
327
+ // treats it (O-8). Do not "harden" this into a base-ref read; that would
328
+ // require a `gh`/git fetch per repo per tick this mode has no PR context
329
+ // to anchor, and would re-break the CLI-mode-vs-watcher parity found by
330
+ // pr-hero's own review of PR #204 (CRITICAL, blocking) — the reason
331
+ // this fix exists at all. The merged rule set (builtins + this repo's
332
+ // `.prheroignore`) is built through the SAME sizeGateConfig() the CLI
333
+ // paths use, so the watcher's gate agrees with what a real review would
334
+ // decide, and it is carried on WatchedRepoFacts.excludeRules so the
335
+ // pre-launch veto below can reuse it without a second read.
336
+ const userIgnore = await io.readIgnoreFile(repoRoot);
337
+ const gateConfig = sizeGateConfig(
338
+ {
339
+ maxChangedLines: entry.maxChangedLines,
340
+ maxChangedFiles: entry.maxChangedFiles,
341
+ },
342
+ undefined,
343
+ userIgnore.rules,
344
+ );
345
+ const remoteHeads: { pr: number; heads: string[]; markerSeen: boolean }[] =
346
+ [];
347
+ const tooLarge: number[] = [];
348
+ const nothingToReview: number[] = [];
349
+ const inFlight: { pr: number; head: string }[] = [];
350
+ const pending: { pr: number; head: string }[] = [];
351
+ const nowMs = Date.now();
352
+ for (const candidate of prs) {
353
+ if (candidate.isDraft) continue;
354
+ const locallyBlocked = runDirs.localReviews.some(
355
+ (r) =>
356
+ r.pr === candidate.pr && (r.head === candidate.head || !entry.onPush),
357
+ );
358
+ if (locallyBlocked) continue;
359
+ // The size gate, TIERED, same frugality rule as the comments fetch
360
+ // below: `gh pr list` already handed us GitHub's aggregate counters,
361
+ // so a PR under both limits by its aggregate is settled for FREE —
362
+ // exclusions can only ever make it smaller. Only a PR whose aggregate
363
+ // exceeds a limit is worth a second call, and then the per-file list
364
+ // is fetched so an excluded lockfile can still rescue it.
365
+ //
366
+ // BOTH tiers are whitespace-NAIVE, and nothing here can fix that:
367
+ // GitHub's aggregate counters and `gh pr view --json files` alike carry
368
+ // no whitespace information, so a formatter sweep counts in full where
369
+ // the real git-side gate (cli.ts, `git diff -w --ignore-blank-lines`)
370
+ // counts zero. The error is one-directional — the watcher can only
371
+ // OVER-count and therefore only over-skip, never under-skip — and the
372
+ // spawned review re-runs the real gate on real git data anyway.
373
+ //
374
+ // Recomputed from live counters on EVERY tick and never persisted: a
375
+ // force-push that shrinks the PR must make it eligible again next
376
+ // tick (constraint (b) on candidateSkipReason).
377
+ if (
378
+ !evaluateSizeGateAggregate(
379
+ {
380
+ files: candidate.changedFiles,
381
+ insertions: candidate.additions,
382
+ deletions: candidate.deletions,
383
+ },
384
+ gateConfig,
385
+ ).ok
386
+ ) {
387
+ const perFile = parsePrFiles(
388
+ await io.ghPrFiles(repoRoot, candidate.pr),
389
+ );
390
+ // gh's `files` list can be truncated on a very large PR. A short
391
+ // list under-counts, and under-counting here FALSELY RESCUES exactly
392
+ // the monster the gate exists to stop — so a count that disagrees
393
+ // with GitHub's own changedFiles is not trusted to rescue anything.
394
+ const trustworthy = perFile.length >= candidate.changedFiles;
395
+ const verdict = evaluateSizeGate(perFile, gateConfig);
396
+ if (!trustworthy || !verdict.ok) {
397
+ tooLarge.push(candidate.pr);
398
+ // No comments fetch for a PR that is already skipped — the pure
399
+ // decision reads an unfetched PR as unguarded, and too-large
400
+ // fires before the remote checks.
401
+ continue;
402
+ }
403
+ // Rescued by the exclusions, but rescued into NOTHING: every changed
404
+ // file was generated content. Spawning would have the child exit on
405
+ // an empty effective diff before it creates a run dir, and with no
406
+ // run dir there is no attempt to count — so the same PR would be
407
+ // re-spawned every tick. Settle it here instead.
408
+ if (verdict.effectiveFiles === 0) {
409
+ nothingToReview.push(candidate.pr);
410
+ continue;
411
+ }
412
+ }
413
+ const comments = await fetchPrComments(repoRoot, candidate.pr);
414
+ remoteHeads.push({
415
+ pr: candidate.pr,
416
+ heads: markerDeclaredHeads(comments),
417
+ markerSeen: markerCommentSeen(comments),
418
+ });
419
+ const statuses = await fetchCommitStatuses(repoRoot, candidate.head);
420
+ // The watcher's own leftover pending is local-only (T3 S7): it settles
421
+ // only what it posted. A pending on pr-hero is a CI run's to finish.
422
+ const latest = latestStatusInContext(
423
+ statuses,
424
+ LOCAL_COMMIT_STATUS_CONTEXT,
425
+ );
426
+ if (latest?.state === "pending") {
427
+ pending.push({ pr: candidate.pr, head: candidate.head });
428
+ }
429
+ // In flight on EITHER context: CI's gate or a local run already reviewing
430
+ // this head is a reason to launch nothing here (T3 S7).
431
+ if (
432
+ isInFlightCommitStatus(
433
+ statuses,
434
+ nowMs,
435
+ IN_FLIGHT_TTL_MS,
436
+ RUN_STATUS_CONTEXTS,
437
+ )
438
+ ) {
439
+ inFlight.push({ pr: candidate.pr, head: candidate.head });
440
+ }
441
+ }
442
+
443
+ repos.push({
444
+ path: repoRoot,
445
+ post: entry.post,
446
+ onPush: entry.onPush,
447
+ prs,
448
+ localReviews: runDirs.localReviews,
449
+ remoteHeads,
450
+ attempts: prs.map((candidate) => ({
451
+ pr: candidate.pr,
452
+ head: candidate.head,
453
+ count: countAttempts(runDirs.facts, candidate.pr, candidate.head),
454
+ })),
455
+ tooLarge,
456
+ nothingToReview,
457
+ inFlight,
458
+ pending,
459
+ runsRoot,
460
+ maxChangedLines: entry.maxChangedLines,
461
+ maxChangedFiles: entry.maxChangedFiles,
462
+ excludeRules: gateConfig.excludeRules,
463
+ });
464
+ }
465
+ return repos;
466
+ }
467
+
468
+ // One level deep: run dirs are flat children of the runs root. The
469
+ // reviewed-local set comes from each dir's findings.json, read through the
470
+ // same validator the post and triage verbs use — the set must come from parsed
471
+ // artifact fields (pr + head_sha), never from directory names. A run counts
472
+ // only when it is a PR review (pr > 0) that did not fail its session: a
473
+ // sessionFailed run never reached a verdict, and a local run (pr 0) names no
474
+ // PR to dedupe against. pipeline.json feeds the tolerant attempts counter (see
475
+ // the WHY on countAttempts in watch/preflight.ts).
476
+ export async function scanRunDirs(runsRoot: string): Promise<{
477
+ facts: RunDirFact[];
478
+ localReviews: { pr: number; head: string }[];
479
+ }> {
480
+ const facts: RunDirFact[] = [];
481
+ const localReviews: { pr: number; head: string }[] = [];
482
+ if (!existsSync(runsRoot)) return { facts, localReviews };
483
+ for (const entry of await readdir(runsRoot, { withFileTypes: true })) {
484
+ if (!entry.isDirectory()) continue;
485
+ const dir = path.join(runsRoot, entry.name);
486
+ const findingsPath = path.join(dir, "findings.json");
487
+ if (existsSync(findingsPath)) {
488
+ try {
489
+ const doc = validateFindingsDocument(
490
+ JSON.parse(await Bun.file(findingsPath).text()),
491
+ );
492
+ // An absent sessionFailed means "unknown" (findings.ts). Same
493
+ // back-compat rule as commands/post.ts: fall back to run_status, so a
494
+ // legacy "complete" document still counts and any other is retried.
495
+ const failed = doc.sessionFailed ?? doc.run_status !== "complete";
496
+ if (doc.pr > 0 && !failed) {
497
+ localReviews.push({ pr: doc.pr, head: doc.head_sha });
498
+ }
499
+ } catch (error) {
500
+ // Loud on purpose: a mis-read findings.json would silently re-review
501
+ // (and re-bill) a PR. The message leads with the file so the operator
502
+ // knows which run to inspect.
503
+ const reason = error instanceof Error ? error.message : String(error);
504
+ throw new CliError(`${findingsPath}: ${reason}`);
505
+ }
506
+ }
507
+ const pipelinePath = path.join(dir, "pipeline.json");
508
+ facts.push({
509
+ name: entry.name,
510
+ pipelineMeta: existsSync(pipelinePath)
511
+ ? parsePipelineMeta(await Bun.file(pipelinePath).text())
512
+ : null,
513
+ });
514
+ }
515
+ return { facts, localReviews };
516
+ }
517
+
518
+ // The argv a launched review runs with, after the engine's own invocation. No
519
+ // `--ci`: the watcher is a local actor (T3 S7), so its child resolves advisory on
520
+ // pr-hero/local and can never write the gate's context. Exported so a test reads
521
+ // the real argv, not a copy of it.
522
+ export function localReviewArgv(input: {
523
+ pr: number;
524
+ post: boolean;
525
+ sizeArgs: readonly string[];
526
+ }): string[] {
527
+ return [
528
+ "review",
529
+ "--pr",
530
+ String(input.pr),
531
+ "--yes",
532
+ ...input.sizeArgs,
533
+ ...(input.post ? ["--post"] : []),
534
+ ];
535
+ }
536
+
537
+ // The settle for a leftover pending this watcher owns (T3 S7). It settles on the
538
+ // LOCAL context only: a `pr-hero` pending belongs to a CI run the watcher cannot
539
+ // grade, and a `success` written here would turn a failed CI gate green.
540
+ export function orphanPendingSettleRequest(
541
+ targetUrl: string | undefined,
542
+ ): ReturnType<typeof commitStatusRequest> {
543
+ return commitStatusRequest({
544
+ phase: "success",
545
+ posted: false,
546
+ targetUrl,
547
+ context: LOCAL_COMMIT_STATUS_CONTEXT,
548
+ });
549
+ }
550
+
551
+ // Completes a leftover pending status on a PR this tick will not launch
552
+ // again. Fail-soft: a yellow dot is worse than silence, a thrown tick is
553
+ // worse than a yellow dot. Dry-run never calls this (runTick is live only).
554
+ async function settleOrphanPendings(
555
+ repos: WatchedRepoFacts[],
556
+ skips: TickDecision["skips"],
557
+ ): Promise<void> {
558
+ for (const job of pendingReviewsToSettle(skips, repos)) {
559
+ try {
560
+ const targetUrl = prHtmlUrl(await ghRepoWebUrl(job.repo), job.pr);
561
+ await postCommitStatus(
562
+ job.repo,
563
+ job.head,
564
+ orphanPendingSettleRequest(targetUrl),
565
+ );
566
+ } catch {
567
+ // Leave the pending in place; the next live tick will try again.
568
+ }
569
+ }
570
+ }
571
+
572
+ export interface PreLaunchVetoResult {
573
+ launch: TickLaunch | null;
574
+ vetoed: boolean;
575
+ }
576
+
577
+ // The pre-launch veto's impure half (design D6): orchestrates the ONE
578
+ // ghPrFiles call the pure preLaunchExclusionVeto (watch/preflight.ts) needs,
579
+ // for the CHOSEN launch only, then re-decides. `io` is narrowed to just
580
+ // ghPrFiles — the only I/O this needs — so tests never have to stub the
581
+ // rest of WatchIo to exercise it.
582
+ export async function applyPreLaunchVeto(
583
+ io: Pick<WatchIo, "ghPrFiles">,
584
+ launch: TickLaunch,
585
+ repos: readonly WatchedRepoFacts[],
586
+ ): Promise<PreLaunchVetoResult> {
587
+ const repo = repos.find((r) => r.path === launch.repo);
588
+ const candidate = repo?.prs.find(
589
+ (c) => c.pr === launch.pr && c.head === launch.head,
590
+ );
591
+ // Unreachable in production: `launch` always comes from decideTick(repos),
592
+ // so it is derived FROM this same repos array. Kept as a defensive
593
+ // fail-open rather than a non-null assertion, because a launch this
594
+ // function cannot place is exactly the kind of surprise that must never
595
+ // block a review it has no evidence against.
596
+ if (repo === undefined || candidate === undefined) {
597
+ return { launch, vetoed: false };
598
+ }
599
+ let perFile: NumstatFile[];
600
+ try {
601
+ perFile = parsePrFiles(await io.ghPrFiles(repo.path, launch.pr));
602
+ } catch {
603
+ // Fails open (D6): the size gate's own WHY above (gatherRepoFacts) already
604
+ // treats an unfetched PR as unguarded, and the CLI gate stays the backstop
605
+ // (see the WHY on sizeArgs in runTick). Failing closed here would
606
+ // silently re-create the exact daily-cap burn this veto exists to stop.
607
+ return { launch, vetoed: false };
608
+ }
609
+ const gateConfig: SizeGateConfig = {
610
+ maxChangedLines: repo.maxChangedLines,
611
+ maxChangedFiles: repo.maxChangedFiles,
612
+ excludeRules: repo.excludeRules,
613
+ };
614
+ const vetoed = preLaunchExclusionVeto(
615
+ perFile,
616
+ candidate.changedFiles,
617
+ gateConfig,
618
+ );
619
+ return { launch: vetoed ? null : launch, vetoed };
620
+ }
621
+
622
+ // How many candidates one tick will veto before it gives up and launches
623
+ // nothing. WHY a cap exists at all, and WHY this number (paid for by
624
+ // pr-hero's own review of PR #205, BLOCKER): the fall-through below is what
625
+ // stops the veto from starving the queue, but an UNBOUNDED fall-through
626
+ // turns a single tick into one `gh pr view` per open PR — a dependabot
627
+ // flood, or any repo whose front-of-queue is a run of lockfile bumps, would
628
+ // have every tick spend the whole GitHub budget walking the same list.
629
+ //
630
+ // 5 is anchored to cost, not to taste: it bounds the veto's added spend at 5
631
+ // `gh pr view` calls per tick, against the tick's ALREADY per-candidate
632
+ // `gh pr list` + comments + statuses traffic, and it is comfortably longer
633
+ // than any realistic run of consecutive all-excluded PRs at the low-numbered
634
+ // end of the queue.
635
+ //
636
+ // The ACCEPTED tradeoff, stated so the next reader does not rediscover it as
637
+ // a bug: with more than 5 all-excluded PRs ahead of a reviewable one, the
638
+ // reviewable one is still starved — bounded per tick, but stably, tick after
639
+ // tick, because nothing here is persisted. That is deliberate. The forbidden
640
+ // alternative is the unbounded loop; the other alternative, remembering the
641
+ // veto across ticks, is ruled out by constraint (b) on candidateSkipReason
642
+ // (a force-push that shrinks a PR must make it eligible again NEXT tick), so
643
+ // no veto verdict may survive the tick that computed it. A repo that hits
644
+ // this cap has a systemic flood that one launch slot per tick cannot fix
645
+ // anyway; the `tick veto-cap-reached` log line is how the operator sees it.
646
+ export const PRE_LAUNCH_VETO_MAX_ATTEMPTS = 5;
647
+
648
+ export interface LaunchSelection {
649
+ launch: TickLaunch | null;
650
+ // Every candidate this tick vetoed, in the order they were considered —
651
+ // runTick logs one skip line each. Never persisted anywhere (constraint
652
+ // (b) above); a vetoed PR is re-examined from live counters next tick.
653
+ vetoed: TickLaunch[];
654
+ capReached: boolean;
655
+ }
656
+
657
+ // The fix for the #205 LIVELOCK, and the whole reason this sits between
658
+ // decideTick and the spawn. decideTick returns at most ONE launch per tick
659
+ // ACROSS ALL configured repos (`eligible[0]`, ascending by PR number). The
660
+ // veto as first built turned that single slot into `null` and the tick
661
+ // returned 0 — so an all-excluded PR that is nevertheless ELIGIBLE (its
662
+ // aggregate is under both limits, so gatherRepoFacts's tier 2 never fetches
663
+ // its file list and `nothingToReview` cannot see it) won the slot, was
664
+ // vetoed, wrote no artifact any later tick could read back, and did it all
665
+ // again on the next tick, forever — starving every other eligible PR in
666
+ // every configured repo. The veto swapped "launch and waste the slot" for
667
+ // "veto and waste the slot".
668
+ //
669
+ // So: fall through to the next eligible candidate INSIDE the same tick. The
670
+ // vetoed PR still costs one `ghPrFiles` call every tick forever, which is
671
+ // accepted — it is far cheaper than the per-tick spawn it replaced, and it
672
+ // is the only shape compatible with never persisting the verdict.
673
+ //
674
+ // applyPreLaunchVeto stays strictly per-candidate (it never sees the list):
675
+ // its fail-open contract on a `ghPrFiles` failure is per-PR reasoning, and
676
+ // widening it to the queue would make that contract answer a question it
677
+ // has no evidence for.
678
+ export async function selectLaunchAfterVeto(
679
+ io: Pick<WatchIo, "ghPrFiles">,
680
+ eligible: readonly TickLaunch[],
681
+ repos: readonly WatchedRepoFacts[],
682
+ ): Promise<LaunchSelection> {
683
+ const vetoed: TickLaunch[] = [];
684
+ for (const candidate of eligible) {
685
+ // Checked BEFORE the call, so the cap bounds gh calls and not merely
686
+ // vetoes. It can only fire with a candidate still unconsidered, which is
687
+ // exactly when "launched nothing" is a decision rather than an empty
688
+ // queue — hence capReached, which runTick logs.
689
+ if (vetoed.length >= PRE_LAUNCH_VETO_MAX_ATTEMPTS) {
690
+ return { launch: null, vetoed, capReached: true };
691
+ }
692
+ const result = await applyPreLaunchVeto(io, candidate, repos);
693
+ if (!result.vetoed)
694
+ return { launch: result.launch, vetoed, capReached: false };
695
+ vetoed.push(candidate);
696
+ }
697
+ return { launch: null, vetoed, capReached: false };
698
+ }
699
+
700
+ async function runTick(
701
+ paths: PrheroHomePaths,
702
+ decision: TickDecision,
703
+ repos: WatchedRepoFacts[],
704
+ ghPrFilesFn: WatchIo["ghPrFiles"],
705
+ ): Promise<number> {
706
+ await appendLog(
707
+ paths.logPath,
708
+ logLine(localIsoTimestamp(new Date()), "tick start"),
709
+ );
710
+ for (const skip of decision.skips) {
711
+ await appendLog(
712
+ paths.logPath,
713
+ skipLine(
714
+ localIsoTimestamp(new Date()),
715
+ path.basename(skip.repo),
716
+ skip.pr,
717
+ skip.head,
718
+ skip.reason,
719
+ ),
720
+ );
721
+ }
722
+ await settleOrphanPendings(repos, decision.skips);
723
+
724
+ // Pre-launch exclusion veto (design D6, prheroignore Phase 6, built after
725
+ // pr-hero's own review of PR #204 flagged the shape of this gap): a PR
726
+ // whose files are ALL excluded generated content but whose AGGREGATE is
727
+ // under both limits never reaches gatherRepoFacts's tier-2 per-file fetch,
728
+ // so `nothingToReview` cannot see it there. Without this veto it launches,
729
+ // the CLI exits on the empty effective diff before createPrRunDir, and it
730
+ // relaunches every tick — $0 each time, but `launched` is logged at spawn
731
+ // (below) BEFORE that exit, so it burns the daily cap and the tick's one
732
+ // launch slot reviewing nothing. An extra ghPrFiles call per candidate
733
+ // considered — at most PRE_LAUNCH_VETO_MAX_ATTEMPTS of them, see
734
+ // selectLaunchAfterVeto — buys the same rescue tier 2 already gives a PR
735
+ // whose aggregate happened to exceed a limit; applyPreLaunchVeto carries
736
+ // the fail-open contract on a ghPrFiles failure.
737
+ //
738
+ // The WHOLE eligible queue goes in, NOT `[decision.launch]`: passing the
739
+ // single chosen launch would leave every unit test on selectLaunchAfterVeto
740
+ // green while the fall-through — the actual fix for the #205 livelock —
741
+ // was dead in production. `decision.launch === null` still short-circuits,
742
+ // because a closed window or a spent daily cap leaves `eligible` populated
743
+ // while nothing at all may launch.
744
+ const selection: LaunchSelection =
745
+ decision.launch === null
746
+ ? { launch: null, vetoed: [], capReached: false }
747
+ : await selectLaunchAfterVeto(
748
+ { ghPrFiles: ghPrFilesFn },
749
+ decision.eligible,
750
+ repos,
751
+ );
752
+ for (const vetoed of selection.vetoed) {
753
+ await appendLog(
754
+ paths.logPath,
755
+ skipLine(
756
+ localIsoTimestamp(new Date()),
757
+ path.basename(vetoed.repo),
758
+ vetoed.pr,
759
+ vetoed.head,
760
+ "nothing-to-review",
761
+ ),
762
+ );
763
+ }
764
+ if (selection.capReached) {
765
+ await appendLog(
766
+ paths.logPath,
767
+ logLine(
768
+ localIsoTimestamp(new Date()),
769
+ `tick veto-cap-reached attempts=${PRE_LAUNCH_VETO_MAX_ATTEMPTS}`,
770
+ ),
771
+ );
772
+ }
773
+ // ONE count, used by BOTH tick-end lines. They diverged the moment the
774
+ // fall-through landed: the old single-candidate veto nulled the launch
775
+ // whenever it fired, so `launched=1` was unreachable with a vetoed
776
+ // candidate and the two branches could not disagree. `selectLaunchAfterVeto`
777
+ // makes `launch !== null` and `vetoed.length > 0` coexist BY DESIGN — it is
778
+ // the headline case, a lower-numbered PR vetoed and a higher-numbered one
779
+ // launched in the same tick — and the launched branch was still reporting
780
+ // the pre-fall-through count.
781
+ //
782
+ // Computed once rather than corrected in place: two call sites deriving the
783
+ // same number is what let them drift, and the operator's only window into a
784
+ // tick is this log.
785
+ const skippedThisTick = decision.skips.length + selection.vetoed.length;
786
+ const launch = selection.launch;
787
+ if (launch === null) {
788
+ await appendLog(
789
+ paths.logPath,
790
+ logLine(
791
+ localIsoTimestamp(new Date()),
792
+ `tick end launched=0 skipped=${skippedThisTick}`,
793
+ ),
794
+ );
795
+ return 0;
796
+ }
797
+
798
+ const repoBase = path.basename(launch.repo);
799
+ // The launched repo's own size-gate thresholds, forwarded to the spawn.
800
+ // NOT optional: the spawned CLI runs the gate AGAIN, on the real git
801
+ // numstat, and without these it would use DEFAULT_SIZE_GATE — so a repo
802
+ // configured with a RAISED threshold would pass the watch tier, get
803
+ // launched, and then be refused by the CLI's default. That refusal
804
+ // happens before createPrRunDir, so it leaves no run dir, so the attempts
805
+ // guard never sees it: the same PR would be relaunched every tick and eat
806
+ // the whole daily cap, every day, reviewing nothing.
807
+ //
808
+ // Deliberately NOT --force: the CLI gate stays live as the backstop (it
809
+ // sees the true diff, not GitHub's counters). It just has to agree with
810
+ // this tick on what the limits are.
811
+ const launched = repos.find((r) => r.path === launch.repo);
812
+ const sizeArgs =
813
+ launched === undefined
814
+ ? []
815
+ : [
816
+ "--max-changed-lines",
817
+ String(launched.maxChangedLines),
818
+ "--max-changed-files",
819
+ String(launched.maxChangedFiles),
820
+ ];
821
+ // Append-BEFORE-spawn, the fail-safe direction: if the tick crashes with
822
+ // the review in flight, the launch must already be on the books — an
823
+ // over-counted cap skips one review, an under-counted cap is unbounded
824
+ // spend. This line is also what makes preflight-failing spawns (which
825
+ // leave no run dir for the attempts guard to see) cost at most
826
+ // daily_cap launches a day.
827
+ await appendLog(
828
+ paths.logPath,
829
+ launchedLine(
830
+ localIsoTimestamp(new Date()),
831
+ launch.pr,
832
+ repoBase,
833
+ launch.head,
834
+ ),
835
+ );
836
+
837
+ // The engine re-invoking ITSELF, through the one resolver that knows how:
838
+ // under launchd there is no user PATH, so a bare `pr-hero` (or a bare
839
+ // `bun`) resolves in every terminal and in nothing launchd starts — and a
840
+ // hand-built `[execPath, <dir>/cli.ts]` pair names a script the compiled
841
+ // binary does not carry, which is the tick spawning a review that could
842
+ // never start.
843
+ const self = selfInvocation();
844
+ const proc = Bun.spawn(
845
+ [
846
+ self.command,
847
+ ...self.args,
848
+ ...localReviewArgv({ pr: launch.pr, post: launch.post, sizeArgs }),
849
+ ],
850
+ {
851
+ cwd: launch.repo,
852
+ stdin: "ignore",
853
+ // Inherit, explicitly: the review's progress goes wherever the tick's
854
+ // own stderr goes (launchd.log under launchd), and an unread pipe
855
+ // would fill and stall a long review. watch.log stays append-only by
856
+ // construction — nothing streams into it.
857
+ stdout: "inherit",
858
+ stderr: "inherit",
859
+ },
860
+ );
861
+ const exitCode = await proc.exited;
862
+
863
+ const outcome: ReviewOutcome = {
864
+ pr: launch.pr,
865
+ ok: exitCode === 0,
866
+ exitCode,
867
+ counts:
868
+ exitCode === 0
869
+ ? await readTierCounts(launched?.runsRoot, launch.pr, launch.head)
870
+ : null,
871
+ };
872
+ await appendLog(
873
+ paths.logPath,
874
+ outcomeLine(localIsoTimestamp(new Date()), repoBase, outcome),
875
+ );
876
+ await notify("crysk", outcomeNotificationText(outcome));
877
+ await appendLog(
878
+ paths.logPath,
879
+ logLine(
880
+ localIsoTimestamp(new Date()),
881
+ `tick end launched=1 skipped=${skippedThisTick}`,
882
+ ),
883
+ );
884
+ return 0;
885
+ }
886
+
887
+ // The finding counts for the notification — cosmetic by contract, so every
888
+ // failure path degrades to null and the notification says "counts
889
+ // unavailable" instead of the tick dying over decoration.
890
+ async function readTierCounts(
891
+ runsRoot: string | undefined,
892
+ pr: number,
893
+ headSha: string,
894
+ ): Promise<{ blocking: number; advisory: number } | null> {
895
+ try {
896
+ if (runsRoot === undefined || !existsSync(runsRoot)) return null;
897
+ const names = (await readdir(runsRoot, { withFileTypes: true }))
898
+ .filter((entry) => entry.isDirectory())
899
+ .map((entry) => entry.name);
900
+ const latest = latestRunDirName(names, pr, headSha);
901
+ if (latest === null) return null;
902
+ const parsed: unknown = await Bun.file(
903
+ path.join(runsRoot, latest, "findings.json"),
904
+ ).json();
905
+ return findingsTierCounts(parsed);
906
+ } catch {
907
+ return null;
908
+ }
909
+ }
910
+
911
+ async function notify(title: string, text: string): Promise<void> {
912
+ // macOS only; elsewhere the notification is silently skipped (the log
913
+ // line above already carries the outcome).
914
+ if (process.platform !== "darwin") return;
915
+ try {
916
+ await run(osascriptNotifyArgs(title, text));
917
+ } catch {
918
+ // Cosmetic by contract — a broken osascript must never fail the tick.
919
+ }
920
+ }
921
+
922
+ async function appendLog(logPath: string, line: string): Promise<void> {
923
+ await appendFile(logPath, `${line}\n`);
924
+ }
925
+
926
+ // The PID in the lockfile if it names a LIVE process, else null (no file,
927
+ // unreadable, or dead holder — all mean "take the lock"). EPERM means the
928
+ // process exists but is not ours: alive.
929
+ async function lockHolder(lockPath: string): Promise<number | null> {
930
+ if (!existsSync(lockPath)) return null;
931
+ const pid = parseLockPid(await Bun.file(lockPath).text());
932
+ if (pid === null) return null;
933
+ try {
934
+ process.kill(pid, 0);
935
+ return pid;
936
+ } catch (error) {
937
+ return (error as NodeJS.ErrnoException).code === "EPERM" ? pid : null;
938
+ }
939
+ }
940
+
941
+ // Rendered through the same src/ui/primitives.ts primitives as the review plan card, on
942
+ // purpose: two surfaces that answer the same question ("what would this
943
+ // spend?") that look nothing alike cost the reader a re-orientation every
944
+ // time they switch.
945
+ function printDryRun(
946
+ paths: PrheroHomePaths,
947
+ config: WatchConfig,
948
+ launchedToday: number,
949
+ decision: TickDecision,
950
+ repos: WatchedRepoFacts[],
951
+ ): void {
952
+ // Both impure decisions are made HERE, at the shell boundary, and handed
953
+ // down as values — ui.ts's contract. This printer is the shell, so it is
954
+ // allowed to sniff; row() and box() are not, which is why width is now a
955
+ // required option rather than one they fill in behind the caller's back.
956
+ const styles = styleEnabled();
957
+ const width = terminalWidth();
958
+ const emit = (label: string, value: string): void => {
959
+ for (const line of row(label, value, { styles, width })) log(line);
960
+ };
961
+ for (const line of box(
962
+ "crysk · watch",
963
+ [
964
+ "dry run — nothing spawned, logged, or locked",
965
+ `${config.repos.length} repo(s) · ${launchedToday}/${config.dailyCap} ` +
966
+ "launches used today",
967
+ ],
968
+ { styles, width },
969
+ )) {
970
+ log(line);
971
+ }
972
+ log();
973
+ emit("CONFIG", shortPath(paths.watchConfigPath));
974
+ emit(
975
+ "WINDOW",
976
+ config.window === null
977
+ ? "always"
978
+ : `${config.window.start}-${config.window.end}`,
979
+ );
980
+ emit("GATE", decision.gate);
981
+ for (const repo of repos) {
982
+ log();
983
+ log(` ${section(shortPath(repo.path), styles)}`);
984
+ if (repo.prs.length === 0) {
985
+ log(" no open PRs");
986
+ continue;
987
+ }
988
+ for (const candidate of repo.prs) {
989
+ const skip = decision.skips.find(
990
+ (s) =>
991
+ s.repo === repo.path &&
992
+ s.pr === candidate.pr &&
993
+ s.head === candidate.head,
994
+ );
995
+ log(
996
+ ` pr ${candidate.pr} head ${shortSha(candidate.head, 8)} — ` +
997
+ (skip === undefined ? "eligible" : `skip: ${skip.reason}`),
998
+ );
999
+ }
1000
+ }
1001
+ log();
1002
+ if (decision.launch !== null) {
1003
+ emit(
1004
+ "LAUNCH",
1005
+ `pr ${decision.launch.pr} in ${shortPath(decision.launch.repo)}` +
1006
+ ` (review --pr ${decision.launch.pr} --yes` +
1007
+ `${decision.launch.post ? " --post" : ""})`,
1008
+ );
1009
+ } else if (decision.gate !== "open") {
1010
+ emit("LAUNCH", `nothing — gate is ${decision.gate}`);
1011
+ } else {
1012
+ emit("LAUNCH", "nothing — no eligible (pr, head)");
1013
+ }
1014
+ if (decision.eligible.length > 1) {
1015
+ emit(
1016
+ "WAITING",
1017
+ decision.eligible
1018
+ .slice(1)
1019
+ .map((e) => `pr ${e.pr} (${path.basename(e.repo)})`)
1020
+ .join(", "),
1021
+ );
1022
+ }
1023
+ }
1024
+
1025
+ // ---------------------------------------------------------------------------
1026
+ // launchd install/uninstall (macOS). Both idempotent, both loud about what
1027
+ // they did; the plist body itself is pure (renderWatchPlist).
1028
+
1029
+ async function watchInstall(intervalMin: number): Promise<number> {
1030
+ if (process.platform !== "darwin") {
1031
+ throw new CliError(
1032
+ "watch install renders a macOS launchd agent. On other systems run " +
1033
+ "`crysk watch --once` from cron — the lockfile covers overlap.",
1034
+ );
1035
+ }
1036
+ // Checked before any write, so a refused install leaves nothing on disk.
1037
+ const invocation = selfInvocation();
1038
+ if (isNpxCacheInvocation(invocation)) {
1039
+ throw new CliError(NPX_REGISTRATION_REFUSED);
1040
+ }
1041
+ const paths = prheroHomePaths(os.homedir());
1042
+ await mkdir(paths.dir, { recursive: true });
1043
+ await mkdir(path.dirname(paths.plistPath), { recursive: true });
1044
+ const plist = renderWatchPlist({
1045
+ invocation,
1046
+ intervalSeconds: intervalMin * 60,
1047
+ logPath: paths.launchdLogPath,
1048
+ pathEnv: process.env.PATH ?? "",
1049
+ });
1050
+ // Unload first so a re-install refreshes the running definition; launchd
1051
+ // ignores rewrites of a loaded plist until the next load.
1052
+ if (existsSync(paths.plistPath)) {
1053
+ const unloaded = await run(["launchctl", "unload", "-w", paths.plistPath]);
1054
+ log(
1055
+ unloaded.ok
1056
+ ? `unloaded previous ${WATCH_LAUNCHD_LABEL}`
1057
+ : "previous plist present but not loaded (fine, replacing it)",
1058
+ );
1059
+ }
1060
+ await retireLegacyAgent({
1061
+ home: os.homedir(),
1062
+ legacyLabel: LEGACY_WATCH_LAUNCHD_LABEL,
1063
+ run,
1064
+ log,
1065
+ });
1066
+ await Bun.write(paths.plistPath, plist);
1067
+ const loaded = await run(["launchctl", "load", "-w", paths.plistPath]);
1068
+ if (!loaded.ok) {
1069
+ throw new CliError(
1070
+ `launchctl load -w ${paths.plistPath} failed: ${loaded.stderr.trim()}`,
1071
+ );
1072
+ }
1073
+ log(`wrote ${paths.plistPath}`);
1074
+ log(`loaded ${WATCH_LAUNCHD_LABEL} — one tick every ${intervalMin} min`);
1075
+ log(`tick output: ${paths.launchdLogPath}`);
1076
+ log(`event log: ${paths.logPath}`);
1077
+ if (!existsSync(paths.watchConfigPath)) {
1078
+ log();
1079
+ log(
1080
+ `NOTE: no ${paths.watchConfigPath} yet — ticks will fail until a repo is ` +
1081
+ "opted in. Run `crysk watch add` inside the repo to watch.",
1082
+ );
1083
+ }
1084
+ return 0;
1085
+ }
1086
+
1087
+ async function watchUninstall(): Promise<number> {
1088
+ if (process.platform !== "darwin") {
1089
+ throw new CliError(
1090
+ "watch uninstall manages a macOS launchd agent; there is nothing to " +
1091
+ "uninstall on this system.",
1092
+ );
1093
+ }
1094
+ const paths = prheroHomePaths(os.homedir());
1095
+ await retireLegacyAgent({
1096
+ home: os.homedir(),
1097
+ legacyLabel: LEGACY_WATCH_LAUNCHD_LABEL,
1098
+ run,
1099
+ log,
1100
+ });
1101
+ if (!existsSync(paths.plistPath)) {
1102
+ log(`nothing installed (no ${paths.plistPath})`);
1103
+ return 0;
1104
+ }
1105
+ const unloaded = await run(["launchctl", "unload", "-w", paths.plistPath]);
1106
+ log(
1107
+ unloaded.ok
1108
+ ? `unloaded ${WATCH_LAUNCHD_LABEL}`
1109
+ : `plist present but not loaded: ${unloaded.stderr.trim() || "(no detail)"}`,
1110
+ );
1111
+ await rm(paths.plistPath, { force: true });
1112
+ log(`removed ${paths.plistPath}`);
1113
+ return 0;
1114
+ }
1115
+
1116
+ // ---------------------------------------------------------------------------
1117
+ // Config management (add/remove) and the read-only status view. The config
1118
+ // file is machine-owned through these verbs so nobody hand-edits JSON; every
1119
+ // decision (upsert, removal, rendering) is pure in watch/preflight.ts.
1120
+
1121
+ async function watchAdd(options: CliOptions): Promise<number> {
1122
+ const repoRoot = await resolveRepoRoot(options.repo);
1123
+ const home = os.homedir();
1124
+ const paths = prheroHomePaths(home);
1125
+ const raw = existsSync(paths.watchConfigPath)
1126
+ ? await Bun.file(paths.watchConfigPath).text()
1127
+ : null;
1128
+ const result = upsertWatchRepo(
1129
+ raw,
1130
+ repoRoot,
1131
+ {
1132
+ post: options.post ?? false,
1133
+ onPush: options.onPush,
1134
+ // Same disclosed reset semantics as post/on_push: an absent flag
1135
+ // records the shipped default rather than preserving the old value —
1136
+ // `watch add` states the whole intent on the command line.
1137
+ maxChangedLines:
1138
+ options.maxChangedLines ?? DEFAULT_SIZE_GATE.maxChangedLines,
1139
+ maxChangedFiles:
1140
+ options.maxChangedFiles ?? DEFAULT_SIZE_GATE.maxChangedFiles,
1141
+ },
1142
+ home,
1143
+ );
1144
+ await mkdir(paths.dir, { recursive: true });
1145
+ await Bun.write(paths.watchConfigPath, result.config);
1146
+ log(
1147
+ `${result.action} ${result.storedPath} (post=${options.post ?? false} ` +
1148
+ `on_push=${options.onPush} ` +
1149
+ `max_changed_lines=${options.maxChangedLines ?? DEFAULT_SIZE_GATE.maxChangedLines} ` +
1150
+ `max_changed_files=${options.maxChangedFiles ?? DEFAULT_SIZE_GATE.maxChangedFiles}` +
1151
+ `) in ${paths.watchConfigPath}`,
1152
+ );
1153
+ await resolveRepoHome({
1154
+ home,
1155
+ operatorRoot: repoRoot,
1156
+ persist: true,
1157
+ });
1158
+ // The same hint install prints in reverse: config without a schedule is
1159
+ // as inert as a schedule without config — but only when the plist is
1160
+ // genuinely absent, an installed watcher needs no reminder.
1161
+ if (!existsSync(paths.plistPath)) {
1162
+ log();
1163
+ log(
1164
+ "NOTE: launchd agent not installed — run `crysk watch install` to " +
1165
+ "start ticking (this is the moment automatic spending starts).",
1166
+ );
1167
+ }
1168
+ return 0;
1169
+ }
1170
+
1171
+ async function watchRemove(options: CliOptions): Promise<number> {
1172
+ const repoRoot = await resolveRepoRoot(options.repo);
1173
+ const home = os.homedir();
1174
+ const paths = prheroHomePaths(home);
1175
+ // Idempotent by contract: removing what is not there succeeds saying so —
1176
+ // a missing config file is just the emptiest way of not being listed.
1177
+ if (!existsSync(paths.watchConfigPath)) {
1178
+ log(`not listed: no ${paths.watchConfigPath} exists`);
1179
+ return 0;
1180
+ }
1181
+ const result = removeWatchRepo(
1182
+ await Bun.file(paths.watchConfigPath).text(),
1183
+ repoRoot,
1184
+ home,
1185
+ );
1186
+ if (result.action === "not-listed" || result.config === null) {
1187
+ log(`not listed: ${repoRoot} is not in ${paths.watchConfigPath}`);
1188
+ return 0;
1189
+ }
1190
+ await Bun.write(paths.watchConfigPath, result.config);
1191
+ log(`removed ${repoRoot} from ${paths.watchConfigPath}`);
1192
+ return 0;
1193
+ }
1194
+
1195
+ // $0 and read-only, and it never throws over an absent piece: no config, no
1196
+ // log, no plist and no lock are all ordinary states the report simply
1197
+ // names. Even an INVALID config renders as a status line — a status that
1198
+ // crashes on a broken setup is useless exactly when it is needed.
1199
+ async function watchStatus(): Promise<number> {
1200
+ const home = os.homedir();
1201
+ const paths = prheroHomePaths(home);
1202
+ let config: WatchConfig | null = null;
1203
+ let configError: string | null = null;
1204
+ if (existsSync(paths.watchConfigPath)) {
1205
+ try {
1206
+ config = parseWatchConfig(await Bun.file(paths.watchConfigPath).text());
1207
+ } catch (error) {
1208
+ configError = (error as Error).message;
1209
+ }
1210
+ }
1211
+ const logText = existsSync(paths.logPath)
1212
+ ? await Bun.file(paths.logPath).text()
1213
+ : "";
1214
+ const installed = existsSync(paths.plistPath);
1215
+ const activity = lastLogActivity(logText);
1216
+ const lines = renderWatchStatus({
1217
+ watchConfigPath: paths.watchConfigPath,
1218
+ config,
1219
+ configError,
1220
+ launchedToday: countLaunchedToday(
1221
+ logText,
1222
+ localIsoTimestamp(new Date()).slice(0, 10),
1223
+ ),
1224
+ plistPath: paths.plistPath,
1225
+ installed,
1226
+ intervalSeconds: installed
1227
+ ? parsePlistInterval(await Bun.file(paths.plistPath).text())
1228
+ : null,
1229
+ lockPid: await lockHolder(paths.lockPath),
1230
+ lastLaunched: activity.launched,
1231
+ lastOutcome: activity.outcome,
1232
+ });
1233
+ for (const line of lines) log(line);
1234
+ return 0;
1235
+ }