crysk 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +610 -2
  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/adjudicator-dtg2axnh.md +86 -0
  10. package/dist/admission-config.example-a9vqmmad.json +9 -0
  11. package/dist/ci-admission-camfbx2b.md +122 -0
  12. package/dist/cli.js +42292 -0
  13. package/dist/consolidate-ac0mnfyj.md +24 -0
  14. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  15. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  16. package/dist/deep-review-parity-0ec904db.md +120 -0
  17. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  18. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  19. package/dist/index.js +20190 -0
  20. package/dist/opencode-ci-7b0be64p.md +141 -0
  21. package/dist/review-refuter-j4e9gezy.md +71 -0
  22. package/dist/scout-yvp153q7.md +140 -0
  23. package/dist/summarizer-zca44nxa.md +18 -0
  24. package/dist/workflow-w1g9szna.yml +151 -0
  25. package/package.json +82 -4
  26. package/prompts/consolidate.md +24 -0
  27. package/prompts/default/PROVENANCE.md +18 -0
  28. package/prompts/default/deep-review-lifecycle.md +362 -0
  29. package/prompts/default/deep-review-logic.md +156 -0
  30. package/prompts/default/deep-review-parity.md +120 -0
  31. package/prompts/default/deep-review-reliability.md +125 -0
  32. package/prompts/default/deep-review-resilience.md +118 -0
  33. package/prompts/default/review-refuter.md +71 -0
  34. package/prompts/scout.md +140 -0
  35. package/prompts/summarizer.md +18 -0
  36. package/skills/crysk/SKILL.md +74 -0
  37. package/skills/crysk-ci-setup/SKILL.md +134 -0
  38. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  39. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  40. package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
  41. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  42. package/skills/crysk-loop/SKILL.md +496 -0
  43. package/skills/crysk-loop/adjudicator.md +86 -0
  44. package/skills/crysk-pr/SKILL.md +66 -0
  45. package/src/agent-env.ts +1084 -0
  46. package/src/asset-manifest.ts +83 -0
  47. package/src/assets.d.ts +6 -0
  48. package/src/assets.ts +183 -0
  49. package/src/brand-paths.ts +155 -0
  50. package/src/brand.ts +255 -0
  51. package/src/ci/admission-ledger.ts +350 -0
  52. package/src/ci/classify-error.ts +73 -0
  53. package/src/ci/cli-record.ts +271 -0
  54. package/src/ci/force-comment.ts +39 -0
  55. package/src/ci/gates.ts +923 -0
  56. package/src/ci/outcome.ts +2181 -0
  57. package/src/ci/override.ts +187 -0
  58. package/src/ci/publish.ts +1639 -0
  59. package/src/ci/reporter.ts +626 -0
  60. package/src/ci/review-admission.ts +901 -0
  61. package/src/ci/review-levels.ts +310 -0
  62. package/src/ci/review-policy.ts +18 -0
  63. package/src/ci/review-risk.ts +184 -0
  64. package/src/ci/setup.ts +844 -0
  65. package/src/ci/trigger.ts +1353 -0
  66. package/src/cli.ts +348 -0
  67. package/src/commands/activity.ts +67 -0
  68. package/src/commands/ci-setup-questions.ts +397 -0
  69. package/src/commands/ci-setup.ts +381 -0
  70. package/src/commands/config.ts +99 -0
  71. package/src/commands/doctor.ts +108 -0
  72. package/src/commands/init.ts +139 -0
  73. package/src/commands/mcp.ts +10 -0
  74. package/src/commands/menu.ts +129 -0
  75. package/src/commands/post.ts +302 -0
  76. package/src/commands/skills.ts +83 -0
  77. package/src/commands/status.ts +173 -0
  78. package/src/commands/triage.ts +342 -0
  79. package/src/commands/uninstall.ts +37 -0
  80. package/src/commands/upgrade.ts +214 -0
  81. package/src/commands/usage.ts +98 -0
  82. package/src/compare/compare.ts +28 -0
  83. package/src/compare/floor-test.ts +471 -0
  84. package/src/compare/martian-adapter.ts +80 -0
  85. package/src/config/config.ts +267 -0
  86. package/src/corpus/corpus.ts +1094 -0
  87. package/src/corpus/preflight.ts +1789 -0
  88. package/src/diversity/accounting.ts +90 -0
  89. package/src/diversity/adjudication.ts +145 -0
  90. package/src/diversity/admission.ts +60 -0
  91. package/src/diversity/benchmark.ts +195 -0
  92. package/src/diversity/clustering.ts +285 -0
  93. package/src/diversity/errors.ts +7 -0
  94. package/src/diversity/identity.ts +285 -0
  95. package/src/diversity/index.ts +11 -0
  96. package/src/diversity/pipeline-integration.ts +448 -0
  97. package/src/diversity/projection.ts +57 -0
  98. package/src/diversity/self-contained.ts +68 -0
  99. package/src/diversity/target-validation.ts +179 -0
  100. package/src/doctor-migration.ts +209 -0
  101. package/src/doctor.ts +723 -0
  102. package/src/errors.ts +83 -0
  103. package/src/execution/admission.ts +75 -0
  104. package/src/execution/atomic-write.ts +35 -0
  105. package/src/execution/attempt-evidence.ts +415 -0
  106. package/src/execution/bucket-id.ts +136 -0
  107. package/src/execution/concurrency-limiter.ts +175 -0
  108. package/src/execution/contracts.ts +443 -0
  109. package/src/execution/failure-classification.ts +42 -0
  110. package/src/execution/failure-policy.ts +240 -0
  111. package/src/execution/harness.ts +2548 -0
  112. package/src/execution/settlement.ts +348 -0
  113. package/src/execution/spawned-process.ts +66 -0
  114. package/src/execution/spend-limiter.ts +424 -0
  115. package/src/execution/step-artifacts.ts +55 -0
  116. package/src/execution/usage-normalized.ts +469 -0
  117. package/src/git/git.ts +396 -0
  118. package/src/git/identity.ts +64 -0
  119. package/src/git/refs.ts +140 -0
  120. package/src/home-preflight.ts +443 -0
  121. package/src/home.ts +243 -0
  122. package/src/ignore-file.ts +336 -0
  123. package/src/ignore-read.ts +118 -0
  124. package/src/index.ts +34 -0
  125. package/src/legacy-launchd.ts +29 -0
  126. package/src/mcp/mcp.ts +150 -0
  127. package/src/mcp/preflight.ts +407 -0
  128. package/src/menu-context.ts +192 -0
  129. package/src/model/catalog.ts +251 -0
  130. package/src/model/exec-snapshots.ts +390 -0
  131. package/src/model/free-discovery.ts +302 -0
  132. package/src/model/provider-capabilities.ts +814 -0
  133. package/src/model/routing.ts +600 -0
  134. package/src/pr/admission.ts +847 -0
  135. package/src/pr/ci-admission-gate.ts +665 -0
  136. package/src/pr/ci-publish.ts +76 -0
  137. package/src/pr/discovery.ts +432 -0
  138. package/src/pr/inline.ts +507 -0
  139. package/src/pr/plan.ts +366 -0
  140. package/src/pr/posting.ts +115 -0
  141. package/src/pr/pr-status.ts +787 -0
  142. package/src/pr/pr.ts +3642 -0
  143. package/src/pr/preflight.ts +1031 -0
  144. package/src/pr/publish-outcome.ts +361 -0
  145. package/src/pr/range.ts +119 -0
  146. package/src/pr/reverts-preflight.ts +606 -0
  147. package/src/pr/reverts.ts +377 -0
  148. package/src/pr/review-pr.ts +927 -0
  149. package/src/pr/status.ts +154 -0
  150. package/src/pr/target.ts +388 -0
  151. package/src/pr/teardown.ts +437 -0
  152. package/src/pr/worktree-setup.ts +60 -0
  153. package/src/production-runtime.ts +1877 -0
  154. package/src/progress.ts +487 -0
  155. package/src/rereview/adjudicate.ts +89 -0
  156. package/src/rereview/classify.ts +362 -0
  157. package/src/rereview/identity.ts +211 -0
  158. package/src/rereview/plan.ts +308 -0
  159. package/src/rereview/prepare.ts +1025 -0
  160. package/src/rereview/state.ts +767 -0
  161. package/src/rereview/verify.ts +241 -0
  162. package/src/review/boundary.ts +105 -0
  163. package/src/review/consolidate.ts +246 -0
  164. package/src/review/dedupe.ts +368 -0
  165. package/src/review/drafts.ts +448 -0
  166. package/src/review/findings-conformance.ts +120 -0
  167. package/src/review/findings.ts +714 -0
  168. package/src/review/pipeline.ts +3977 -0
  169. package/src/review/preflight.ts +3575 -0
  170. package/src/review/prompt-set.ts +177 -0
  171. package/src/review/proof-refs.ts +187 -0
  172. package/src/review/report.ts +1821 -0
  173. package/src/review/review.ts +490 -0
  174. package/src/review/root-cause.ts +120 -0
  175. package/src/review/route-preflight.ts +289 -0
  176. package/src/review/run.ts +601 -0
  177. package/src/review/scout.ts +323 -0
  178. package/src/review/size-gate.ts +595 -0
  179. package/src/review/spec.ts +235 -0
  180. package/src/review/step-runner.ts +233 -0
  181. package/src/runner-authority.ts +596 -0
  182. package/src/security/binding-policy.ts +115 -0
  183. package/src/security/credential-broker.ts +773 -0
  184. package/src/security/evidence-redaction.ts +62 -0
  185. package/src/security/execution-authority.ts +27 -0
  186. package/src/security/redact.ts +71 -0
  187. package/src/security/workspace-read-broker.ts +466 -0
  188. package/src/server/client.ts +190 -0
  189. package/src/server/preflight.ts +217 -0
  190. package/src/server/server.ts +327 -0
  191. package/src/signal-handler.ts +50 -0
  192. package/src/store/activity.ts +413 -0
  193. package/src/store/backfill-preflight.ts +49 -0
  194. package/src/store/backfill.ts +141 -0
  195. package/src/store/gc-preflight.ts +206 -0
  196. package/src/store/gc.ts +424 -0
  197. package/src/store/metrics-preflight.ts +229 -0
  198. package/src/store/metrics.ts +236 -0
  199. package/src/store/preflight.ts +748 -0
  200. package/src/store/store.ts +693 -0
  201. package/src/system-tools.ts +355 -0
  202. package/src/transport-registry.ts +1124 -0
  203. package/src/transports/claude-code-cli.ts +1348 -0
  204. package/src/transports/opencode-admission.ts +515 -0
  205. package/src/transports/opencode-client.ts +3328 -0
  206. package/src/transports/opencode-evidence.ts +557 -0
  207. package/src/transports/opencode-mcp.ts +248 -0
  208. package/src/transports/opencode-sdk.ts +2294 -0
  209. package/src/transports/opencode-server.ts +535 -0
  210. package/src/triage/adjudication.ts +113 -0
  211. package/src/triage/reply.ts +125 -0
  212. package/src/triage/triage.ts +255 -0
  213. package/src/ui/activity.ts +173 -0
  214. package/src/ui/config-edit.ts +816 -0
  215. package/src/ui/config.ts +462 -0
  216. package/src/ui/menu.ts +1325 -0
  217. package/src/ui/plan.ts +1039 -0
  218. package/src/ui/primitives.ts +300 -0
  219. package/src/ui/progress.ts +298 -0
  220. package/src/ui/result.ts +552 -0
  221. package/src/ui/review-menu.ts +312 -0
  222. package/src/ui/select.ts +528 -0
  223. package/src/ui/tree.ts +178 -0
  224. package/src/uninstaller.ts +479 -0
  225. package/src/updater.ts +836 -0
  226. package/src/usage.ts +77 -0
  227. package/src/watch/preflight.ts +1389 -0
  228. package/src/watch/watch.ts +1235 -0
  229. package/src/wizard.ts +877 -0
@@ -0,0 +1,1389 @@
1
+ // Everything the watcher (ROADMAP B3) must decide, expressed as pure
2
+ // functions so it is all testable offline — same contract as review/preflight.ts
3
+ // and pr/preflight.ts: nothing here touches the filesystem, git, gh, launchd
4
+ // or the clock. watch/watch.ts is the I/O shell that acts on these.
5
+ //
6
+ // The watcher's model is a TICK, not a daemon: launchd (or cron) runs
7
+ // `pr-hero watch --once` every N minutes, each tick launches AT MOST ONE
8
+ // review, and every decision an unattended process makes about spending
9
+ // money is pinned here where a test can hold it still.
10
+
11
+ import path from "node:path";
12
+ import { isFullCommitId } from "#git/refs";
13
+ import { PR_COMMENT_MARKER_PREFIX } from "#pr/preflight";
14
+ import type { NumstatFile } from "#review/preflight";
15
+ import {
16
+ DEFAULT_SIZE_GATE,
17
+ evaluateSizeGate,
18
+ type SizeGateConfig,
19
+ } from "#review/size-gate";
20
+ import type { SelfInvocation } from "../assets";
21
+ import { MARKER_BRAND_PATTERN, matchMarkerPrefix } from "../brand";
22
+ import { CliUsageError } from "../errors";
23
+ import { type PrheroLayout, prheroLayout } from "../home-preflight";
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // ~/.prhero/ layout — one source for every path the watcher owns, so the
27
+ // shell, the plist and the docs cannot drift apart on where things live.
28
+
29
+ // Extends PrheroLayout (never redeclares its fields) so a new field there —
30
+ // metricsDbPath (W4 / #23) was the first — cannot silently drift out of
31
+ // this spread; tsc rejects an object literal missing a field the moment
32
+ // PrheroLayout grows one.
33
+ export interface PrheroHomePaths extends PrheroLayout {
34
+ plistPath: string;
35
+ }
36
+
37
+ export function prheroHomePaths(home: string): PrheroHomePaths {
38
+ const layout = prheroLayout(home);
39
+ return {
40
+ ...layout,
41
+ plistPath: path.join(
42
+ home,
43
+ "Library",
44
+ "LaunchAgents",
45
+ `${WATCH_LAUNCHD_LABEL}.plist`,
46
+ ),
47
+ };
48
+ }
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // ~/.prhero/watch.json — the explicit opt-in. A repo is watched ONLY if
52
+ // listed here; nothing in a repo's own .prhero/ can subscribe it to
53
+ // automatic spend. Parsed loudly, ledger-style: every failing field names
54
+ // itself and its got-value, because a silently mis-read config either burns
55
+ // money on the wrong repo or silently watches nothing.
56
+
57
+ export const DEFAULT_DAILY_CAP = 5;
58
+
59
+ export interface WatchRepoConfig {
60
+ // As written in the config (tilde and all); the shell expands it.
61
+ path: string;
62
+ post: boolean;
63
+ // false (the default): one review per PR — any prior review of the PR
64
+ // NUMBER blocks it, whatever head it covered. true: the original (pr,
65
+ // head) key — every push re-arms the PR. See candidateSkipReason.
66
+ onPush: boolean;
67
+ // The size gate's per-repo thresholds (see size-gate.ts). A MISSING key
68
+ // falls back to DEFAULT_SIZE_GATE, so every config file written before
69
+ // the gate landed keeps working untouched.
70
+ maxChangedLines: number;
71
+ maxChangedFiles: number;
72
+ }
73
+
74
+ export interface WatchWindow {
75
+ start: string; // "HH:MM", local time
76
+ end: string;
77
+ }
78
+
79
+ export interface WatchConfig {
80
+ repos: WatchRepoConfig[];
81
+ dailyCap: number;
82
+ window: WatchWindow | null;
83
+ }
84
+
85
+ const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
86
+
87
+ export function parseWatchConfig(raw: string): WatchConfig {
88
+ let parsed: unknown;
89
+ try {
90
+ parsed = JSON.parse(raw);
91
+ } catch (error) {
92
+ throw new CliUsageError(
93
+ `watch.json is not valid JSON: ${(error as Error).message}`,
94
+ );
95
+ }
96
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
97
+ throw new CliUsageError("watch.json must be a single JSON object");
98
+ }
99
+ const record = parsed as Record<string, unknown>;
100
+ const repos = record.repos;
101
+ if (!Array.isArray(repos)) {
102
+ throw new CliUsageError(
103
+ `watch.json "repos" must be an array, got: ${JSON.stringify(repos)}`,
104
+ );
105
+ }
106
+ const parsedRepos: WatchRepoConfig[] = repos.map((entry, i) => {
107
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
108
+ throw new CliUsageError(`watch.json repos[${i}] must be an object`);
109
+ }
110
+ const repo = entry as Record<string, unknown>;
111
+ if (typeof repo.path !== "string" || repo.path.trim().length === 0) {
112
+ throw new CliUsageError(
113
+ `watch.json repos[${i}].path must be a non-empty string, got: ` +
114
+ JSON.stringify(repo.path),
115
+ );
116
+ }
117
+ const post = repo.post ?? false;
118
+ if (typeof post !== "boolean") {
119
+ throw new CliUsageError(
120
+ `watch.json repos[${i}].post must be a boolean, got: ` +
121
+ JSON.stringify(repo.post),
122
+ );
123
+ }
124
+ const onPush = repo.on_push ?? false;
125
+ if (typeof onPush !== "boolean") {
126
+ throw new CliUsageError(
127
+ `watch.json repos[${i}].on_push must be a boolean, got: ` +
128
+ JSON.stringify(repo.on_push),
129
+ );
130
+ }
131
+ return {
132
+ path: repo.path,
133
+ post,
134
+ onPush,
135
+ maxChangedLines: sizeLimit(
136
+ repo.max_changed_lines,
137
+ DEFAULT_SIZE_GATE.maxChangedLines,
138
+ i,
139
+ "max_changed_lines",
140
+ ),
141
+ maxChangedFiles: sizeLimit(
142
+ repo.max_changed_files,
143
+ DEFAULT_SIZE_GATE.maxChangedFiles,
144
+ i,
145
+ "max_changed_files",
146
+ ),
147
+ };
148
+ });
149
+ const cap = record.daily_cap ?? DEFAULT_DAILY_CAP;
150
+ // Zero is legal on purpose: `"daily_cap": 0` is the pause switch — the
151
+ // watcher keeps observing (and dry-runs keep working) but launches nothing.
152
+ if (typeof cap !== "number" || !Number.isInteger(cap) || cap < 0) {
153
+ throw new CliUsageError(
154
+ `watch.json "daily_cap" must be a non-negative integer, got: ` +
155
+ JSON.stringify(record.daily_cap),
156
+ );
157
+ }
158
+ const window = parseWindow(record.window);
159
+ return { repos: parsedRepos, dailyCap: cap, window };
160
+ }
161
+
162
+ // Zero is legal and MEANINGFUL — like daily_cap's pause switch, it is the
163
+ // documented "disable this limit" value, not a nonsense input — so the
164
+ // validation floor is 0, not 1. Absent falls back to the shipped default.
165
+ function sizeLimit(
166
+ value: unknown,
167
+ fallback: number,
168
+ i: number,
169
+ key: string,
170
+ ): number {
171
+ if (value === undefined || value === null) return fallback;
172
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
173
+ throw new CliUsageError(
174
+ `watch.json repos[${i}].${key} must be a non-negative integer ` +
175
+ `(0 disables the limit), got: ${JSON.stringify(value)}`,
176
+ );
177
+ }
178
+ return value;
179
+ }
180
+
181
+ function parseWindow(value: unknown): WatchWindow | null {
182
+ if (value === undefined || value === null) return null;
183
+ if (typeof value !== "object" || Array.isArray(value)) {
184
+ throw new CliUsageError(
185
+ `watch.json "window" must be null or {start, end}, got: ` +
186
+ JSON.stringify(value),
187
+ );
188
+ }
189
+ const window = value as Record<string, unknown>;
190
+ for (const field of ["start", "end"] as const) {
191
+ if (typeof window[field] !== "string" || !HHMM.test(window[field])) {
192
+ throw new CliUsageError(
193
+ `watch.json "window.${field}" must be "HH:MM" (24h), got: ` +
194
+ JSON.stringify(window[field]),
195
+ );
196
+ }
197
+ }
198
+ const start = window.start as string;
199
+ const end = window.end as string;
200
+ // start === end would be an always-closed window: a config bug with a
201
+ // plausible face ("all day" is `null`, not a degenerate range).
202
+ if (start === end) {
203
+ throw new CliUsageError(
204
+ `watch.json "window" start and end must differ (got ${start} twice); ` +
205
+ "use null for no window",
206
+ );
207
+ }
208
+ return { start, end };
209
+ }
210
+
211
+ // Only the two shell forms (`~` and `~/...`) expand — `~user` is left alone,
212
+ // because guessing another user's home would point the watcher at a repo
213
+ // nobody configured.
214
+ export function expandTilde(p: string, home: string): string {
215
+ if (p === "~") return home;
216
+ if (p.startsWith("~/")) return path.join(home, p.slice(2));
217
+ return p;
218
+ }
219
+
220
+ // The write-side inverse of expandTilde: paths STORED in watch.json contract
221
+ // $HOME back to `~`, so the file stays readable, matches the README's
222
+ // examples, and survives a home-directory rename.
223
+ export function contractTilde(p: string, home: string): string {
224
+ if (p === home) return "~";
225
+ if (p.startsWith(`${home}${path.sep}`)) {
226
+ return `~/${p.slice(home.length + 1)}`;
227
+ }
228
+ return p;
229
+ }
230
+
231
+ // ---------------------------------------------------------------------------
232
+ // Config management (watch add/remove) — the config file is machine-owned so
233
+ // nobody hand-edits JSON. Both rewrites are SURGICAL over the raw JSON
234
+ // record, never a re-projection of the parsed WatchConfig: parseWatchConfig
235
+ // tolerates unknown keys (top-level and per-repo alike), so a canonical
236
+ // re-projection would silently drop whatever a future version — or a careful
237
+ // hand — put there. The raw text is still validated through parseWatchConfig
238
+ // FIRST: a malformed config fails loud instead of being "repaired" into
239
+ // data loss.
240
+
241
+ // A stored path and a freshly resolved repo root must collide however the
242
+ // config spells the repo — `~/x` and `/Users/user/x` are the same entry.
243
+ function sameRepoPath(stored: string, repoRoot: string, home: string): boolean {
244
+ return path.resolve(expandTilde(stored, home)) === path.resolve(repoRoot);
245
+ }
246
+
247
+ function serializeConfig(record: unknown): string {
248
+ return `${JSON.stringify(record, null, 2)}\n`;
249
+ }
250
+
251
+ export interface ConfigUpsert {
252
+ // The new file body, ready to write.
253
+ config: string;
254
+ action: "added" | "updated";
255
+ // As recorded in the file: the tilde-contracted form on an add, the
256
+ // entry's own existing spelling on an update.
257
+ storedPath: string;
258
+ }
259
+
260
+ export interface WatchRepoFlags {
261
+ post: boolean;
262
+ onPush: boolean;
263
+ // Size-gate thresholds, written on every add/update like every other flag
264
+ // here — absent on the command line means "the shipped default", per this
265
+ // command's disclosed reset semantics.
266
+ maxChangedLines: number;
267
+ maxChangedFiles: number;
268
+ }
269
+
270
+ // Idempotent by design: re-adding a listed repo UPDATES its flags in place
271
+ // (every other key of the entry survives) and is never an error — `watch
272
+ // add` doubles as "change this repo's settings", and an absent flag RESETS
273
+ // to its default rather than keeping the old value (disclosed semantics:
274
+ // the command line states the whole intent). A null raw means no config
275
+ // file yet: one is created with the shipped defaults.
276
+ export function upsertWatchRepo(
277
+ raw: string | null,
278
+ repoRoot: string,
279
+ flags: WatchRepoFlags,
280
+ home: string,
281
+ ): ConfigUpsert {
282
+ const storedPath = contractTilde(repoRoot, home);
283
+ if (raw === null) {
284
+ return {
285
+ config: serializeConfig({
286
+ repos: [repoEntry(storedPath, flags)],
287
+ daily_cap: DEFAULT_DAILY_CAP,
288
+ window: null,
289
+ }),
290
+ action: "added",
291
+ storedPath,
292
+ };
293
+ }
294
+ // Loud validation first; the raw re-parse below is then known-shaped.
295
+ parseWatchConfig(raw);
296
+ const record = JSON.parse(raw) as Record<string, unknown>;
297
+ const repos = record.repos as Record<string, unknown>[];
298
+ for (const entry of repos) {
299
+ if (sameRepoPath(entry.path as string, repoRoot, home)) {
300
+ entry.post = flags.post;
301
+ entry.on_push = flags.onPush;
302
+ entry.max_changed_lines = flags.maxChangedLines;
303
+ entry.max_changed_files = flags.maxChangedFiles;
304
+ return {
305
+ config: serializeConfig(record),
306
+ action: "updated",
307
+ storedPath: entry.path as string,
308
+ };
309
+ }
310
+ }
311
+ repos.push(repoEntry(storedPath, flags));
312
+ return { config: serializeConfig(record), action: "added", storedPath };
313
+ }
314
+
315
+ // One shape for both the create and the append path: two literals would
316
+ // drift the day a knob is added.
317
+ function repoEntry(
318
+ storedPath: string,
319
+ flags: WatchRepoFlags,
320
+ ): Record<string, unknown> {
321
+ return {
322
+ path: storedPath,
323
+ post: flags.post,
324
+ on_push: flags.onPush,
325
+ max_changed_lines: flags.maxChangedLines,
326
+ max_changed_files: flags.maxChangedFiles,
327
+ };
328
+ }
329
+
330
+ export interface ConfigRemoval {
331
+ // null when nothing changed (the repo was not listed) — the caller skips
332
+ // the write, so a no-op remove cannot even reformat the file.
333
+ config: string | null;
334
+ action: "removed" | "not-listed";
335
+ }
336
+
337
+ // Removing the last repo leaves `"repos": []` — a VALID config state
338
+ // ("watch nothing"): parseWatchConfig accepts it and a tick over zero repos
339
+ // gates, logs and exits cleanly. Deleting the file instead would throw away
340
+ // the operator's cap and window settings.
341
+ export function removeWatchRepo(
342
+ raw: string,
343
+ repoRoot: string,
344
+ home: string,
345
+ ): ConfigRemoval {
346
+ parseWatchConfig(raw);
347
+ const record = JSON.parse(raw) as Record<string, unknown>;
348
+ const repos = record.repos as Record<string, unknown>[];
349
+ const kept = repos.filter(
350
+ (entry) => !sameRepoPath(entry.path as string, repoRoot, home),
351
+ );
352
+ if (kept.length === repos.length) {
353
+ return { config: null, action: "not-listed" };
354
+ }
355
+ record.repos = kept;
356
+ return { config: serializeConfig(record), action: "removed" };
357
+ }
358
+
359
+ // Start-inclusive, end-EXCLUSIVE, so back-to-back windows neither overlap
360
+ // nor gap. An inverted range (start > end) is an overnight window — 22:00 to
361
+ // 06:00 means "late evening through early morning", not an error.
362
+ export function insideWindow(
363
+ window: WatchWindow | null,
364
+ localMinutes: number,
365
+ ): boolean {
366
+ if (window === null) return true;
367
+ const start = hhmmToMinutes(window.start);
368
+ const end = hhmmToMinutes(window.end);
369
+ return start < end
370
+ ? localMinutes >= start && localMinutes < end
371
+ : localMinutes >= start || localMinutes < end;
372
+ }
373
+
374
+ function hhmmToMinutes(hhmm: string): number {
375
+ return Number(hhmm.slice(0, 2)) * 60 + Number(hhmm.slice(3, 5));
376
+ }
377
+
378
+ // ---------------------------------------------------------------------------
379
+ // gh output parsers — the same loud register as resolvePrTarget: gh's output
380
+ // is input from outside this process, and a mis-read PR list makes an
381
+ // unattended watcher spend money on a range nobody asked about.
382
+
383
+ export interface WatchPrCandidate {
384
+ pr: number;
385
+ head: string;
386
+ isDraft: boolean;
387
+ // GitHub's own aggregate counters, free in the same list response — the
388
+ // size gate's zero-extra-call first tier.
389
+ additions: number;
390
+ deletions: number;
391
+ changedFiles: number;
392
+ }
393
+
394
+ // Parses the raw stdout of `gh pr list --json <PR_LIST_JSON_FIELDS>` (open
395
+ // PRs only — gh's default state filter is the one the watcher wants).
396
+ export function parsePrList(raw: string): WatchPrCandidate[] {
397
+ let parsed: unknown;
398
+ try {
399
+ parsed = JSON.parse(raw);
400
+ } catch (error) {
401
+ throw new CliUsageError(
402
+ `gh pr list returned invalid JSON: ${(error as Error).message}`,
403
+ );
404
+ }
405
+ if (!Array.isArray(parsed)) {
406
+ throw new CliUsageError("gh pr list must return a JSON array");
407
+ }
408
+ return parsed.map((entry, i) => {
409
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
410
+ throw new CliUsageError(`gh pr list [${i}] must be an object`);
411
+ }
412
+ const record = entry as Record<string, unknown>;
413
+ const pr = record.number;
414
+ if (typeof pr !== "number" || !Number.isInteger(pr) || pr < 1) {
415
+ throw new CliUsageError(
416
+ `gh pr list [${i}].number must be a positive integer, got: ` +
417
+ JSON.stringify(pr),
418
+ );
419
+ }
420
+ const head = record.headRefOid;
421
+ if (typeof head !== "string" || !isFullCommitId(head)) {
422
+ throw new CliUsageError(
423
+ `gh pr list [${i}].headRefOid must be a full 40-hex commit id, ` +
424
+ `got: ${JSON.stringify(head)}`,
425
+ );
426
+ }
427
+ const isDraft = record.isDraft;
428
+ if (typeof isDraft !== "boolean") {
429
+ throw new CliUsageError(
430
+ `gh pr list [${i}].isDraft must be a boolean, got: ` +
431
+ JSON.stringify(isDraft),
432
+ );
433
+ }
434
+ return {
435
+ pr,
436
+ head,
437
+ isDraft,
438
+ additions: countField(record, i, "additions"),
439
+ deletions: countField(record, i, "deletions"),
440
+ changedFiles: countField(record, i, "changedFiles"),
441
+ };
442
+ });
443
+ }
444
+
445
+ // Loud, like every other field here: a size counter silently read as 0 would
446
+ // wave a monster PR straight past the gate — the exact failure the gate
447
+ // exists to prevent — and it would look identical to a genuinely tiny PR.
448
+ function countField(
449
+ record: Record<string, unknown>,
450
+ i: number,
451
+ key: string,
452
+ ): number {
453
+ const value = record[key];
454
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
455
+ throw new CliUsageError(
456
+ `gh pr list [${i}].${key} must be a non-negative integer, got: ` +
457
+ JSON.stringify(value),
458
+ );
459
+ }
460
+ return value;
461
+ }
462
+
463
+ // Parses the raw stdout of `gh pr view <n> --json files` into the same
464
+ // NumstatFile shape the local gate uses, so ONE evaluateSizeGate serves both
465
+ // the git path and the GitHub path — two size gates would drift.
466
+ //
467
+ // `binary` is always false: GitHub's file list carries no binary marker, and
468
+ // for a binary file it simply reports 0/0 — which is what a binary file
469
+ // contributes anyway, so the gate's arithmetic is unaffected.
470
+ export function parsePrFiles(raw: string): NumstatFile[] {
471
+ let parsed: unknown;
472
+ try {
473
+ parsed = JSON.parse(raw);
474
+ } catch (error) {
475
+ throw new CliUsageError(
476
+ `gh pr view --json files returned invalid JSON: ${(error as Error).message}`,
477
+ );
478
+ }
479
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
480
+ throw new CliUsageError(
481
+ "gh pr view --json files must return a JSON object",
482
+ );
483
+ }
484
+ const files = (parsed as Record<string, unknown>).files;
485
+ if (!Array.isArray(files)) {
486
+ throw new CliUsageError(
487
+ `gh pr view --json files "files" must be an array, got: ${JSON.stringify(files)}`,
488
+ );
489
+ }
490
+ return files.map((entry, i) => {
491
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
492
+ throw new CliUsageError(`gh pr view files[${i}] must be an object`);
493
+ }
494
+ const record = entry as Record<string, unknown>;
495
+ const filePath = record.path;
496
+ if (typeof filePath !== "string" || filePath.length === 0) {
497
+ throw new CliUsageError(
498
+ `gh pr view files[${i}].path must be a non-empty string, got: ` +
499
+ JSON.stringify(filePath),
500
+ );
501
+ }
502
+ return {
503
+ path: filePath,
504
+ insertions: countField(record, i, "additions"),
505
+ deletions: countField(record, i, "deletions"),
506
+ binary: false,
507
+ };
508
+ });
509
+ }
510
+
511
+ // ---------------------------------------------------------------------------
512
+ // The cross-machine guard. A posted pr-hero comment now declares which head
513
+ // it reviewed (prCommentMarker in pr/preflight.ts); reading that declaration
514
+ // back out is how one machine's watcher learns another machine already paid
515
+ // for this head.
516
+
517
+ // The exact-token contract (rereview-coverage fix): a marker's
518
+ // first line is either the plain complete form, or the plain form plus the
519
+ // space-separated `coverage=partial` token — and NOTHING else. An
520
+ // abbreviated or garbage trailing token (`coverage=partiallyDone`,
521
+ // `coverage=PARTIAL`, a stray space) fails the WHOLE match rather than being
522
+ // coerced into either bucket, mirroring how a malformed sha already failed
523
+ // the whole marker before this fix (never a partial match). This single
524
+ // regex backs both readers below so their heads can never drift apart.
525
+ //
526
+ // WHY this is also the correct behavior for an OLDER pr-hero deployed
527
+ // elsewhere, unaware of the coverage token: its own copy of this regex has
528
+ // no optional group, so it fails to match a partial marker's first line
529
+ // entirely and reads it as the legacy headless marker — no head declared,
530
+ // covers none, PR stays eligible. That is the fail-safe direction (more
531
+ // review, never a truncated one), and it is what motivates fail-closed
532
+ // (not fail-complete) as THIS reader's answer for a garbage token too.
533
+ const MARKER_HEAD_RE = new RegExp(
534
+ `^<!-- ${MARKER_BRAND_PATTERN}-report head=([0-9a-f]{40})( coverage=partial)? -->`,
535
+ );
536
+
537
+ // NEVER throws: comment bodies are foreign text (bots, humans, pasted
538
+ // reports), and a guard that crashes on someone else's comment takes the
539
+ // whole watcher down with it. An old-format marker (`<!-- pr-hero-report -->`,
540
+ // no head=) returns null — it declares NO head, so it covers none and the
541
+ // PR stays eligible; a malformed or abbreviated head reads the same way.
542
+ //
543
+ // Every existing consumer (markerDeclaredHeads below; cli.ts's CI-admission
544
+ // authority check and its previousHeadSha reconcile read) needs the head
545
+ // unchanged regardless of whether the run that posted it completed — none of
546
+ // them care about completeness, only identity — so this stays a thin
547
+ // projection of parsePrCommentMarker rather than a second regex to keep in
548
+ // sync.
549
+ export function parseMarkerHead(body: string): string | null {
550
+ return parsePrCommentMarker(body)?.head ?? null;
551
+ }
552
+
553
+ export interface PrCommentMarkerFields {
554
+ head: string;
555
+ complete: boolean;
556
+ }
557
+
558
+ // The coverage-aware reader (rereview-coverage fix): cli.ts's
559
+ // re-review discovery seam needs to know not just WHICH head a posted
560
+ // summary comment covers, but whether that run actually finished — a
561
+ // PARTIAL run's own L must never be trusted the same way a COMPLETE run's
562
+ // is (see resolveLastReviewedHead's `lastComplete` in rereview/plan.ts).
563
+ export function parsePrCommentMarker(
564
+ body: string,
565
+ ): PrCommentMarkerFields | null {
566
+ if (typeof body !== "string") return null;
567
+ if (matchMarkerPrefix(body, PR_COMMENT_MARKER_PREFIX) === undefined) {
568
+ return null;
569
+ }
570
+ const newlineAt = body.indexOf("\n");
571
+ const firstLine = newlineAt === -1 ? body : body.slice(0, newlineAt);
572
+ const match = MARKER_HEAD_RE.exec(firstLine);
573
+ if (match === null) return null;
574
+ const head = match[1];
575
+ if (head === undefined) return null;
576
+ return { head, complete: match[2] === undefined };
577
+ }
578
+
579
+ // The two fields every production consumer of a parsed marker actually
580
+ // wants, with the "nothing posted yet" default folded in ONE place: a null
581
+ // marker (no comment, or one that failed to parse) declares no head — there
582
+ // is nothing to distrust, so it reads as complete. Both reviewPr()'s
583
+ // discovery seam (src/pr/review-pr.ts) and the CI admission gate
584
+ // (src/pr/ci-admission-gate.ts) independently needed `summaryHead`/
585
+ // `summaryComplete` derived from a parsed marker; before this helper existed
586
+ // each site re-wrote the same `marker?.head ?? null` / `marker?.complete ??
587
+ // true` pair inline, which is exactly the shape that can drift — one call
588
+ // site could gain a real default (a stray `true` literal, say) while the
589
+ // other kept threading the marker's own value, silently reopening the
590
+ // rereview-coverage fix's failure mode (a forced-full re-review from a
591
+ // partial marker that only ONE of the two consumers still notices).
592
+ export function summaryMarkerFields(marker: PrCommentMarkerFields | null): {
593
+ summaryHead: string | null;
594
+ summaryComplete: boolean;
595
+ } {
596
+ return {
597
+ summaryHead: marker?.head ?? null,
598
+ summaryComplete: marker?.complete ?? true,
599
+ };
600
+ }
601
+
602
+ // Every head any pr-hero-marked comment on the PR declares. Duplicates are
603
+ // harmless (the guard only asks "is this head among them").
604
+ //
605
+ // Rereview-coverage fix (explicitly unchanged): a PARTIAL marker's
606
+ // head still counts as "declared" here — parseMarkerHead returns the head
607
+ // for both wire forms, and this function does not distinguish them. There is
608
+ // deliberately NO automatic relaunch loop for a PR whose review keeps timing
609
+ // out: the watcher's one-review-per-PR eligibility stays exactly as it was.
610
+ // Recovery is an explicit `pr-hero review --pr N`, a CI re-run of the same
611
+ // commit (CI admission does not treat a partial same-head review as done,
612
+ // see evaluateCiReviewAdmission), or a new push; each forces a full
613
+ // re-review via `lastComplete` (rereview/plan.ts). Never the watcher noticing
614
+ // coverage=partial and retrying on its own.
615
+ export function markerDeclaredHeads(comments: { body: string }[]): string[] {
616
+ const heads: string[] = [];
617
+ for (const comment of comments) {
618
+ const head = parseMarkerHead(comment?.body);
619
+ if (head !== null) heads.push(head);
620
+ }
621
+ return heads;
622
+ }
623
+
624
+ // Whether ANY pr-hero marker comment exists on the PR, head-declaring or
625
+ // not. Distinct from markerDeclaredHeads on purpose: a legacy headless
626
+ // marker declares no head — it can never prove THIS head was reviewed — but
627
+ // it does prove the PR was reviewed at some point, which is exactly what
628
+ // the one-review-per-PR default (on_push: false) needs to know. Same
629
+ // never-throw contract as parseMarkerHead: bodies are foreign text.
630
+ export function markerCommentSeen(comments: { body: string }[]): boolean {
631
+ return comments.some(
632
+ (comment) =>
633
+ typeof comment?.body === "string" &&
634
+ matchMarkerPrefix(comment.body, PR_COMMENT_MARKER_PREFIX) !== undefined,
635
+ );
636
+ }
637
+
638
+ // ---------------------------------------------------------------------------
639
+ // The attempts guard (poison-PR): max 2 total launches per (pr, head), so a
640
+ // PR that keeps killing the review cannot eat the daily cap every day
641
+ // forever. Attempts are counted from RUN ARTIFACTS, not from memory:
642
+ //
643
+ // - a run that reached the pipeline wrote pipeline.json, which carries the
644
+ // full `pr` and `head_sha` — parsed fields, the preferred source (the
645
+ // ledger's must-use-parsed-fields rule applied to the guard);
646
+ // - a run that died before the pipeline wrote anything still created its
647
+ // run dir, whose NAME encodes pr + sha8 (prRunDirCandidate) — the
648
+ // fallback for exactly the dirs whose artifacts genuinely lack the sha.
649
+ //
650
+ // parsePipelineMeta is TOLERANT (null, never throw) against the module's own
651
+ // loud grain, deliberately: a corrupt pipeline.json falls back to the
652
+ // dir-name count, which errs toward COUNTING the attempt — the fail-safe
653
+ // direction for money — while a loud throw would brick every future tick on
654
+ // one damaged artifact, and skipping the dir would retry a poison PR
655
+ // forever.
656
+ //
657
+ // What this cannot see, and why that is fine: a spawn that dies in
658
+ // preflight (bad gotchas, missing agents dir) creates no run dir at all, so
659
+ // its attempts stay 0 — but every launch appends to watch.log BEFORE the
660
+ // spawn, so the daily cap still bounds the damage at `daily_cap` failed
661
+ // launches per day.
662
+
663
+ export const MAX_WATCH_ATTEMPTS = 2;
664
+
665
+ export interface RunDirFact {
666
+ name: string;
667
+ // null when the dir has no parseable pipeline.json.
668
+ pipelineMeta: { pr: number; head_sha: string } | null;
669
+ }
670
+
671
+ export function parsePipelineMeta(
672
+ raw: string,
673
+ ): { pr: number; head_sha: string } | null {
674
+ let parsed: unknown;
675
+ try {
676
+ parsed = JSON.parse(raw);
677
+ } catch {
678
+ return null;
679
+ }
680
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
681
+ return null;
682
+ }
683
+ const record = parsed as Record<string, unknown>;
684
+ const pr = record.pr;
685
+ const head = record.head_sha;
686
+ // pr 0 is legal: local-mode runs share the runs root and record the
687
+ // schema's "not a PR" value — they parse fine and never match a real PR.
688
+ if (typeof pr !== "number" || !Number.isInteger(pr) || pr < 0) return null;
689
+ if (typeof head !== "string" || !isFullCommitId(head)) return null;
690
+ return { pr, head_sha: head };
691
+ }
692
+
693
+ export function countAttempts(
694
+ dirs: RunDirFact[],
695
+ pr: number,
696
+ headSha: string,
697
+ ): number {
698
+ // pr is a validated integer and the sha slice is hex, so the pattern
699
+ // contains no regex metacharacters.
700
+ const namePattern = new RegExp(`^pr-${pr}-${headSha.slice(0, 8)}-\\d+$`);
701
+ let count = 0;
702
+ for (const dir of dirs) {
703
+ if (dir.pipelineMeta !== null) {
704
+ // Parsed fields win over the dir name whenever they exist.
705
+ if (dir.pipelineMeta.pr === pr && dir.pipelineMeta.head_sha === headSha) {
706
+ count++;
707
+ }
708
+ continue;
709
+ }
710
+ if (namePattern.test(dir.name)) count++;
711
+ }
712
+ return count;
713
+ }
714
+
715
+ // The newest run dir for a (pr, head) — highest -<n> suffix, mirroring the
716
+ // smallest-unused-integer allocation in cli.ts. Cosmetic consumer only (the
717
+ // notification's finding counts), so null on no match, never a throw.
718
+ export function latestRunDirName(
719
+ names: string[],
720
+ pr: number,
721
+ headSha: string,
722
+ ): string | null {
723
+ const pattern = new RegExp(`^pr-${pr}-${headSha.slice(0, 8)}-(\\d+)$`);
724
+ let best: string | null = null;
725
+ let bestN = -1;
726
+ for (const name of names) {
727
+ const match = pattern.exec(name);
728
+ if (match === null) continue;
729
+ const n = Number(match[1]);
730
+ if (n > bestN) {
731
+ bestN = n;
732
+ best = name;
733
+ }
734
+ }
735
+ return best;
736
+ }
737
+
738
+ // Blocking/advisory counts from a findings.json body already parsed as JSON.
739
+ // Tolerant (null, never throw): the counts only decorate a notification, and
740
+ // a notification must never take the tick down — same contract as
741
+ // ghRepoWebUrl's "cosmetic by contract".
742
+ export function findingsTierCounts(
743
+ parsed: unknown,
744
+ ): { blocking: number; advisory: number } | null {
745
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
746
+ return null;
747
+ }
748
+ const findings = (parsed as Record<string, unknown>).findings;
749
+ if (!Array.isArray(findings)) return null;
750
+ let blocking = 0;
751
+ for (const finding of findings) {
752
+ if (typeof finding !== "object" || finding === null) return null;
753
+ if ((finding as Record<string, unknown>).tier === "blocking") blocking++;
754
+ }
755
+ // Advisory is the remainder, the same projection cli.ts's summary uses.
756
+ return { blocking, advisory: findings.length - blocking };
757
+ }
758
+
759
+ // ---------------------------------------------------------------------------
760
+ // The tick decision — every already-fetched fact in, one launch (at most)
761
+ // out. The shell gathers; this decides.
762
+
763
+ export type SkipReason =
764
+ | "draft"
765
+ | "reviewed-local"
766
+ | "reviewed-remote"
767
+ | "reviewed-prior-head"
768
+ | "too-large"
769
+ | "nothing-to-review"
770
+ | "attempts-exhausted"
771
+ | "in-flight";
772
+
773
+ export interface TickRepoFacts {
774
+ // Expanded absolute operator checkout — the spawn's cwd and the skip
775
+ // lines' identity.
776
+ path: string;
777
+ post: boolean;
778
+ // The re-arm policy (config on_push): false = one review per PR, any
779
+ // prior review of the number blocks; true = the (pr, head) key, every
780
+ // push re-arms.
781
+ onPush: boolean;
782
+ prs: WatchPrCandidate[];
783
+ // Parsed findings.json fields (pr + head_sha) of PR reviews that did not
784
+ // fail their session — never dir names.
785
+ localReviews: { pr: number; head: string }[];
786
+ // Marker facts per PR: the declared heads AND whether any marker comment
787
+ // exists at all (a legacy headless marker is seen but declares nothing).
788
+ // A PR absent here means "comments not fetched" — the shell may skip the
789
+ // fetch for candidates a cheaper check already killed, and an unfetched
790
+ // PR must read as unguarded, not covered.
791
+ remoteHeads: { pr: number; heads: string[]; markerSeen: boolean }[];
792
+ attempts: { pr: number; head: string; count: number }[];
793
+ // PR numbers the size gate rejected THIS TICK. Computed fresh by the
794
+ // shell every tick and never persisted — see the recompute-every-tick WHY
795
+ // on candidateSkipReason. A PR absent here was either under the limits or
796
+ // never evaluated (the shell settles cheaper reasons first).
797
+ tooLarge: number[];
798
+ // PR numbers whose changed files are ALL generated content the size gate
799
+ // excludes — so the effective diff is empty and there is nothing to review.
800
+ // Same fresh-every-tick, never-persisted rule as tooLarge. WHY it is its
801
+ // own reason and not folded into too-large: spawning here would have the
802
+ // child CLI exit on an empty effective diff without creating a run dir, and
803
+ // a run dir is where attempts are counted — so the watcher would re-spawn
804
+ // the same PR every tick forever. Skipping it here is what stops that loop.
805
+ nothingToReview: number[];
806
+ // Heads with a fresh pending `pr-hero` commit status. Shell-gathered
807
+ // (fetchCommitStatuses + isInFlightCommitStatus); a PR absent here is
808
+ // not in-flight, same unfetched-means-unguarded rule as remoteHeads.
809
+ inFlight: { pr: number; head: string }[];
810
+ // Latest pr-hero status is pending, any age. Distinct from inFlight: a
811
+ // stale pending on an already-reviewed PR is NOT in-flight (must not
812
+ // block a launch) but MUST be settled to success so the yellow dot does
813
+ // not stick after a crash between comment-post and status-complete.
814
+ pending: { pr: number; head: string }[];
815
+ }
816
+
817
+ export type TickGate = "open" | "window-closed" | "cap-reached";
818
+
819
+ export interface TickGateInput {
820
+ window: WatchWindow | null;
821
+ localMinutes: number;
822
+ dailyCap: number;
823
+ launchedToday: number;
824
+ }
825
+
826
+ // Window before cap: outside the window the operator said "never at this
827
+ // hour", which is stronger than "not again today" — and the real tick
828
+ // checks this gate BEFORE any gh call, so a closed window costs nothing.
829
+ export function tickGate(input: TickGateInput): TickGate {
830
+ if (!insideWindow(input.window, input.localMinutes)) return "window-closed";
831
+ if (input.launchedToday >= input.dailyCap) return "cap-reached";
832
+ return "open";
833
+ }
834
+
835
+ export interface TickInput extends TickGateInput {
836
+ repos: TickRepoFacts[];
837
+ }
838
+
839
+ export interface TickSkip {
840
+ repo: string;
841
+ pr: number;
842
+ head: string;
843
+ reason: SkipReason;
844
+ }
845
+
846
+ export interface TickLaunch {
847
+ repo: string;
848
+ post: boolean;
849
+ pr: number;
850
+ head: string;
851
+ }
852
+
853
+ export interface TickDecision {
854
+ gate: TickGate;
855
+ skips: TickSkip[];
856
+ // FIFO-ordered, kept whole so a dry run can show what stands in line
857
+ // behind the pick.
858
+ eligible: TickLaunch[];
859
+ // null unless the gate is open AND something is eligible.
860
+ launch: TickLaunch | null;
861
+ }
862
+
863
+ // ONE review per tick MAX, across all repos: eligible candidates sort by PR
864
+ // number ascending (oldest PR first — deterministic FIFO) and the first one
865
+ // wins. The sort is stable, so two repos sharing a PR number tie-break by
866
+ // their order in the config — the operator's own priority order.
867
+ //
868
+ // Skips and eligibility are computed even when the gate is closed: the $0
869
+ // dry run wants the full picture ("would run were it not for the window"),
870
+ // and a gated launch stays null either way.
871
+ export function decideTick(input: TickInput): TickDecision {
872
+ const gate = tickGate(input);
873
+ const skips: TickSkip[] = [];
874
+ const eligible: TickLaunch[] = [];
875
+ for (const repo of input.repos) {
876
+ for (const candidate of repo.prs) {
877
+ const reason = candidateSkipReason(repo, candidate);
878
+ if (reason !== null) {
879
+ skips.push({
880
+ repo: repo.path,
881
+ pr: candidate.pr,
882
+ head: candidate.head,
883
+ reason,
884
+ });
885
+ continue;
886
+ }
887
+ eligible.push({
888
+ repo: repo.path,
889
+ post: repo.post,
890
+ pr: candidate.pr,
891
+ head: candidate.head,
892
+ });
893
+ }
894
+ }
895
+ eligible.sort((a, b) => a.pr - b.pr);
896
+ return {
897
+ gate,
898
+ skips,
899
+ eligible,
900
+ launch: gate === "open" ? (eligible[0] ?? null) : null,
901
+ };
902
+ }
903
+
904
+ const SETTLE_SKIP_REASONS: ReadonlySet<SkipReason> = new Set([
905
+ "reviewed-local",
906
+ "reviewed-remote",
907
+ "attempts-exhausted",
908
+ ]);
909
+
910
+ // A leftover pending on a head this tick will not launch again.
911
+ // reviewed-local/remote: THIS head's review finished, the complete POST
912
+ // did not. attempts-exhausted: the review died and will not retry, so the
913
+ // yellow dot must not stick forever. NOT reviewed-prior-head: that only
914
+ // proves an EARLIER head was reviewed; a pending on the current head is a
915
+ // live review (manual re-review) and must not be overwritten with success.
916
+ // Live ticks settle these; dry-run must not.
917
+ export function pendingReviewsToSettle(
918
+ skips: readonly TickSkip[],
919
+ repos: readonly Pick<TickRepoFacts, "path" | "pending">[],
920
+ ): { repo: string; pr: number; head: string }[] {
921
+ const out: { repo: string; pr: number; head: string }[] = [];
922
+ const seen = new Set<string>();
923
+ for (const skip of skips) {
924
+ if (!SETTLE_SKIP_REASONS.has(skip.reason)) continue;
925
+ const repo = repos.find((entry) => entry.path === skip.repo);
926
+ if (repo === undefined) continue;
927
+ if (
928
+ !repo.pending.some(
929
+ (entry) => entry.pr === skip.pr && entry.head === skip.head,
930
+ )
931
+ ) {
932
+ continue;
933
+ }
934
+ const key = `${skip.repo}:${skip.pr}:${skip.head}`;
935
+ if (seen.has(key)) continue;
936
+ seen.add(key);
937
+ out.push({ repo: skip.repo, pr: skip.pr, head: skip.head });
938
+ }
939
+ return out;
940
+ }
941
+
942
+ // The checks run in a FIXED order because the first hit is the reason a
943
+ // human reads in the log: draft → reviewed-local → local prior head →
944
+ // too-large → reviewed-remote → remote prior marker → in-flight → attempts.
945
+ // The same-head checks run BEFORE the prior-head ones so the more specific
946
+ // reason always wins. in-flight sits after "already reviewed" (a completed
947
+ // review is more specific than a pending status) and before attempts, so a
948
+ // live run is not launched a second time just because attempts is still 1.
949
+ //
950
+ // The re-arm policy: under on_push (the original behavior) a new push
951
+ // changes the head, every (pr, head) key is fresh by construction, and an
952
+ // updated PR becomes eligible again — with auto-post the comment tracks the
953
+ // live head. Under the DEFAULT (on_push: false) each PR is reviewed ONCE:
954
+ // any prior review of the PR number — a local findings.json at any head,
955
+ // or any pr-hero marker comment whatever it declares (a legacy headless
956
+ // marker proves a review happened even though it covers no specific head) —
957
+ // skips it as `reviewed-prior-head`, so a push never re-bills a review.
958
+ function candidateSkipReason(
959
+ repo: TickRepoFacts,
960
+ candidate: WatchPrCandidate,
961
+ ): SkipReason | null {
962
+ if (candidate.isDraft) return "draft";
963
+ if (
964
+ repo.localReviews.some(
965
+ (r) => r.pr === candidate.pr && r.head === candidate.head,
966
+ )
967
+ ) {
968
+ return "reviewed-local";
969
+ }
970
+ if (!repo.onPush && repo.localReviews.some((r) => r.pr === candidate.pr)) {
971
+ return "reviewed-prior-head";
972
+ }
973
+ // The size gate (size-gate.ts) — a COST skip, not a quality judgement and
974
+ // not a failure. It sits here, after the local review checks and before
975
+ // the remote ones, because the shell can settle it from facts it already
976
+ // holds and thereby skip the per-PR comments fetch for an oversized PR.
977
+ //
978
+ // Three properties this skip MUST have, each of which a later change could
979
+ // quietly break:
980
+ //
981
+ // (a) It does NOT consume an attempt. MAX_WATCH_ATTEMPTS exists for a
982
+ // POISON PR — one that keeps killing the review — and attempts are
983
+ // counted from run artifacts, which a gate skip never creates (the
984
+ // CLI gate fires before createPrRunDir). Nothing here touches the
985
+ // attempts bookkeeping below, and nothing here may start.
986
+ // (b) It writes NO review marker, local or remote. A force-push can
987
+ // shrink a PR back under the limits, and it must become eligible on
988
+ // the very next tick — so the verdict is RECOMPUTED every tick from
989
+ // live gh counters and never persisted anywhere.
990
+ // (c) It does NOT arm the on_push "one review per PR" state. That state
991
+ // is armed by a findings.json or a marker comment, both of which
992
+ // only a review that actually ran produces. A skip is not a review;
993
+ // treating it as one would permanently retire the PR.
994
+ if (repo.tooLarge.includes(candidate.pr)) return "too-large";
995
+ // The other end of the same instrument: everything changed is excluded
996
+ // generated content, so a review would read an empty diff. Same three
997
+ // properties as above — no attempt, no marker, recomputed every tick.
998
+ if (repo.nothingToReview.includes(candidate.pr)) return "nothing-to-review";
999
+ const remote = repo.remoteHeads.find((r) => r.pr === candidate.pr);
1000
+ if ((remote?.heads ?? []).includes(candidate.head)) {
1001
+ return "reviewed-remote";
1002
+ }
1003
+ if (!repo.onPush && remote?.markerSeen === true) {
1004
+ return "reviewed-prior-head";
1005
+ }
1006
+ // Cross-machine in-flight lock: a pending `pr-hero` commit status on this
1007
+ // head, younger than IN_FLIGHT_TTL_MS. Same three properties as too-large
1008
+ // (no attempt consumed, no marker written, recomputed every tick) PLUS it
1009
+ // is the thing that closes the accepted ~10-min dual-watcher race for as
1010
+ // long as the first review is actually running.
1011
+ if (
1012
+ repo.inFlight.some(
1013
+ (entry) => entry.pr === candidate.pr && entry.head === candidate.head,
1014
+ )
1015
+ ) {
1016
+ return "in-flight";
1017
+ }
1018
+ const attempts =
1019
+ repo.attempts.find(
1020
+ (a) => a.pr === candidate.pr && a.head === candidate.head,
1021
+ )?.count ?? 0;
1022
+ if (attempts >= MAX_WATCH_ATTEMPTS) return "attempts-exhausted";
1023
+ return null;
1024
+ }
1025
+
1026
+ // The pre-launch exclusion veto's pure half (design D6, prheroignore Phase
1027
+ // 6): tier 2 in gatherRepoFacts (watch/watch.ts) only runs a per-file rescue for a
1028
+ // candidate whose AGGREGATE already exceeds a limit, so a PR whose aggregate
1029
+ // is already under both limits — but whose changed files are ALL excluded
1030
+ // content — never gets a per-file evaluation at all. Without this veto it
1031
+ // launches straight into an empty effective diff, the CLI exits before
1032
+ // creating a run dir, and with no run dir the attempts guard cannot see it —
1033
+ // so it relaunches every tick, burning the daily cap and the tick's one
1034
+ // launch slot on a PR the size gate would have rescued anyway.
1035
+ //
1036
+ // SAME truncation guard as tier 2 (`perFile.length >= candidateChangedFiles`),
1037
+ // carried here because under-counting in THIS direction is the OPPOSITE
1038
+ // failure of tier 2's own under-count risk: tier 2 under-counting falsely
1039
+ // RESCUES a monster PR, while under-counting here would falsely VETO a
1040
+ // launch tier 1 already cleared — silently dropping a real review. Both
1041
+ // directions are closed by the same one-line guard.
1042
+ export function preLaunchExclusionVeto(
1043
+ perFile: NumstatFile[],
1044
+ candidateChangedFiles: number,
1045
+ gateConfig: SizeGateConfig,
1046
+ ): boolean {
1047
+ if (perFile.length < candidateChangedFiles) return false;
1048
+ const verdict = evaluateSizeGate(perFile, gateConfig);
1049
+ return verdict.ok && verdict.effectiveFiles === 0;
1050
+ }
1051
+
1052
+ // ---------------------------------------------------------------------------
1053
+ // watch.log — append-only, one line per event, and the daily-cap COUNTER:
1054
+ // today's `launched` lines ARE the count, no separate state file. The
1055
+ // launched line is appended BEFORE the spawn on purpose (fail-safe
1056
+ // direction: a crash mid-review must still count toward the cap — err
1057
+ // toward counting, because the failure mode of over-counting is a skipped
1058
+ // review and the failure mode of under-counting is unbounded spend).
1059
+
1060
+ // LOCAL-time ISO 8601 with the numeric offset, never toISOString's UTC: the
1061
+ // cap is a local-calendar-day budget, and a UTC date would roll the counter
1062
+ // over at whatever local hour UTC midnight happens to be.
1063
+ export function localIsoTimestamp(d: Date): string {
1064
+ const pad = (n: number): string => String(n).padStart(2, "0");
1065
+ const offsetMinutes = -d.getTimezoneOffset();
1066
+ const sign = offsetMinutes < 0 ? "-" : "+";
1067
+ const abs = Math.abs(offsetMinutes);
1068
+ return (
1069
+ `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` +
1070
+ `T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}` +
1071
+ `${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`
1072
+ );
1073
+ }
1074
+
1075
+ export function logLine(ts: string, text: string): string {
1076
+ return `${ts} ${text}`;
1077
+ }
1078
+
1079
+ export function skipLine(
1080
+ ts: string,
1081
+ repoBase: string,
1082
+ pr: number,
1083
+ headSha: string,
1084
+ reason: SkipReason,
1085
+ ): string {
1086
+ return `${ts} skip repo=${repoBase} pr=${pr} head=${headSha.slice(0, 8)} reason=${reason}`;
1087
+ }
1088
+
1089
+ // THE format contract with countLaunchedToday below — change them together.
1090
+ export function launchedLine(
1091
+ ts: string,
1092
+ pr: number,
1093
+ repoBase: string,
1094
+ headSha: string,
1095
+ ): string {
1096
+ return `${ts} launched pr=${pr} repo=${repoBase} head=${headSha.slice(0, 8)}`;
1097
+ }
1098
+
1099
+ export interface ReviewOutcome {
1100
+ pr: number;
1101
+ ok: boolean;
1102
+ exitCode: number;
1103
+ counts: { blocking: number; advisory: number } | null;
1104
+ }
1105
+
1106
+ export function outcomeLine(
1107
+ ts: string,
1108
+ repoBase: string,
1109
+ outcome: ReviewOutcome,
1110
+ ): string {
1111
+ const status = outcome.ok ? "status=ok" : "status=failed";
1112
+ const detail = outcome.ok
1113
+ ? outcome.counts === null
1114
+ ? ""
1115
+ : ` blocking=${outcome.counts.blocking} advisory=${outcome.counts.advisory}`
1116
+ : ` exit=${outcome.exitCode}`;
1117
+ return `${ts} outcome pr=${outcome.pr} repo=${repoBase} ${status}${detail}`;
1118
+ }
1119
+
1120
+ // Counts today's launches back out of the raw log text. dayPrefix is the
1121
+ // local "YYYY-MM-DD" — the first 10 chars of localIsoTimestamp, so writer
1122
+ // and counter agree on what "today" means by construction. The match is
1123
+ // deliberately narrow (timestamp token, then the literal `launched` token):
1124
+ // skip/outcome/free-text lines must never inflate the cap, and a foreign
1125
+ // line must never crash the parse.
1126
+ export function countLaunchedToday(logText: string, dayPrefix: string): number {
1127
+ let count = 0;
1128
+ for (const line of logText.split("\n")) {
1129
+ const match = /^(\S+)\s+launched(?:\s|$)/.exec(line);
1130
+ if (match === null) continue;
1131
+ if ((match[1] ?? "").startsWith(dayPrefix)) count++;
1132
+ }
1133
+ return count;
1134
+ }
1135
+
1136
+ export interface LastActivity {
1137
+ launched: string | null;
1138
+ outcome: string | null;
1139
+ }
1140
+
1141
+ // The status view's "what happened last": the FINAL launched and outcome
1142
+ // lines of the log, whole — the line already carries its timestamp, pr,
1143
+ // repo and result, so re-parsing it into fields would only lose fidelity.
1144
+ // Same event-token discipline as the cap counter: free text never matches.
1145
+ export function lastLogActivity(logText: string): LastActivity {
1146
+ let launched: string | null = null;
1147
+ let outcome: string | null = null;
1148
+ for (const line of logText.split("\n")) {
1149
+ if (/^\S+\s+launched(?:\s|$)/.test(line)) launched = line;
1150
+ else if (/^\S+\s+outcome(?:\s|$)/.test(line)) outcome = line;
1151
+ }
1152
+ return { launched, outcome };
1153
+ }
1154
+
1155
+ // ---------------------------------------------------------------------------
1156
+ // The lockfile — belt and suspenders under cron or a hand-run tick (launchd
1157
+ // itself is already single-instance per label). Advisory: the file holds a
1158
+ // PID, a live PID means "another tick is running, exit quietly", a dead one
1159
+ // is stolen.
1160
+
1161
+ export function parseLockPid(raw: string): number | null {
1162
+ const trimmed = raw.trim();
1163
+ if (!/^\d+$/.test(trimmed)) return null;
1164
+ const pid = Number(trimmed);
1165
+ return pid > 0 ? pid : null;
1166
+ }
1167
+
1168
+ // ---------------------------------------------------------------------------
1169
+ // The launchd agent (macOS). Rendering is pure string-out so a test can pin
1170
+ // the exact plist; loading it is the shell's job.
1171
+
1172
+ export const WATCH_LAUNCHD_LABEL = "io.crysk.watch";
1173
+
1174
+ export interface WatchPlistInput {
1175
+ // The engine's OWN invocation (assets.ts's selfInvocation()), never a fixed
1176
+ // runtime + entry-script pair and never a bare `pr-hero`. Two traps, one
1177
+ // field:
1178
+ //
1179
+ // launchd starts agents with a bare-bones PATH (/usr/bin:/bin) that has
1180
+ // never heard of bun, so a name that resolves in every terminal resolves in
1181
+ // nothing launchd starts — selfInvocation answers absolute on both halves.
1182
+ //
1183
+ // And a compiled binary IS the entry: it contributes no script path at all.
1184
+ // The pair could not say that, so it rendered `<binary> /$bunfs/root/cli.ts
1185
+ // watch --once`, whose second argument exists on no machine. launchd ran it
1186
+ // every interval, the CLI rejected the path as an unknown command every
1187
+ // time, into a log nobody reads — and `watch install` reported success.
1188
+ invocation: SelfInvocation;
1189
+ intervalSeconds: number;
1190
+ // launchd's stdout/stderr for the tick process — the SEPARATE launchd.log,
1191
+ // so the spawned review's progress noise can never land in watch.log and
1192
+ // corrupt the cap counter.
1193
+ logPath: string;
1194
+ // The CURRENT process's PATH, captured at install time: the tick spawns
1195
+ // gh, git, codegraph and claude, none of which live on launchd's default
1196
+ // PATH — the install-time shell knows where they are, launchd does not.
1197
+ pathEnv: string;
1198
+ }
1199
+
1200
+ export function renderWatchPlist(input: WatchPlistInput): string {
1201
+ const programArguments = [input.invocation.command, ...input.invocation.args];
1202
+ const lines = [
1203
+ `<?xml version="1.0" encoding="UTF-8"?>`,
1204
+ `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,
1205
+ `<plist version="1.0">`,
1206
+ `<dict>`,
1207
+ ` <key>Label</key>`,
1208
+ ` <string>${WATCH_LAUNCHD_LABEL}</string>`,
1209
+ ` <key>ProgramArguments</key>`,
1210
+ ` <array>`,
1211
+ ...[...programArguments, "watch", "--once"].map(
1212
+ (arg) => ` <string>${xmlEscape(arg)}</string>`,
1213
+ ),
1214
+ ` </array>`,
1215
+ ` <key>StartInterval</key>`,
1216
+ ` <integer>${input.intervalSeconds}</integer>`,
1217
+ ` <key>StandardOutPath</key>`,
1218
+ ` <string>${xmlEscape(input.logPath)}</string>`,
1219
+ ` <key>StandardErrorPath</key>`,
1220
+ ` <string>${xmlEscape(input.logPath)}</string>`,
1221
+ ` <key>EnvironmentVariables</key>`,
1222
+ ` <dict>`,
1223
+ ` <key>PATH</key>`,
1224
+ ` <string>${xmlEscape(input.pathEnv)}</string>`,
1225
+ ` </dict>`,
1226
+ `</dict>`,
1227
+ `</plist>`,
1228
+ ];
1229
+ return `${lines.join("\n")}\n`;
1230
+ }
1231
+
1232
+ function xmlEscape(text: string): string {
1233
+ return text
1234
+ .replaceAll("&", "&amp;")
1235
+ .replaceAll("<", "&lt;")
1236
+ .replaceAll(">", "&gt;");
1237
+ }
1238
+
1239
+ // StartInterval read back OUT of an installed plist, for `watch status`.
1240
+ // TOLERANT (null, never throw) against the module's loud grain: the plist
1241
+ // on disk may predate this parser or have been edited by hand, and status
1242
+ // is a read-only report — "installed (interval unreadable)" is the honest
1243
+ // answer, a crash is not.
1244
+ export function parsePlistInterval(plist: string): number | null {
1245
+ const match = /<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/.exec(
1246
+ plist,
1247
+ );
1248
+ if (match === null) return null;
1249
+ const seconds = Number(match[1]);
1250
+ return seconds > 0 ? seconds : null;
1251
+ }
1252
+
1253
+ // ---------------------------------------------------------------------------
1254
+ // The macOS notification — argv for `osascript`, built here so the
1255
+ // AppleScript string escaping is testable. The args are spawned as an ARRAY
1256
+ // (no shell anywhere), so the only escaping that exists is AppleScript's
1257
+ // own string literal: backslash and double quote.
1258
+
1259
+ export function osascriptNotifyArgs(title: string, text: string): string[] {
1260
+ const quote = (s: string): string =>
1261
+ `"${s.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
1262
+ return [
1263
+ "osascript",
1264
+ "-e",
1265
+ `display notification ${quote(text)} with title ${quote(title)}`,
1266
+ ];
1267
+ }
1268
+
1269
+ export function outcomeNotificationText(outcome: ReviewOutcome): string {
1270
+ if (!outcome.ok) {
1271
+ return `PR #${outcome.pr} review failed (exit ${outcome.exitCode})`;
1272
+ }
1273
+ if (outcome.counts === null) {
1274
+ return `PR #${outcome.pr} reviewed (counts unavailable)`;
1275
+ }
1276
+ return (
1277
+ `PR #${outcome.pr}: ${outcome.counts.blocking} blocking, ` +
1278
+ `${outcome.counts.advisory} advisory`
1279
+ );
1280
+ }
1281
+
1282
+ // ---------------------------------------------------------------------------
1283
+ // `watch status` — a read-only report over whatever exists. The shell
1284
+ // gathers the facts (it never throws on an absent piece: no config, no log,
1285
+ // no plist and no lock are all ordinary states worth reporting), and this
1286
+ // renders them — same shape as the dry-run printer, pure so a test can pin
1287
+ // every branch.
1288
+
1289
+ export interface WatchStatusFacts {
1290
+ // Named for the file it carries (~/.prhero/watch.json), never `configPath`
1291
+ // — C5 retired that name on PrheroLayout because it stopped identifying a
1292
+ // file. This field is the one consumer that retirement provably cannot
1293
+ // reach: it belongs to a DIFFERENT type, so `watchConfigPath: paths.
1294
+ // watchConfigPath` in watch/watch.ts would have compiled just as happily as
1295
+ // `configPath:` did. Renamed by hand, and pinned by a test, because a
1296
+ // mechanism that cannot enforce a rule has to be paired with one that can.
1297
+ watchConfigPath: string;
1298
+ // null = no config file. configError carries the parse failure when the
1299
+ // file exists but is invalid — status REPORTS brokenness instead of
1300
+ // crashing over it, because a status you cannot run on a broken setup is
1301
+ // useless exactly when you need it.
1302
+ config: WatchConfig | null;
1303
+ configError: string | null;
1304
+ launchedToday: number;
1305
+ plistPath: string;
1306
+ installed: boolean;
1307
+ // null when not installed OR the plist's StartInterval is unreadable.
1308
+ intervalSeconds: number | null;
1309
+ lockPid: number | null;
1310
+ lastLaunched: string | null;
1311
+ lastOutcome: string | null;
1312
+ }
1313
+
1314
+ export function renderWatchStatus(facts: WatchStatusFacts): string[] {
1315
+ const row = (label: string, value: string): string =>
1316
+ ` ${label.padEnd(13)}${value}`;
1317
+ const lines = ["crysk watch — status", ""];
1318
+ if (facts.configError !== null) {
1319
+ lines.push(
1320
+ row("config", `INVALID — ${facts.watchConfigPath}: ${facts.configError}`),
1321
+ );
1322
+ } else if (facts.config === null) {
1323
+ lines.push(
1324
+ row(
1325
+ "config",
1326
+ `none (${facts.watchConfigPath}) — run "crysk watch add" inside a ` +
1327
+ "repo to opt it in",
1328
+ ),
1329
+ );
1330
+ } else {
1331
+ lines.push(row("config", facts.watchConfigPath));
1332
+ if (facts.config.repos.length === 0) {
1333
+ lines.push(row("", 'no repos watched — "crysk watch add" opts one in'));
1334
+ }
1335
+ for (const repo of facts.config.repos) {
1336
+ lines.push(
1337
+ row(
1338
+ "",
1339
+ `${repo.path} post=${repo.post} on_push=${repo.onPush} ` +
1340
+ `max_lines=${repo.maxChangedLines} max_files=${repo.maxChangedFiles}`,
1341
+ ),
1342
+ );
1343
+ }
1344
+ lines.push(
1345
+ row(
1346
+ "today",
1347
+ `${facts.launchedToday} of ${facts.config.dailyCap} launches used`,
1348
+ ),
1349
+ );
1350
+ lines.push(
1351
+ row(
1352
+ "window",
1353
+ facts.config.window === null
1354
+ ? "always"
1355
+ : `${facts.config.window.start}-${facts.config.window.end}`,
1356
+ ),
1357
+ );
1358
+ }
1359
+ // Without a valid config there is no cap to report against, but the log
1360
+ // exists independently — the raw count still says whether money moved.
1361
+ if (facts.config === null || facts.configError !== null) {
1362
+ lines.push(row("today", `${facts.launchedToday} launched`));
1363
+ }
1364
+ lines.push(
1365
+ row(
1366
+ "launchd",
1367
+ facts.installed
1368
+ ? facts.intervalSeconds === null
1369
+ ? `installed (${facts.plistPath}, interval unreadable)`
1370
+ : `installed — one tick every ${formatIntervalSeconds(facts.intervalSeconds)}`
1371
+ : 'not installed — run "crysk watch install" to start ticking',
1372
+ ),
1373
+ );
1374
+ lines.push(
1375
+ row(
1376
+ "lock",
1377
+ facts.lockPid === null
1378
+ ? "free"
1379
+ : `held by pid ${facts.lockPid} (a tick is running)`,
1380
+ ),
1381
+ );
1382
+ lines.push(row("last launch", facts.lastLaunched ?? "none recorded"));
1383
+ lines.push(row("last outcome", facts.lastOutcome ?? "none recorded"));
1384
+ return lines;
1385
+ }
1386
+
1387
+ function formatIntervalSeconds(seconds: number): string {
1388
+ return seconds % 60 === 0 ? `${seconds / 60} min` : `${seconds}s`;
1389
+ }