crysk 0.0.0 → 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 +609 -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/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 +81 -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,3575 @@
1
+ // Everything local mode (ROADMAP B0) must decide BEFORE it is allowed to
2
+ // spend money, expressed as pure functions so it is all testable offline.
3
+ // The CLI in cli.ts is the I/O shell around these; nothing here touches the
4
+ // filesystem, git, or the network — a preflight that needs a live repo to be
5
+ // tested is a preflight that gets tested once, live, at $10 a go.
6
+
7
+ import { existsSync } from "node:fs";
8
+ import { mkdir } from "node:fs/promises";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ import {
12
+ CI_REVIEW_POLICY_MODES,
13
+ type CiReviewPolicyMode,
14
+ } from "#ci/review-policy";
15
+ import type { EffectiveConfig } from "#config/config";
16
+ import type {
17
+ ModelGateway,
18
+ RouteMapping,
19
+ RoutingConfig,
20
+ RunnerBackend,
21
+ } from "#model/routing";
22
+ import type { SuspicionPrior } from "#review/prompt-set";
23
+ import { type AgentSpec, isSafeSlug, type ReviewSpec } from "#review/spec";
24
+ import {
25
+ ADJUDICATED_TAGS,
26
+ type TriageTag,
27
+ type TriageVerdict,
28
+ } from "#triage/triage";
29
+ import { type EngineAssets, resolveEngineAssets } from "../assets";
30
+ import { type BrandEnvValue, readBrandEnv } from "../brand";
31
+ import { REPO_DIR_NAME } from "../brand-paths";
32
+ // CliError/CliUsageError and the git/ref pure helpers used to be DEFINED here
33
+ // and imported by value into git.ts — the bottom layer depending on a
34
+ // review-domain module. They live in ../errors and ../git/refs; this file
35
+ // imports only the ones it uses itself.
36
+ import { CliError, CliUsageError, withUsageClass } from "../errors";
37
+ import { DEFAULT_BASE_REF, listPaths } from "../git/refs";
38
+ import { redactDiagnostic } from "../security/redact";
39
+ // review/size-gate.ts imports only a TYPE from here, so this is not a runtime
40
+ // cycle — the type import is erased and size-gate has no load-time
41
+ // dependency on this module.
42
+ import { DEFAULT_SIZE_GATE, unquotePath } from "./size-gate";
43
+
44
+ // The lab's production value. Also the single biggest per-hunter cost lever
45
+ // in the whole engine: every hop is another round of tool calls against the
46
+ // tree, and hunter cost scales with hops far more sharply than with diff
47
+ // size. The fixture eval runs at 4 precisely because 12 is not cheap.
48
+ export const DEFAULT_HOP_BUDGET = 12;
49
+
50
+ // watch install's default StartInterval, in minutes. 15 keeps a fresh PR's
51
+ // wait bounded by the tick while staying far below GitHub's rate-limit radar
52
+ // (a tick is one `pr list` per repo plus a comments read per candidate).
53
+ export const DEFAULT_WATCH_INTERVAL_MIN = 15;
54
+
55
+ // gc install's default StartInterval, in minutes. The 72h TTL only
56
+ // evaluates when GC actually runs; 6h is frequent enough that a merged PR
57
+ // does not sit until tomorrow, and cheap (gh view per tree, no LLM).
58
+ export const DEFAULT_GC_INTERVAL_MIN = 360;
59
+
60
+ export const DEFAULT_HEAD_REF = "HEAD";
61
+
62
+ // Keep this in sync with prompts/summarizer.md. The prompt remains the source
63
+ // of truth for execution when no model override is configured; this value is
64
+ // only the honest model label shown in a preflight plan.
65
+ export const DEFAULT_SUMMARY_MODEL = "haiku";
66
+
67
+ export interface CliOptions {
68
+ // Relative on purpose: parseArgs is pure, so "resolve against cwd" is the
69
+ // caller's job, not a hidden dependency on process.cwd() in a pure function.
70
+ repo: string;
71
+ // UNSET when no --base was given, never pre-filled with a literal branch
72
+ // name. Resolving the real default branch needs git (the remote head), and
73
+ // parseArgs must stay pure — so the shell in cli.ts finishes the job via
74
+ // resolveBaseRef. A default baked in here would be a wrong ref that nothing
75
+ // downstream can tell apart from one the user asked for.
76
+ base?: string;
77
+ head: string;
78
+ agents?: string;
79
+ out?: string;
80
+ // Gotchas describe the REPO, not the commit under review, so they must be
81
+ // supplyable from outside the reviewed tree — see the note in cli.ts. The
82
+ // same is true of the config: parity triggers and priors are properties of
83
+ // the project, and requiring them in-tree silently disables the conditional
84
+ // parity hunter on any tree you cannot add a file to.
85
+ gotchas?: string;
86
+ config?: string;
87
+ model?: string;
88
+ // Summary activation is tri-state at parse time: undefined means no flag,
89
+ // so review can apply flag > config > the default-on setting.
90
+ summary?: boolean;
91
+ // The scout is tri-state at parse time: undefined means no flag,
92
+ // so review can apply flag > config > default (false).
93
+ scout?: boolean;
94
+ // `--shared-prefix` / `--no-shared-prefix`. Undefined means the default,
95
+ // which is ON (see resolveSharedPrefix).
96
+ sharedPrefix?: boolean;
97
+ // Independent model knob (§3.7), and NOT exercised by M6 — the whole
98
+ // control corpus is sonnet, so ratifying this is ratifying a flag, not a
99
+ // second variable. `--model` still outranks it (the JD override rule).
100
+ scoutModel?: string;
101
+ // Item 7: widen discovery to full B..H on a re-review. Default OFF — a
102
+ // second push is delta-scoped unless asked otherwise. Verification,
103
+ // triage, and classification still run (R2-C5). Review-only, like --scout.
104
+ full: boolean;
105
+ // T5b: with --pr --ci, also have the CI adjudicator rule on each pending
106
+ // dismissal of a blocking finding. Set by a /crysk recheck comment. Absent
107
+ // means off.
108
+ adjudicate?: boolean;
109
+ hopBudget: number;
110
+ dryRun: boolean;
111
+ yes: boolean;
112
+ // PR mode (ROADMAP B1). Set only by --pr: head and base both come from the
113
+ // PR record itself, so parseArgs rejects --base/--head/--two-dot beside it
114
+ // — a hand-picked endpoint would silently contradict the PR's own range.
115
+ // "current" is bare `--pr`: resolve the PR from the operator checkout's
116
+ // current branch at run time (the shell owns that gh call). Absent means
117
+ // local mode.
118
+ pr?: number | "current";
119
+ // Publish the review as ONE marked PR comment (ROADMAP B2) — created the
120
+ // first time, updated in place after, never stacked. Tri-state at parse time:
121
+ // undefined means no flag, resolved via flag > config > default (false).
122
+ // Requires --pr (parseArgs enforces it): a comment needs a PR to land on.
123
+ post?: boolean;
124
+ // post/triage only (ROADMAP B6/B6c): the run dir to read findings.json +
125
+ // diff.patch (post and triage reply) from, instead of producing a new run.
126
+ // Required by both; parseArgs enforces it.
127
+ from?: string;
128
+ // `status` only (ROADMAP S9): print one JSON object on stdout instead of the human lines.
129
+ // Refused on every other command, so the flag never parses and then does nothing.
130
+ json?: boolean;
131
+ // `status` only: poll GitHub until an in-flight (or newly-triggered) PR review settles, then
132
+ // emit the settled status. Refused on every other command.
133
+ wait?: boolean;
134
+ // The escape hatch for change 3's default. See resolveDiffRange's WHY: the
135
+ // three-dot (merge-base) range is right almost always, and this flag exists
136
+ // for the rare caller who genuinely wants the literal two-point diff.
137
+ twoDot: boolean;
138
+ // watch only (ROADMAP B3): which watch action was asked for. "once" is one
139
+ // tick (the launchd unit of work), install/uninstall manage the launchd
140
+ // agent, add/remove/status manage and inspect the watch config so nobody
141
+ // hand-edits JSON. Required for `watch` — a bare `pr-hero watch` has no
142
+ // daemon mode to fall into, so it fails loud instead of hanging.
143
+ watch?: "once" | "install" | "uninstall" | "add" | "remove" | "status";
144
+ // gc install/uninstall/status manage a SEPARATE launchd agent from the
145
+ // watcher: it runs `pr-hero gc` (no reviews, no watch.json, no window/cap).
146
+ // Unset means the collector itself.
147
+ gc?: "install" | "uninstall" | "status";
148
+ // `skills install` (src/commands/skills.ts): the non-interactive install of
149
+ // pr-hero's agent skills into every detected coding agent. Its only
150
+ // subcommand; anything else after `skills` is a usage error.
151
+ skills?: "install";
152
+ // watch install and gc install: launchd StartInterval, in minutes.
153
+ interval?: number;
154
+ // watch add only: record on_push: true for the repo, so every new push
155
+ // re-arms its PRs. The default (false) reviews each PR once — see the
156
+ // re-arm policy note on candidateSkipReason in watch/preflight.ts.
157
+ onPush: boolean;
158
+ // Bypass the CI skips for THIS run: the size gate, review-policy
159
+ // admission, and (in CI) the budget ceiling. The GitHub comment
160
+ // `/crysk review` is what sets this flag from Actions. Deliberately
161
+ // does NOT imply --yes: the interactive cost-band prompt is a separate
162
+ // question from those skips.
163
+ force: boolean;
164
+ // usage only (W4 / #23): show every repo_id instead of the current
165
+ // checkout's origin-scoped view (spec "Operator-Wide View Via --all").
166
+ // Valid on no other command — a size-gate-style boolean, not a value
167
+ // flag, so `usage --all` and `usage` are the whole surface.
168
+ all: boolean;
169
+ // Size-gate overrides. UNSET means "use DEFAULT_SIZE_GATE"; 0 is a real,
170
+ // distinct value that DISABLES the limit, so these cannot default to 0.
171
+ maxChangedLines?: number;
172
+ maxChangedFiles?: number;
173
+ // `triage reply` sub-word (W1). Required for the triage command: the bare
174
+ // `triage --pr --from` verb was removed with comparison.json, so parseArgs rejects `triage` without it. Same pattern as watch's
175
+ // sub-words: `reply` is not its own command, so `pr-hero reply` still fails
176
+ // as unknown.
177
+ triage?: "reply";
178
+ finding?: string;
179
+ tag?: TriageTag;
180
+ bodyFile?: string;
181
+ verdict?: TriageVerdict;
182
+ issue?: number;
183
+ // reverts only (GitHub #41): the `git log --since=` window to mine for
184
+ // reverted/hotfixed PRs. A string, not a date, because git's own date
185
+ // parser accepts "24 months ago" as readily as "2025-01-01" and reusing it
186
+ // beats re-implementing it here. Unset means DEFAULT_REVERTS_SINCE — the
187
+ // shell applies it, so parseArgs stays pure and "the operator asked for a
188
+ // window" stays distinguishable from "nobody said".
189
+ since?: string;
190
+ // corpus only (GitHub #43/#44): the five candidate sources. At least one is
191
+ // REQUIRED (enforced post-loop, where the whole set is visible) — a bare
192
+ // `pr-hero corpus` would be a $0 no-op that looks like a scan. --proximity
193
+ // IMPLIES --fixes (proximity suspects are computed over the fix set),
194
+ // applied here so the shell never re-derives the implication. --issues
195
+ // upgrades a classified set and does NOT imply --fixes; it requires
196
+ // --fixes and/or --incidents (--proximity already implies --fixes).
197
+ fixes: boolean;
198
+ incidents: boolean;
199
+ issues: boolean;
200
+ proximity: boolean;
201
+ threads: boolean;
202
+ // corpus only: the proximity window in days, kept VERBATIM like --since —
203
+ // validateProximityDays in corpus/preflight.ts owns the 1..90 rule where
204
+ // the join that consumes it is tested. Unset means DEFAULT_PROXIMITY_DAYS.
205
+ proximityDays?: string;
206
+ // corpus only: csv of issue labels that mark a referenced issue as a bug.
207
+ // Unset means DEFAULT_BUG_LABELS. GitHub labels are case-sensitive, so the
208
+ // split (splitBugLabels) never lowercases. Requires --issues — a value
209
+ // flag of a source that is not on would be a silently dropped intention.
210
+ bugLabels?: string;
211
+ // mcp only (Canonical Store / MCP): optional socket or db path overrides.
212
+ socket?: string;
213
+ db?: string;
214
+ // upgrade & uninstall only
215
+ purge?: boolean;
216
+ check?: boolean;
217
+ reconcile?: boolean;
218
+ // activity only
219
+ kill?: number;
220
+ // config only
221
+ configSubcommand?: "set" | "unset" | "edit";
222
+ configKey?: string;
223
+ configValue?: string;
224
+ configLayer?: "person" | "team" | "watch";
225
+ edit?: boolean;
226
+ repoExplicit?: boolean;
227
+ // ROADMAP Pillar 3 (GitHub Actions CI). `ci` is the EXPLICIT flag only —
228
+ // `isCiEnvironment()` ORs it with the GITHUB_ACTIONS/CI env vars, which
229
+ // parseArgs (pure, no process.env read) cannot see. Both `budgetUsd` and
230
+ // `stepSummary` require `--ci` at parse time (the `--post`-requires-`--pr`
231
+ // precedent above): a spend ceiling or a summary toggle for a mode that
232
+ // never activates would be exactly the "silently dropped intention" the
233
+ // --bug-labels/--scout-model guards already refuse elsewhere in this file.
234
+ //
235
+ // Phase 4 (CI Scaffolding) gave `--ci` a SECOND, command-scoped meaning:
236
+ // on `review` it activates the CI headless shell (requires --pr); on
237
+ // `setup` it means "scaffold .github/workflows/crysk.yml instead of
238
+ // running the interactive wizard" — see `ci init`'s dedicated command
239
+ // below for the same scaffolding without touching `setup`'s wizard
240
+ // default. `budgetUsd`/`stepSummary` still require the REVIEW reading of
241
+ // `--ci` specifically (checked below), since neither means anything to
242
+ // scaffolding.
243
+ ci?: boolean;
244
+ // `ci init` — the same scaffolding as `setup --ci`, as its own command.
245
+ // Unset on every other command. "init" is the only sub-word today; kept
246
+ // as a literal union (not a bare boolean) so a future `ci status` has
247
+ // somewhere to go without a breaking change.
248
+ ciSubcommand?: "init";
249
+ // Unset means "no ceiling configured" (no gate, no disabled-ceiling
250
+ // warning — there is nothing to disable). <= 0, GIVEN explicitly, disables
251
+ // the ceiling too, but DOES warn: see ci/gates.ts's
252
+ // budgetDisabledWarningMessage for why the two are not the same state.
253
+ budgetUsd?: number;
254
+ // Tri-state like `summary`/`scout`: unset means "the shell's own default
255
+ // (on)", so `--step-summary` and `--no-step-summary` stay distinguishable
256
+ // from "nobody said".
257
+ stepSummary?: boolean;
258
+ // S4: the commit-status gate for a `review --ci` run, required at parse time
259
+ // like budgetUsd. `gate` (the CI default) turns the pr-hero commit status red
260
+ // on blocking findings, a size or budget skip, and a crash; `advisory` keeps
261
+ // today's posture. Unset means the run resolves it (resolveCiMode, pr/preflight).
262
+ ciMode?: "gate" | "advisory";
263
+ // `setup --ci` / `ci init` only: the re-review preset and how CI pays, for an
264
+ // agent that already asked the person. --ci-mode and --budget-usd also apply
265
+ // there; together they replace the questions setup asks in a terminal.
266
+ reviewLevel?: "minimal" | "balanced" | "thorough" | "manual";
267
+ billing?: "subscription" | "api";
268
+ }
269
+
270
+ // design.md 3.1's literal formula: Boolean(GITHUB_ACTIONS || CI || --ci).
271
+ // Pure — env arrives as a parameter (reviewPr's shell reads
272
+ // process.env.GITHUB_ACTIONS/CI and passes them in), so this stays offline-
273
+ // testable without process.env being a hidden dependency the way parseArgs
274
+ // itself refuses to have one. There is no `src/ci.ts` (design's proposed
275
+ // home for this function) — Phases 1-2 already folded the CI surface into
276
+ // ci/reporter.ts/ci/gates.ts instead, and this joins that same deviation
277
+ // rather than starting a third file for one function.
278
+ export function isCiEnvironment(
279
+ options: { ci?: boolean },
280
+ env: { GITHUB_ACTIONS?: string; CI?: string },
281
+ ): boolean {
282
+ return Boolean(env.GITHUB_ACTIONS || env.CI || options.ci);
283
+ }
284
+
285
+ export interface ParsedCli {
286
+ command:
287
+ | "review"
288
+ | "init"
289
+ | "setup"
290
+ | "doctor"
291
+ | "menu"
292
+ | "activity"
293
+ | "watch"
294
+ | "post"
295
+ | "triage"
296
+ | "status"
297
+ | "gc"
298
+ | "usage"
299
+ | "reverts"
300
+ | "corpus"
301
+ | "config"
302
+ | "mcp"
303
+ | "upgrade"
304
+ | "uninstall"
305
+ | "ci"
306
+ | "skills"
307
+ | "help";
308
+ options: CliOptions;
309
+ }
310
+
311
+ export const HELP_TEXT = `crysk — multi-agent review of a real repo + branch
312
+
313
+ Usage:
314
+ crysk [options] Open interactive terminal user interface (TTY)
315
+ crysk menu [options] Open interactive terminal user interface
316
+ crysk review [options] Review a branch (zero flags inside a configured repo)
317
+ crysk init [options] Scaffold <repo>/.crysk/ (config.json + gotchas.md)
318
+ crysk setup [options] Run interactive onboarding wizard
319
+ crysk setup --ci [--force] [--level <l>] [--ci-mode <m>] [--billing <b>] [--budget-usd <n>]
320
+ Scaffold .github/workflows/crysk.yml (or update
321
+ an existing pr-hero.yml) instead
322
+ of the wizard. Refuses to overwrite an existing
323
+ workflow unless --force is passed. Asks how CI
324
+ re-reviews (in a terminal) or takes the flags:
325
+ --level minimal|balanced|thorough|manual,
326
+ --ci-mode gate|advisory, --billing
327
+ subscription|api, --budget-usd (api only),
328
+ --max-changed-lines (default 4000).
329
+ Writes the level to .crysk/config.json and
330
+ prints a summary. Then checks gh and, in a
331
+ terminal, offers to install it and run gh auth
332
+ login
333
+ crysk skills install [--force]
334
+ Install the crysk, crysk-pr, triage and CI-setup skills into every detected coding agent (no TTY, no MCP)
335
+ crysk ci init [--force] Same scaffolding and flags as "setup --ci", as its own
336
+ command
337
+ crysk doctor [options] Check system tools and environment readiness
338
+ crysk activity [options] View currently running reviews and recent store history
339
+ crysk activity --kill <pid> [--yes]
340
+ Safely terminate a running review (checks process identity)
341
+ crysk upgrade [options] Upgrade crysk to latest version & sync agent assets
342
+ crysk uninstall [opts] Remove crysk daemons, MCP registrations & skills
343
+ crysk mcp [options] Start the read-only Model Context Protocol (MCP)
344
+ server over stdio for AI coding assistants. Read-only, $0
345
+ crysk post --pr <n> --from <run-dir> [--dry-run]
346
+ Publish a PREVIOUSLY RUN review's findings.json
347
+ to PR <n>, reading it (and diff.patch) off disk
348
+ instead of running a fresh review — the same
349
+ fetch → match → post flow --pr --post uses.
350
+ --dry-run renders the planned comment set at $0
351
+ and posts nothing (the only way to preview a
352
+ plan, since --pr --dry-run returns before any
353
+ findings exist)
354
+ crysk triage reply --pr <n> --from <run-dir> --finding <id> --tag <tag>
355
+ --body-file <path> [--verdict <v>] [--issue <n>] [--dry-run]
356
+ Post one triage reply. The driver resolves the
357
+ parent from the posted <!-- crysk-finding
358
+ marker (never path/line), renders the marker +
359
+ badge, posts, and resolves the inline review
360
+ thread. --body-file is reasoning prose only.
361
+ --dry-run prints the parent and posts nothing
362
+ crysk status --pr <n> [--wait] [--json]
363
+ Read the PR's crysk gate, posted findings and
364
+ next action, through gh only and read-only. With
365
+ --wait, poll until an in-flight or newly-triggered
366
+ review settles before printing. With
367
+ --json, one JSON object on stdout (schema
368
+ pr-hero.status/v1); without it, a few lines on
369
+ stderr. Exits 1 with no stdout when any read
370
+ fails. Skills drive review -> reply -> fix -> wait
371
+ from its next_action
372
+ crysk reverts [options] Mine the repo's default branch for PRs that were
373
+ later reverted or hotfixed, and write them as
374
+ markdown CANDIDATES for human confirmation. Runs
375
+ git log + gh api only: no review, no scoring, no
376
+ labelling of what the defect was, $0
377
+ crysk corpus [options] Widen the known-bad corpus beyond reverts with
378
+ five candidate sources, gated by their flags:
379
+ --fixes (fix-shaped merged PRs, blame-resolved
380
+ to their likely introducer), --incidents
381
+ (incident/outage keywords in title/body),
382
+ --issues (upgrade classified PRs that reference
383
+ a bug-labelled GitHub issue), --proximity
384
+ (prior PRs on the same files when the introducer
385
+ did not resolve), --threads (defects review DID
386
+ catch, from resolved review threads). At least
387
+ one source is required; --issues needs --fixes
388
+ and/or --incidents. All output is CANDIDATES
389
+ for human confirmation. git log + gh api only:
390
+ no review, no scoring, $0
391
+ crysk watch --once Run ONE watcher tick over ~/.crysk/watch.json:
392
+ pick the next unreviewed open PR across the
393
+ configured repos and review it. launchd (or cron)
394
+ is the scheduler; this never daemonizes
395
+ crysk watch add Opt the current repo (or --repo) into the watch
396
+ config; --post makes its reviews publish to the
397
+ PR, --on-push re-reviews on every push,
398
+ --max-changed-lines/--max-changed-files set the
399
+ repo's size gate.
400
+ Idempotent — re-adding updates the flags
401
+ crysk watch remove Remove the current repo (or --repo) from the
402
+ watch config (idempotent)
403
+ crysk watch status Read-only: config summary, today's launch count
404
+ vs the cap, launchd state, lock, last activity
405
+ crysk watch install Install the macOS launchd agent that runs
406
+ "watch --once" every --interval minutes
407
+ crysk watch uninstall Unload and remove that launchd agent
408
+ crysk gc [--dry-run] [--repo <dir>]
409
+ Collect review worktrees under ~/.crysk/repos
410
+ that are merged/closed or idle >72h. --dry-run
411
+ prints the table and removes nothing. --repo
412
+ scopes to one origin; default is the whole home
413
+ crysk gc install Install the macOS launchd agent that runs
414
+ "crysk gc" every --interval minutes (default
415
+ ${DEFAULT_GC_INTERVAL_MIN} = 6h). No reviews,
416
+ no watch.json — the $0 sweeper so trees do not
417
+ wait for a review or the watcher
418
+ crysk gc uninstall Unload and remove that launchd agent
419
+ crysk gc status Read-only: whether the GC agent is installed
420
+ crysk usage [--all] Print the observability store's per-run rows
421
+ (cost, tokens, findings) for the current
422
+ checkout's origin — every review, local and
423
+ PR, auto-ingests into it. --all shows every
424
+ origin instead of just this one. Read-only, $0
425
+ crysk config [options] Print every config key's effective value and the
426
+ LAYER it came from — global (~/.crysk/config.json),
427
+ repo (<repo>/.crysk/config.json), capped (the
428
+ global ceiling narrowed the repo's value away) or
429
+ default (neither file spoke). Names both file
430
+ paths whether or not they exist. Resolves through
431
+ the same merge a review does, so it cannot drift
432
+ from what actually runs. Read-only — it never
433
+ writes either file. $0
434
+
435
+ Options:
436
+ --repo <dir> Repository to review (default: current directory)
437
+ --pr [n] Review GitHub PR #n — or, with no number, the PR that
438
+ belongs to the current branch. head and base come from
439
+ gh, the review runs in a detached worktree with its
440
+ own codegraph index, and the result is written to the
441
+ run directory's findings.json. Excludes --base,
442
+ --head and --two-dot
443
+ --post With --pr only: publish the review to the PR as one
444
+ marked comment — created the first time, updated in
445
+ place on re-runs, never stacked. Explicit, never a
446
+ default. With watch add: record post: true, so the
447
+ watcher-launched reviews of that repo publish
448
+ --base <ref> Base branch or sha. Default, in order: the config's
449
+ default_base, then the remote head
450
+ (refs/remotes/origin/HEAD), then ${DEFAULT_BASE_REF}
451
+ --head <ref> Head branch or sha (default: ${DEFAULT_HEAD_REF})
452
+ --agents <dir> Prompt-set directory. Default, in order: the config's
453
+ agents_dir (relative paths resolve against the config
454
+ file), then PRHERO_AGENTS_DIR
455
+ --out <dir> Run directory; must live OUTSIDE the reviewed repo
456
+ (default: ~/.crysk/repos/<origin>/runs/<sha>-<n>).
457
+ For reverts and corpus: the file to write instead of
458
+ stdout
459
+ --since <git-date> reverts and corpus only: how far back to scan the
460
+ default branch, in any form git's --since accepts
461
+ ("6 months ago", "2025-01-01"). Default: 24 months ago
462
+ --fixes corpus only: mine fix-shaped merged PRs (anchored
463
+ conventional fix/bugfix subject) and blame-resolve each
464
+ to the PR that last touched the fixed lines
465
+ --incidents corpus only: mine merged PRs whose title or body carry
466
+ incident keywords (incident, outage, sentry,
467
+ crashlytics)
468
+ --issues corpus only: upgrade classified PRs that reference a
469
+ GitHub issue labelled as a bug. Requires --fixes
470
+ and/or --incidents — issue refs do not enter alone
471
+ --proximity corpus only: for fix PRs whose introducer did not
472
+ resolve, list prior PRs on the same files within
473
+ --proximity-days. Implies --fixes — proximity is
474
+ computed over the fix set
475
+ --threads corpus only: mine resolved review threads a later push
476
+ plausibly addressed — the defects review DID catch
477
+ --proximity-days <n>
478
+ corpus only: the proximity window in days, an integer
479
+ between 1 and 90. Default: 7
480
+ --bug-labels <csv> corpus only: with --issues, issue labels that mark a
481
+ referenced issue as a bug (comma-separated,
482
+ case-sensitive). Default: bug
483
+ --json status only: print the status as one JSON object on
484
+ stdout (schema pr-hero.status/v1)
485
+ --from <dir> post/triage only: the run dir to read findings.json and
486
+ anchor.patch or diff.patch from (required). triage reply maps
487
+ --finding F00N onto the posted marker via the same
488
+ post-line remapping post uses
489
+ --finding <id> triage reply only: the finding id in that run's
490
+ findings.json (F001, …). The driver maps it to the
491
+ posted comment; do not pass a GitHub comment id
492
+ --tag <tag> triage reply only: applied, dismissed, deferred, or
493
+ misclassified
494
+ --body-file <path> triage reply only: reasoning prose. The driver prepends
495
+ the triage marker and the visible badge
496
+ --verdict <word> triage reply only: upheld, rejected, or inconclusive.
497
+ Required for dismissed/deferred/misclassified;
498
+ forbidden for applied
499
+ --issue <n> triage reply only: optional GitHub issue number on
500
+ deferred. Not required — deferred is a tag plus
501
+ reasoning; the coding agent decides whether an issue
502
+ exists
503
+ --gotchas <file> Repo gotchas file (default: <repo>/.crysk/gotchas.md);
504
+ supply it from outside to review a tree you cannot dirty
505
+ --config <file> Local config (default: <repo>/.crysk/config.json) with
506
+ agents_dir, default_base, parity_trigger_paths and
507
+ suspicion_priors, optional summary settings, and
508
+ optional max_verification_steps (re-review verify cap;
509
+ default 8; 0 pauses verification), and optional
510
+ max_concurrent_steps (cap on steps in flight at once;
511
+ a positive integer; unset = unlimited)
512
+ --model <model> Override every agent's model
513
+ --summary Enable the engine-owned PR summary (default)
514
+ --no-summary Disable the engine-owned PR summary
515
+ --scout review only: run the diff-only scout stage before the
516
+ hunters, biasing their scan with unverified leads.
517
+ EXPERIMENTAL and off by default — the A/B that decides
518
+ whether it earns its cost has not run yet
519
+ --scout-model <m> Model for the scout stage (default: the run's model).
520
+ Requires --scout
521
+ --no-shared-prefix review only: turn off the shared hunter prefix. By
522
+ default the patch and output contract sit in each
523
+ hunter's system prompt, identical across hunters, and the
524
+ prompt cache is warmed once per group before the fan-out.
525
+ Anthropic routes only; others keep per-hunter prompts
526
+ (--shared-prefix forces it on)
527
+ --full review only: on a re-review, widen discovery to the
528
+ full PR range (B..H). Verification and triage still
529
+ run; the recorded case does not change. On GitHub,
530
+ comment /crysk review --full on the PR
531
+ --adjudicate with --pr --ci: also have the CI adjudicator rule on
532
+ each pending dismissal of a blocking finding (at most
533
+ 5 per run) and post its verdict on the finding's
534
+ thread. Set by a /crysk recheck comment.
535
+ --hop-budget <n> Hops per hunter (default: ${DEFAULT_HOP_BUDGET}); the biggest
536
+ per-hunter cost lever there is
537
+ --two-dot Diff the literal <base>..<head> two-point range instead
538
+ of from the merge base. Rarely what you want: when base
539
+ has moved on, its newer commits show up REVERSED in the
540
+ review
541
+ --once watch only: run one tick and exit (launchd's unit of
542
+ work). Required — watch has no daemon mode
543
+ --on-push watch add only: re-review the repo's PRs on every new
544
+ push. Default: each PR is reviewed ONCE — a push does
545
+ not re-bill; re-review manually with review --pr <n>
546
+ --interval <min> watch install and gc install: minutes between launchd
547
+ ticks (watch default: ${DEFAULT_WATCH_INTERVAL_MIN};
548
+ gc default: ${DEFAULT_GC_INTERVAL_MIN})
549
+ --dry-run Resolve, preflight, print the plan and the cost band,
550
+ then exit without spawning anything. For watch --once:
551
+ print what would be skipped/launched and why, touching
552
+ nothing
553
+ --max-changed-lines <n>
554
+ Size gate: skip the review when the diff has more than
555
+ n effective changed lines (insertions + deletions,
556
+ generated files like lockfiles and minified bundles
557
+ excluded, plus anything a repo's own .cryskignore
558
+ names). Default ${DEFAULT_SIZE_GATE.maxChangedLines}; 0 disables the limit.
559
+ With watch add: record the threshold for the repo
560
+ --max-changed-files <n>
561
+ Size gate: same, on the effective changed-FILE count.
562
+ Default ${DEFAULT_SIZE_GATE.maxChangedFiles}; 0 disables the limit
563
+ --ci-mode <gate|advisory>
564
+ With review --ci only. gate (the default): the
565
+ crysk commit status is failure on blocking findings
566
+ and on a size or budget skip, and error on a crash.
567
+ advisory: the status stays success whatever the
568
+ findings, as before
569
+ --force Review even when CI would skip: the size gate, the
570
+ review-policy admission rules, and the budget ceiling.
571
+ On GitHub, comment /crysk review on the PR to pass
572
+ this flag from Actions. An interactive TTY already
573
+ offers the size-gate choice as a menu; this flag is
574
+ the unattended hatch. Does NOT imply --yes — the
575
+ cost-band prompt still asks. With setup --ci /
576
+ ci init: overwrite the existing review workflow
577
+ (.github/workflows/crysk.yml or pr-hero.yml) instead
578
+ of refusing
579
+ --all usage only: show every origin's rows instead of just
580
+ the current checkout's
581
+ --yes Skip the confirmation prompt
582
+ --help Show this text
583
+
584
+ By default the diff runs from the MERGE BASE of base and head (the three-dot
585
+ range), so only what this branch adds is reviewed. The plan prints both the
586
+ base ref you asked for and the merge-base sha it actually used.
587
+
588
+ Every run costs real money. --dry-run costs nothing and answers most
589
+ questions; use it first.
590
+
591
+ The size gate is a COST gate, not a quality gate: past its limits a diff bills
592
+ several times more with a much wider spread, so Crysk skips it unattended
593
+ rather than guess at the bill. An interactive run asks first. It says nothing
594
+ about how well a large diff reviews.`;
595
+
596
+ const VALUE_FLAGS = new Set([
597
+ "--repo",
598
+ "--base",
599
+ "--head",
600
+ "--agents",
601
+ "--out",
602
+ "--from",
603
+ "--gotchas",
604
+ "--config",
605
+ "--model",
606
+ "--scout-model",
607
+ "--hop-budget",
608
+ "--interval",
609
+ "--max-changed-lines",
610
+ "--max-changed-files",
611
+ "--budget-usd",
612
+ "--ci-mode",
613
+ "--level",
614
+ "--billing",
615
+ "--finding",
616
+ "--tag",
617
+ "--body-file",
618
+ "--verdict",
619
+ "--issue",
620
+ "--since",
621
+ "--proximity-days",
622
+ "--bug-labels",
623
+ "--socket",
624
+ "--db",
625
+ "--kill",
626
+ ]);
627
+
628
+ export function parseArgs(argv: string[]): ParsedCli {
629
+ const options: CliOptions = {
630
+ repo: ".",
631
+ head: DEFAULT_HEAD_REF,
632
+ hopBudget: DEFAULT_HOP_BUDGET,
633
+ full: false,
634
+ dryRun: false,
635
+ yes: false,
636
+ twoDot: false,
637
+ onPush: false,
638
+ force: false,
639
+ all: false,
640
+ fixes: false,
641
+ incidents: false,
642
+ issues: false,
643
+ proximity: false,
644
+ threads: false,
645
+ };
646
+ let command:
647
+ | "review"
648
+ | "init"
649
+ | "setup"
650
+ | "doctor"
651
+ | "menu"
652
+ | "activity"
653
+ | "watch"
654
+ | "post"
655
+ | "triage"
656
+ | "status"
657
+ | "gc"
658
+ | "usage"
659
+ | "reverts"
660
+ | "corpus"
661
+ | "config"
662
+ | "mcp"
663
+ | "upgrade"
664
+ | "uninstall"
665
+ | "ci"
666
+ | "skills"
667
+ | "help"
668
+ | undefined;
669
+ // --head carries a baked-in default, so "was it explicitly given" cannot
670
+ // be read off options afterwards — and the --pr exclusion below must fire
671
+ // on an explicit --head even when its value equals that default.
672
+ let headExplicit = false;
673
+ // --once is watch's tick switch; folded into options.watch after the loop
674
+ // so flag order (watch --once vs --once watch) cannot matter.
675
+ let once = false;
676
+ for (let i = 0; i < argv.length; i++) {
677
+ const arg = argv[i];
678
+ if (arg === undefined) continue;
679
+ if (arg === "--help" || arg === "-h") return { command: "help", options };
680
+ // --pr takes an OPTIONAL value. A digit-LEADING next token is consumed
681
+ // and validated — digit-leading on purpose, not full-match: garbage like
682
+ // "12abc" must still reach the validator and fail loudly, never silently
683
+ // become branch-mode. Anything else (nothing, a flag, a word — including
684
+ // the command token, which the non-digit rule protects) is left alone
685
+ // and the sentinel says "resolve the PR from the current branch".
686
+ if (arg === "--pr") {
687
+ const value = argv[i + 1];
688
+ if (value !== undefined && /^\d/.test(value)) {
689
+ i++;
690
+ const parsed = Number(value);
691
+ if (!Number.isInteger(parsed) || parsed < 1) {
692
+ throw new CliUsageError(
693
+ `--pr must be a positive integer, got: ${value}`,
694
+ );
695
+ }
696
+ options.pr = parsed;
697
+ } else {
698
+ options.pr = "current";
699
+ }
700
+ continue;
701
+ }
702
+ if (VALUE_FLAGS.has(arg)) {
703
+ const value = argv[i + 1];
704
+ // A flag swallowing the NEXT flag as its value is the classic way to
705
+ // end up reviewing the wrong tree: `--base --head foo` would otherwise
706
+ // resolve base to "--head".
707
+ if (value === undefined || value.startsWith("--")) {
708
+ throw new CliUsageError(`${arg} needs a value`);
709
+ }
710
+ i++;
711
+ if (arg === "--head") headExplicit = true;
712
+ if (arg === "--repo") options.repoExplicit = true;
713
+ applyValueFlag(options, arg, value);
714
+ continue;
715
+ }
716
+ if (arg === "--json") {
717
+ options.json = true;
718
+ continue;
719
+ }
720
+ if (arg === "--wait") {
721
+ options.wait = true;
722
+ continue;
723
+ }
724
+ if (arg === "--dry-run") {
725
+ options.dryRun = true;
726
+ continue;
727
+ }
728
+ if (arg === "--summary") {
729
+ options.summary = true;
730
+ continue;
731
+ }
732
+ if (arg === "--no-summary") {
733
+ options.summary = false;
734
+ continue;
735
+ }
736
+ if (arg === "--scout") {
737
+ options.scout = true;
738
+ continue;
739
+ }
740
+ if (arg === "--no-scout") {
741
+ options.scout = false;
742
+ continue;
743
+ }
744
+ if (arg === "--no-shared-prefix") {
745
+ options.sharedPrefix = false;
746
+ continue;
747
+ }
748
+ if (arg === "--shared-prefix") {
749
+ options.sharedPrefix = true;
750
+ continue;
751
+ }
752
+ if (arg === "--ci") {
753
+ options.ci = true;
754
+ continue;
755
+ }
756
+ if (arg === "--step-summary") {
757
+ options.stepSummary = true;
758
+ continue;
759
+ }
760
+ if (arg === "--no-step-summary") {
761
+ options.stepSummary = false;
762
+ continue;
763
+ }
764
+ if (arg === "--full") {
765
+ options.full = true;
766
+ continue;
767
+ }
768
+ if (arg === "--adjudicate") {
769
+ options.adjudicate = true;
770
+ continue;
771
+ }
772
+ if (arg === "--yes" || arg === "-y") {
773
+ options.yes = true;
774
+ continue;
775
+ }
776
+ if (arg === "--post") {
777
+ options.post = true;
778
+ continue;
779
+ }
780
+ if (arg === "--no-post") {
781
+ options.post = false;
782
+ continue;
783
+ }
784
+ if (arg === "--two-dot") {
785
+ options.twoDot = true;
786
+ continue;
787
+ }
788
+ if (arg === "--once") {
789
+ once = true;
790
+ continue;
791
+ }
792
+ if (arg === "--on-push") {
793
+ options.onPush = true;
794
+ continue;
795
+ }
796
+ // NOT folded into --yes: --force overrides the size gate only. See the
797
+ // WHY on CliOptions.force.
798
+ if (arg === "--force") {
799
+ options.force = true;
800
+ continue;
801
+ }
802
+ if (arg === "--all") {
803
+ options.all = true;
804
+ continue;
805
+ }
806
+ if (arg === "--purge") {
807
+ options.purge = true;
808
+ continue;
809
+ }
810
+ if (arg === "--check") {
811
+ options.check = true;
812
+ continue;
813
+ }
814
+ if (arg === "--reconcile") {
815
+ options.reconcile = true;
816
+ continue;
817
+ }
818
+ // The five corpus sources, size-gate-style booleans — no values, and the
819
+ // post-loop corpus block owns their cross-command rules (required-set,
820
+ // --proximity implies --fixes, --issues needs a classified-set source).
821
+ if (arg === "--fixes") {
822
+ options.fixes = true;
823
+ continue;
824
+ }
825
+ if (arg === "--incidents") {
826
+ options.incidents = true;
827
+ continue;
828
+ }
829
+ if (arg === "--issues") {
830
+ options.issues = true;
831
+ continue;
832
+ }
833
+ if (arg === "--proximity") {
834
+ options.proximity = true;
835
+ continue;
836
+ }
837
+ if (arg === "--threads") {
838
+ options.threads = true;
839
+ continue;
840
+ }
841
+ if (arg === "--person") {
842
+ options.configLayer = "person";
843
+ continue;
844
+ }
845
+ if (arg === "--team") {
846
+ options.configLayer = "team";
847
+ continue;
848
+ }
849
+ if (arg === "--watch") {
850
+ options.configLayer = "watch";
851
+ continue;
852
+ }
853
+ if (arg === "--edit") {
854
+ options.edit = true;
855
+ options.configSubcommand = "edit";
856
+ continue;
857
+ }
858
+ if (arg.startsWith("-")) {
859
+ throw new CliUsageError(`unknown option: ${arg}`);
860
+ }
861
+ // install/uninstall/add/remove/status are watch's sub-words, not
862
+ // commands of their own: they only parse AFTER `watch`, so `pr-hero
863
+ // install` still fails with the unknown-command list instead of
864
+ // silently touching launchd.
865
+ if (
866
+ command === "watch" &&
867
+ options.watch === undefined &&
868
+ (arg === "install" ||
869
+ arg === "uninstall" ||
870
+ arg === "add" ||
871
+ arg === "remove" ||
872
+ arg === "status")
873
+ ) {
874
+ options.watch = arg;
875
+ continue;
876
+ }
877
+ if (command === "config" && options.configSubcommand === undefined) {
878
+ if (arg === "set") {
879
+ options.configSubcommand = "set";
880
+ const key = argv[++i];
881
+ if (!key || key.startsWith("-")) {
882
+ throw new CliUsageError("config set requires <key> and <value>");
883
+ }
884
+ const val = argv[++i];
885
+ if (!val || val.startsWith("--")) {
886
+ throw new CliUsageError("config set requires <key> and <value>");
887
+ }
888
+ options.configKey = key;
889
+ options.configValue = val;
890
+ continue;
891
+ }
892
+ if (arg === "unset") {
893
+ options.configSubcommand = "unset";
894
+ const key = argv[++i];
895
+ if (!key || key.startsWith("-")) {
896
+ throw new CliUsageError("config unset requires <key>");
897
+ }
898
+ options.configKey = key;
899
+ continue;
900
+ }
901
+ if (arg === "edit") {
902
+ options.configSubcommand = "edit";
903
+ continue;
904
+ }
905
+ }
906
+ if (
907
+ command === "gc" &&
908
+ options.gc === undefined &&
909
+ (arg === "install" || arg === "uninstall" || arg === "status")
910
+ ) {
911
+ options.gc = arg;
912
+ continue;
913
+ }
914
+ if (
915
+ command === "skills" &&
916
+ options.skills === undefined &&
917
+ arg === "install"
918
+ ) {
919
+ options.skills = "install";
920
+ continue;
921
+ }
922
+ // `skills` has exactly one subcommand, `install`; any other word in that
923
+ // slot is a usage error, not a generic unexpected argument.
924
+ if (command === "skills" && options.skills === undefined) {
925
+ throw new CliUsageError("crysk skills needs a subcommand: install");
926
+ }
927
+ if (
928
+ command === "triage" &&
929
+ options.triage === undefined &&
930
+ arg === "reply"
931
+ ) {
932
+ options.triage = "reply";
933
+ continue;
934
+ }
935
+ // `ci init` — see the CliOptions.ciSubcommand comment. "init" is the
936
+ // only sub-word today; anything else falls through to the
937
+ // `command !== undefined` unexpected-argument guard right below, same
938
+ // as an unrecognized `watch`/`gc` sub-word would.
939
+ if (
940
+ command === "ci" &&
941
+ options.ciSubcommand === undefined &&
942
+ arg === "init"
943
+ ) {
944
+ options.ciSubcommand = "init";
945
+ continue;
946
+ }
947
+ if (command !== undefined) {
948
+ throw new CliUsageError(`unexpected argument: ${arg}`);
949
+ }
950
+ if (
951
+ arg !== "review" &&
952
+ arg !== "init" &&
953
+ arg !== "setup" &&
954
+ arg !== "doctor" &&
955
+ arg !== "menu" &&
956
+ arg !== "activity" &&
957
+ arg !== "watch" &&
958
+ arg !== "post" &&
959
+ arg !== "triage" &&
960
+ arg !== "status" &&
961
+ arg !== "gc" &&
962
+ arg !== "usage" &&
963
+ arg !== "reverts" &&
964
+ arg !== "corpus" &&
965
+ arg !== "config" &&
966
+ arg !== "mcp" &&
967
+ arg !== "upgrade" &&
968
+ arg !== "update" &&
969
+ arg !== "uninstall" &&
970
+ arg !== "ci" &&
971
+ arg !== "skills"
972
+ ) {
973
+ throw new CliUsageError(
974
+ `unknown command: ${arg} (the commands are "menu", "review", "init", "setup", "doctor", ` +
975
+ '"activity", "watch", "post", "triage", "status", "gc", "usage", ' +
976
+ '"reverts", "corpus", "config", "mcp", "upgrade", "uninstall", "ci" and "skills")',
977
+ );
978
+ }
979
+ command = arg === "update" ? "upgrade" : arg;
980
+ }
981
+ if (command === undefined) {
982
+ throw new CliUsageError('no command given (did you mean "crysk review"?)');
983
+ }
984
+ if (command === "skills" && options.skills === undefined) {
985
+ throw new CliUsageError("crysk skills needs a subcommand: install");
986
+ }
987
+ // --pr derives the whole range from the PR record — head from GitHub, base
988
+ // from the merge commit's parent or the base branch — so a hand-picked
989
+ // endpoint or range shape beside it would silently contradict what the PR
990
+ // actually contains. Checked after the loop so flag order cannot matter.
991
+ if (options.pr !== undefined) {
992
+ if (options.base !== undefined) {
993
+ throw new CliUsageError(
994
+ "--pr resolves base from the PR itself, so it cannot be combined " +
995
+ "with --base",
996
+ );
997
+ }
998
+ if (headExplicit) {
999
+ throw new CliUsageError(
1000
+ "--pr reviews the PR's own head commit, so it cannot be combined " +
1001
+ "with --head",
1002
+ );
1003
+ }
1004
+ if (options.twoDot) {
1005
+ throw new CliUsageError(
1006
+ "--pr always diffs the PR from its merge base, so it cannot be " +
1007
+ "combined with --two-dot",
1008
+ );
1009
+ }
1010
+ }
1011
+ // Also after the loop, for the same flag-order reason: posting publishes a
1012
+ // PR comment, and only --pr names a PR to publish to. `watch` is excused —
1013
+ // there --post is `watch add`'s flag, validated in the watch block below.
1014
+ // `post` (the command) is ALSO excused: it always targets a PR via its own
1015
+ // required --pr, so it needs no --post flag at all — see the "post" block
1016
+ // below.
1017
+ if (
1018
+ options.post &&
1019
+ options.pr === undefined &&
1020
+ command !== "watch" &&
1021
+ command !== "post"
1022
+ ) {
1023
+ throw new CliUsageError(
1024
+ "--post publishes the review as a PR comment, so it requires --pr",
1025
+ );
1026
+ }
1027
+ // ROADMAP Pillar 3 (GitHub Actions CI). `--ci` runs the CI headless shell
1028
+ // (skip comments, step summary, structured outputs) against a PR — the
1029
+ // official action always passes both together, and nothing else in this
1030
+ // CLI has a CI-mode surface to activate. Phase 4 added a SECOND reading on
1031
+ // `setup`: scaffold the workflow file instead of running the wizard (see
1032
+ // the CliOptions.ci comment) — `setup --ci` never touches --pr.
1033
+ if (options.ci && command !== "review" && command !== "setup") {
1034
+ throw new CliUsageError("--ci only applies to the review or setup command");
1035
+ }
1036
+ if (options.ci && command === "review" && options.pr === undefined) {
1037
+ throw new CliUsageError(
1038
+ "--ci runs the CI headless shell against a PR, so it requires --pr",
1039
+ );
1040
+ }
1041
+ if (options.adjudicate && options.pr === undefined) {
1042
+ throw new CliUsageError(
1043
+ "--adjudicate runs the CI adjudicator against a PR, so it requires --pr",
1044
+ );
1045
+ }
1046
+ // The adjudicator's verdicts are posted only by the CI shell, so the flag is a
1047
+ // no-op anywhere else. Same reasoning as --budget-usd below.
1048
+ if (options.adjudicate && !(options.ci && command === "review")) {
1049
+ throw new CliUsageError("--adjudicate only applies with review --ci");
1050
+ }
1051
+ // Same "silently dropped intention" reasoning as --post/--pr above: a
1052
+ // spend ceiling or a summary toggle for a mode that never turns on would
1053
+ // be a flag the operator believes changed a run it did not. Scoped to
1054
+ // `review`'s reading of --ci specifically now that `setup --ci` exists —
1055
+ // neither flag means anything to scaffolding.
1056
+ // `setup --ci` and `ci init` read both too: they write the gate mode and
1057
+ // the ceiling into the workflow they scaffold.
1058
+ const scaffolding = (options.ci && command === "setup") || command === "ci";
1059
+ if (
1060
+ options.budgetUsd !== undefined &&
1061
+ !(options.ci && command === "review") &&
1062
+ !scaffolding
1063
+ ) {
1064
+ throw new CliUsageError(
1065
+ "--budget-usd only applies with review --ci, setup --ci or ci init",
1066
+ );
1067
+ }
1068
+ // S4: the gate mode is a review reading of --ci, like budgetUsd. Without
1069
+ // it the flag would name a mode that never runs.
1070
+ if (
1071
+ options.ciMode !== undefined &&
1072
+ !(options.ci && command === "review") &&
1073
+ !scaffolding
1074
+ ) {
1075
+ throw new CliUsageError(
1076
+ "--ci-mode only applies with review --ci, setup --ci or ci init",
1077
+ );
1078
+ }
1079
+ if (
1080
+ (options.reviewLevel !== undefined || options.billing !== undefined) &&
1081
+ !scaffolding
1082
+ ) {
1083
+ throw new CliUsageError(
1084
+ "--level and --billing only apply with setup --ci or ci init",
1085
+ );
1086
+ }
1087
+ if (options.billing === "subscription" && options.budgetUsd !== undefined) {
1088
+ throw new CliUsageError(
1089
+ "--budget-usd does not apply with --billing subscription: a subscription review spends quota, not dollars",
1090
+ );
1091
+ }
1092
+ if (
1093
+ options.stepSummary !== undefined &&
1094
+ !(options.ci && command === "review")
1095
+ ) {
1096
+ throw new CliUsageError(
1097
+ "--step-summary and --no-step-summary only apply with review --ci",
1098
+ );
1099
+ }
1100
+ // `ci` (the command) has exactly one sub-word today: `init`. A bare
1101
+ // `pr-hero ci` has no scaffolding action to fall into — same reasoning as
1102
+ // watch's `options.watch === undefined` guard below.
1103
+ if (command === "ci" && options.ciSubcommand === undefined) {
1104
+ throw new CliUsageError(
1105
+ 'the "ci" command requires a subcommand: "ci init"',
1106
+ );
1107
+ }
1108
+ // The scout is a `review` stage and nothing else reads either flag.
1109
+ // Rejected elsewhere rather than ignored, the --from guard's reasoning: a
1110
+ // flag that parses and then does nothing is an operator believing they
1111
+ // changed a run they did not.
1112
+ if (
1113
+ command !== "review" &&
1114
+ (options.scout !== undefined || options.scoutModel)
1115
+ ) {
1116
+ throw new CliUsageError(
1117
+ "--scout and --scout-model only apply to the review command",
1118
+ );
1119
+ }
1120
+ if (command !== "review" && options.full) {
1121
+ throw new CliUsageError("--full only applies to the review command");
1122
+ }
1123
+ // A model for a stage that will not run is the same silent no-op, one level
1124
+ // down — and the likeliest way to produce it is believing the model flag
1125
+ // turns the stage on.
1126
+ if (options.scoutModel !== undefined && !options.scout) {
1127
+ throw new CliUsageError(
1128
+ "--scout-model sets the model for the scout stage, so it requires --scout",
1129
+ );
1130
+ }
1131
+ // `status` (ROADMAP S9) reads one PR and writes nothing, so its whole surface is --pr <n>
1132
+ // and --json. Every other flag is refused here, not ignored: a flag that parses and then
1133
+ // does nothing is an operator believing they changed a read they did not (the --from
1134
+ // guard's reasoning below). --json belongs to status alone.
1135
+ if (command === "status") {
1136
+ if (options.pr === undefined || options.pr === "current") {
1137
+ throw new CliUsageError("status requires --pr <n> (a PR number)");
1138
+ }
1139
+ for (const arg of argv) {
1140
+ if (
1141
+ arg.startsWith("-") &&
1142
+ arg !== "--pr" &&
1143
+ arg !== "--json" &&
1144
+ arg !== "--wait"
1145
+ ) {
1146
+ throw new CliUsageError(
1147
+ `status takes only --pr <n>, --json, and --wait, not ${arg}`,
1148
+ );
1149
+ }
1150
+ }
1151
+ } else {
1152
+ if (options.json) {
1153
+ throw new CliUsageError("--json only applies to the status command");
1154
+ }
1155
+ if (options.wait) {
1156
+ throw new CliUsageError("--wait only applies to the status command");
1157
+ }
1158
+ }
1159
+ // `post` (ROADMAP B6) and `triage` (ROADMAP B6c) share the same shape:
1160
+ // both read a PRIOR run's artifacts, named by --from, and act on the PR
1161
+ // named by --pr. Both flags required for either — a command with neither
1162
+ // has nothing to read and nowhere to bind it, and guessing either would
1163
+ // silently act on the wrong run or the wrong PR.
1164
+ if (command === "triage" && options.triage !== "reply") {
1165
+ throw new CliUsageError(
1166
+ "triage needs a subcommand: use `crysk triage reply` (the bare " +
1167
+ "`triage --pr --from` verb was removed with comparison.json)",
1168
+ );
1169
+ }
1170
+ if (command === "post" || command === "triage") {
1171
+ if (options.pr === undefined) {
1172
+ throw new CliUsageError(`${command} requires --pr <n>`);
1173
+ }
1174
+ if (options.from === undefined) {
1175
+ throw new CliUsageError(`${command} requires --from <run-dir>`);
1176
+ }
1177
+ } else if (options.from !== undefined) {
1178
+ throw new CliUsageError(
1179
+ "--from only applies to the post and triage commands",
1180
+ );
1181
+ }
1182
+ // --since names the `git log` window `reverts` and `corpus` mine, and
1183
+ // nothing else reads it. Rejected elsewhere rather than ignored: a flag
1184
+ // that parses and then does nothing is an operator believing they scoped a
1185
+ // command they did not — the same reasoning as the --from guard above.
1186
+ if (
1187
+ options.since !== undefined &&
1188
+ command !== "reverts" &&
1189
+ command !== "corpus"
1190
+ ) {
1191
+ throw new CliUsageError(
1192
+ "--since only applies to the reverts and corpus commands",
1193
+ );
1194
+ }
1195
+ // The corpus source flags and their two value flags are corpus-only, same
1196
+ // reasoning as the --since guard: each names the source it enables, and on
1197
+ // any other command it would be a silently dropped intention.
1198
+ if (command !== "corpus") {
1199
+ if (options.fixes) {
1200
+ throw new CliUsageError("--fixes only applies to the corpus command");
1201
+ }
1202
+ if (options.incidents) {
1203
+ throw new CliUsageError("--incidents only applies to the corpus command");
1204
+ }
1205
+ if (options.issues) {
1206
+ throw new CliUsageError("--issues only applies to the corpus command");
1207
+ }
1208
+ if (options.proximity) {
1209
+ throw new CliUsageError("--proximity only applies to the corpus command");
1210
+ }
1211
+ if (options.threads) {
1212
+ throw new CliUsageError("--threads only applies to the corpus command");
1213
+ }
1214
+ if (options.proximityDays !== undefined) {
1215
+ throw new CliUsageError(
1216
+ "--proximity-days only applies to the corpus command",
1217
+ );
1218
+ }
1219
+ if (options.bugLabels !== undefined) {
1220
+ throw new CliUsageError(
1221
+ "--bug-labels only applies to the corpus command",
1222
+ );
1223
+ }
1224
+ } else {
1225
+ // Checked after the loop, where the whole flag set is visible at once:
1226
+ // corpus with NO source would be a $0 no-op that looks like a scan, and
1227
+ // the error names all five so the fix is one copy-paste away.
1228
+ if (
1229
+ !options.fixes &&
1230
+ !options.incidents &&
1231
+ !options.issues &&
1232
+ !options.proximity &&
1233
+ !options.threads
1234
+ ) {
1235
+ throw new CliUsageError(
1236
+ "corpus needs at least one source: --fixes, --incidents, " +
1237
+ "--issues, --proximity or --threads",
1238
+ );
1239
+ }
1240
+ // Proximity suspects are computed over the fix set, so a --proximity run
1241
+ // IS a --fixes run. Applied here rather than in the shell so the
1242
+ // implication is one pure, tested rule instead of an I/O re-derivation.
1243
+ if (options.proximity) options.fixes = true;
1244
+ // --bug-labels is the value flag of --issues. Passing it without the
1245
+ // source would silently configure a walk that never consults the labels.
1246
+ if (options.bugLabels !== undefined && !options.issues) {
1247
+ throw new CliUsageError("--bug-labels requires --issues");
1248
+ }
1249
+ // Issue refs upgrade a classified set; they do not enter on their own.
1250
+ // --proximity has already implied --fixes, so --issues --proximity is
1251
+ // valid. --issues --threads is not: threads do not populate `working`.
1252
+ if (options.issues && !options.fixes && !options.incidents) {
1253
+ throw new CliUsageError(
1254
+ "--issues upgrades classified PRs; pass --fixes and/or --incidents",
1255
+ );
1256
+ }
1257
+ }
1258
+ // spec "--all misused on another command": --all is usage's own
1259
+ // operator-wide escape hatch, and valid on nothing else.
1260
+ if (options.all && command !== "usage") {
1261
+ throw new CliUsageError("--all only applies to usage");
1262
+ }
1263
+ if (options.kill !== undefined && command !== "activity") {
1264
+ throw new CliUsageError("--kill only applies to the activity command");
1265
+ }
1266
+ // The watch surface, validated after the loop for the same order-blindness.
1267
+ if (command === "watch") {
1268
+ if (once && options.watch !== undefined) {
1269
+ throw new CliUsageError(
1270
+ `--once cannot be combined with "${options.watch}"`,
1271
+ );
1272
+ }
1273
+ if (once) options.watch = "once";
1274
+ if (options.watch === undefined) {
1275
+ throw new CliUsageError(
1276
+ 'watch needs an action: --once (one tick), "add", "remove", ' +
1277
+ '"status", "install" or "uninstall"',
1278
+ );
1279
+ }
1280
+ if (options.dryRun && options.watch !== "once") {
1281
+ throw new CliUsageError(
1282
+ `--dry-run only applies to watch --once, not "${options.watch}"`,
1283
+ );
1284
+ }
1285
+ // On watch, --post configures the repo being added — anywhere else in
1286
+ // the watch surface it would be a silently dropped intention.
1287
+ if (options.post && options.watch !== "add") {
1288
+ throw new CliUsageError(
1289
+ `--post with watch only applies to "watch add", not "${options.watch}"`,
1290
+ );
1291
+ }
1292
+ // Same rule for --on-push, for the same silently-dropped reason.
1293
+ if (options.onPush && options.watch !== "add") {
1294
+ throw new CliUsageError(
1295
+ `--on-push only applies to "watch add", not "${options.watch}"`,
1296
+ );
1297
+ }
1298
+ } else {
1299
+ if (once) {
1300
+ throw new CliUsageError("--once only applies to the watch command");
1301
+ }
1302
+ if (options.onPush) {
1303
+ throw new CliUsageError('--on-push only applies to "watch add"');
1304
+ }
1305
+ }
1306
+ if (options.interval !== undefined) {
1307
+ const allowed =
1308
+ (command === "watch" && options.watch === "install") ||
1309
+ (command === "gc" && options.gc === "install");
1310
+ if (!allowed) {
1311
+ throw new CliUsageError(
1312
+ "--interval only applies to watch install and gc install",
1313
+ );
1314
+ }
1315
+ }
1316
+ if (command === "gc" && options.gc !== undefined && options.dryRun) {
1317
+ throw new CliUsageError(
1318
+ `--dry-run only applies to bare gc, not "gc ${options.gc}"`,
1319
+ );
1320
+ }
1321
+ if (options.triage === "reply") {
1322
+ if (options.finding === undefined) {
1323
+ throw new CliUsageError("triage reply requires --finding <id>");
1324
+ }
1325
+ if (options.tag === undefined) {
1326
+ throw new CliUsageError("triage reply requires --tag <tag>");
1327
+ }
1328
+ if (options.bodyFile === undefined) {
1329
+ throw new CliUsageError("triage reply requires --body-file <path>");
1330
+ }
1331
+ if (ADJUDICATED_TAGS.has(options.tag) && options.verdict === undefined) {
1332
+ throw new CliUsageError(
1333
+ `triage reply --tag ${options.tag} requires --verdict ` +
1334
+ "(upheld, rejected, or inconclusive)",
1335
+ );
1336
+ }
1337
+ if (options.tag === "applied" && options.verdict !== undefined) {
1338
+ throw new CliUsageError(
1339
+ "triage reply --tag applied cannot take --verdict " +
1340
+ "(applied pays no adjudicator)",
1341
+ );
1342
+ }
1343
+ if (options.issue !== undefined && options.tag !== "deferred") {
1344
+ throw new CliUsageError(
1345
+ "triage reply --issue only applies to --tag deferred",
1346
+ );
1347
+ }
1348
+ } else {
1349
+ if (options.finding !== undefined) {
1350
+ throw new CliUsageError("--finding only applies to triage reply");
1351
+ }
1352
+ if (options.tag !== undefined) {
1353
+ throw new CliUsageError("--tag only applies to triage reply");
1354
+ }
1355
+ if (options.bodyFile !== undefined) {
1356
+ throw new CliUsageError("--body-file only applies to triage reply");
1357
+ }
1358
+ if (options.verdict !== undefined) {
1359
+ throw new CliUsageError("--verdict only applies to triage reply");
1360
+ }
1361
+ if (options.issue !== undefined) {
1362
+ throw new CliUsageError("--issue only applies to triage reply");
1363
+ }
1364
+ }
1365
+ if (command === "config" && options.configSubcommand !== undefined) {
1366
+ options.configLayer = options.configLayer ?? "person";
1367
+ }
1368
+ return { command, options };
1369
+ }
1370
+
1371
+ function applyValueFlag(
1372
+ options: CliOptions,
1373
+ flag: string,
1374
+ value: string,
1375
+ ): void {
1376
+ switch (flag) {
1377
+ case "--repo":
1378
+ options.repo = value;
1379
+ return;
1380
+ case "--base":
1381
+ options.base = value;
1382
+ return;
1383
+ case "--head":
1384
+ options.head = value;
1385
+ return;
1386
+ case "--agents":
1387
+ options.agents = value;
1388
+ return;
1389
+ case "--out":
1390
+ options.out = value;
1391
+ return;
1392
+ case "--gotchas":
1393
+ options.gotchas = value;
1394
+ return;
1395
+ case "--config":
1396
+ options.config = value;
1397
+ return;
1398
+ case "--model":
1399
+ options.model = value;
1400
+ return;
1401
+ case "--scout-model":
1402
+ options.scoutModel = value;
1403
+ return;
1404
+ case "--from":
1405
+ options.from = value;
1406
+ return;
1407
+ case "--interval": {
1408
+ const parsed = Number(value);
1409
+ if (!Number.isInteger(parsed) || parsed < 1) {
1410
+ throw new CliUsageError(
1411
+ `--interval must be a positive integer (minutes), got: ${value}`,
1412
+ );
1413
+ }
1414
+ options.interval = parsed;
1415
+ return;
1416
+ }
1417
+ // >= 0, unlike every other numeric flag here: 0 is the documented
1418
+ // "disable this limit" value, not a nonsense input.
1419
+ case "--max-changed-lines":
1420
+ options.maxChangedLines = parseLimit(flag, value);
1421
+ return;
1422
+ case "--max-changed-files":
1423
+ options.maxChangedFiles = parseLimit(flag, value);
1424
+ return;
1425
+ // Unlike parseLimit (integer-only, size-gate's line/file counts):
1426
+ // spend is a float ($7.50), and <= 0 is a real, meaningful value (see
1427
+ // ci/gates.ts's evaluateBudgetGate) rather than a rejected input, so this
1428
+ // only refuses non-numbers, never negatives.
1429
+ case "--budget-usd": {
1430
+ const parsed = Number(value);
1431
+ if (!Number.isFinite(parsed)) {
1432
+ throw new CliUsageError(`--budget-usd must be a number, got: ${value}`);
1433
+ }
1434
+ options.budgetUsd = parsed;
1435
+ return;
1436
+ }
1437
+ case "--ci-mode": {
1438
+ if (value !== "gate" && value !== "advisory") {
1439
+ throw new CliUsageError(
1440
+ `--ci-mode must be gate or advisory, got: ${value}`,
1441
+ );
1442
+ }
1443
+ options.ciMode = value;
1444
+ return;
1445
+ }
1446
+ case "--level": {
1447
+ if (
1448
+ value !== "minimal" &&
1449
+ value !== "balanced" &&
1450
+ value !== "thorough" &&
1451
+ value !== "manual"
1452
+ ) {
1453
+ throw new CliUsageError(
1454
+ `--level must be minimal, balanced, thorough or manual, got: ${value}`,
1455
+ );
1456
+ }
1457
+ options.reviewLevel = value;
1458
+ return;
1459
+ }
1460
+ case "--billing": {
1461
+ if (value !== "subscription" && value !== "api") {
1462
+ throw new CliUsageError(
1463
+ `--billing must be subscription or api, got: ${value}`,
1464
+ );
1465
+ }
1466
+ options.billing = value;
1467
+ return;
1468
+ }
1469
+ case "--finding":
1470
+ options.finding = value;
1471
+ return;
1472
+ case "--tag": {
1473
+ if (
1474
+ value !== "applied" &&
1475
+ value !== "dismissed" &&
1476
+ value !== "deferred" &&
1477
+ value !== "misclassified"
1478
+ ) {
1479
+ throw new CliUsageError(
1480
+ `--tag must be applied, dismissed, deferred or misclassified, ` +
1481
+ `got: ${value}`,
1482
+ );
1483
+ }
1484
+ options.tag = value;
1485
+ return;
1486
+ }
1487
+ case "--body-file":
1488
+ options.bodyFile = value;
1489
+ return;
1490
+ case "--verdict": {
1491
+ if (
1492
+ value !== "upheld" &&
1493
+ value !== "rejected" &&
1494
+ value !== "inconclusive"
1495
+ ) {
1496
+ throw new CliUsageError(
1497
+ `--verdict must be upheld, rejected or inconclusive, got: ${value}`,
1498
+ );
1499
+ }
1500
+ options.verdict = value;
1501
+ return;
1502
+ }
1503
+ // Kept as a raw string and handed to `git log --since=` verbatim: git's
1504
+ // date parser is the authority on what "24 months ago" means, and a
1505
+ // validator here could only be a worse second opinion. It MUST have its
1506
+ // own case — the switch's `default:` is --hop-budget's integer parser,
1507
+ // so a missing case would reject a perfectly good date with an error
1508
+ // naming a flag the operator never typed.
1509
+ case "--since":
1510
+ options.since = value;
1511
+ return;
1512
+ // Kept verbatim, exactly like --since: the 1..90 range rule belongs to
1513
+ // validateProximityDays in corpus/preflight.ts, next to the join that
1514
+ // consumes the number — an integer parser HERE would be a second opinion
1515
+ // the shell's validator contradicts. Same own-case reasoning as --since
1516
+ // (the switch's `default:` is --hop-budget's integer parser).
1517
+ case "--proximity-days":
1518
+ options.proximityDays = value;
1519
+ return;
1520
+ // Also verbatim: splitBugLabels owns the trim/dedupe rules, and the csv
1521
+ // must survive byte-for-byte so error messages can quote what was typed.
1522
+ case "--bug-labels":
1523
+ options.bugLabels = value;
1524
+ return;
1525
+ case "--issue": {
1526
+ const parsed = Number(value);
1527
+ if (!Number.isInteger(parsed) || parsed < 1) {
1528
+ throw new CliUsageError(
1529
+ `--issue must be a positive integer, got: ${value}`,
1530
+ );
1531
+ }
1532
+ options.issue = parsed;
1533
+ return;
1534
+ }
1535
+ case "--socket":
1536
+ options.socket = value;
1537
+ return;
1538
+ case "--db":
1539
+ options.db = value;
1540
+ return;
1541
+ case "--kill": {
1542
+ const parsed = Number(value);
1543
+ if (!Number.isInteger(parsed) || parsed < 1) {
1544
+ throw new CliUsageError(
1545
+ `--kill must be a positive integer (PID), got: ${value}`,
1546
+ );
1547
+ }
1548
+ options.kill = parsed;
1549
+ return;
1550
+ }
1551
+ default: {
1552
+ const parsed = Number(value);
1553
+ if (!Number.isInteger(parsed) || parsed < 1) {
1554
+ throw new CliUsageError(
1555
+ `--hop-budget must be a positive integer, got: ${value}`,
1556
+ );
1557
+ }
1558
+ options.hopBudget = parsed;
1559
+ }
1560
+ }
1561
+ }
1562
+
1563
+ function parseLimit(flag: string, value: string): number {
1564
+ const parsed = Number(value);
1565
+ if (!Number.isInteger(parsed) || parsed < 0) {
1566
+ throw new CliUsageError(
1567
+ `${flag} must be a non-negative integer (0 disables the limit), ` +
1568
+ `got: ${value}`,
1569
+ );
1570
+ }
1571
+ return parsed;
1572
+ }
1573
+
1574
+ export type BaseRefSource = "flag" | "config" | "remote" | "fallback";
1575
+
1576
+ export interface BaseRefResolution {
1577
+ ref: string;
1578
+ source: BaseRefSource;
1579
+ }
1580
+
1581
+ // C5 §3.6: `"config"` is RETIRED. Two files can carry `agents_dir` now, and
1582
+ // one label covering both would tell the operator the value came from "the
1583
+ // config" while leaving them to guess which of two files to open — for the
1584
+ // single biggest spend lever in the file, whose prompt-set frontmatter picks
1585
+ // every hunter's model.
1586
+ export type AgentsDirSource = "flag" | "repo" | "global" | "env" | "default";
1587
+
1588
+ // What `dir` MEANS depends on `kind`, and the two cases are not
1589
+ // interchangeable. A Bun-compiled binary embeds every prompt at a hashed,
1590
+ // FLATTENED path (`/$bunfs/root/review-refuter-qkhw7k00.md`), and its
1591
+ // containing "directory" is not one: `existsSync("/$bunfs/root")` is false and
1592
+ // `Bun.Glob().scan({cwd})` on it THROWS ENOENT rather than yielding nothing.
1593
+ // Only `Bun.file(<embedded path>)` reads. So in compiled mode there is no
1594
+ // directory to join a basename onto — there is a MAP, and `dir` degrades to a
1595
+ // display label for the plan card and the config row.
1596
+ export interface AgentsDirResolution {
1597
+ // A real directory when `kind === "dir"`; a DISPLAY LABEL when `"bundled"`.
1598
+ // Never `/$bunfs/root`: that string is actionable to nobody and would name a
1599
+ // path that exists on no machine in every artifact it reached.
1600
+ dir: string;
1601
+ source: AgentsDirSource;
1602
+ kind: "dir" | "bundled";
1603
+ // Logical filename -> readable path. Present iff `kind === "bundled"`.
1604
+ files?: Record<string, string>;
1605
+ }
1606
+
1607
+ // The label the shipped binary shows wherever a prompt-set path would go.
1608
+ // A constant rather than a literal per site because `pr-hero init` already
1609
+ // prints this exact wording for the same concept, and two copies drift the
1610
+ // first time one of them is edited.
1611
+ export const BUNDLED_AGENTS_DIR_LABEL = "bundled default (from engine)";
1612
+
1613
+ // THE read site for every agent file, and the reason it exists is that
1614
+ // `path.join(agentsDir, agent.file)` is unfixable under compiled mode: the
1615
+ // embedded name is hashed, so the logical basename joined onto anything names
1616
+ // a file that does not exist. Callers ask this instead and never see the
1617
+ // difference.
1618
+ export function agentFilePath(
1619
+ resolution: Pick<AgentsDirResolution, "kind" | "dir" | "files">,
1620
+ file: string,
1621
+ ): string {
1622
+ if (resolution.kind === "bundled") {
1623
+ const embedded = resolution.files?.[file];
1624
+ if (embedded === undefined) {
1625
+ // A spec that names a prompt the build never embedded is a BUILD defect,
1626
+ // and it has to say so. Falling back to a join would hand the reader
1627
+ // "/$bunfs/root/<file>" — a path that reads plausibly, exists nowhere,
1628
+ // and sends them hunting a filesystem bug instead of a manifest gap.
1629
+ throw new Error(
1630
+ `the bundled prompt set has no "${file}" — the review spec references ` +
1631
+ "a prompt this build did not embed (asset-manifest.ts and the spec " +
1632
+ "have drifted)",
1633
+ );
1634
+ }
1635
+ return embedded;
1636
+ }
1637
+ return path.join(resolution.dir, file);
1638
+ }
1639
+
1640
+ // The config seat as ONE object rather than three loose optionals. A value,
1641
+ // the layer that spoke it, and the directory that value is relative TO are a
1642
+ // single fact: split apart, a caller can hand over the GLOBAL file's
1643
+ // `agents_dir` with the REPO's `.crysk/` as its base, which resolves a
1644
+ // relative path against a directory the value never lived in and then labels
1645
+ // the result `repo`. Grouped, that mistake does not type-check — which is the
1646
+ // only mitigation available, because the two are both `string` and tsc cannot
1647
+ // otherwise tell them apart (judgment ledger JD-14).
1648
+ export interface AgentsDirConfigSeat {
1649
+ value: string;
1650
+ // Read off mergeConfig's source record by `agentsDirSeat` below: the merge
1651
+ // is the only thing that knows which layer won.
1652
+ layer: Extract<ConfigSource, "repo" | "global">;
1653
+ // The directory the RELATIVE case resolves against — the dirname of the
1654
+ // file `layer` names, never cwd and never the other layer's.
1655
+ dir: string;
1656
+ }
1657
+
1658
+ // WHY `agents_dir` belongs in the config at all: requiring a flag that points
1659
+ // into a SIBLING repository is the single thing that stopped this from being a
1660
+ // one-word command inside the repo being reviewed. Recorded once in
1661
+ // .crysk/config.json, `pr-hero review` needs no arguments.
1662
+ //
1663
+ // The relative case resolves against the CONFIG FILE's directory, not cwd: the
1664
+ // config is the thing that names the path, so the path travels with it. A
1665
+ // cwd-relative reading would make the same config mean different prompt sets
1666
+ // depending on which subdirectory the developer happened to be standing in.
1667
+ // After C5 "the config file" is whichever LAYER won, which is why the seat
1668
+ // carries its own directory instead of taking one from the caller's context.
1669
+ export function resolveAgentsDirSetting(input: {
1670
+ flag?: string | undefined;
1671
+ config?: AgentsDirConfigSeat | undefined;
1672
+ env?: string | undefined;
1673
+ cwd: string;
1674
+ // The runtime's packaged assets, injected. NOT a convenience: the real
1675
+ // `detectAssetMode()` reads `import.meta.dir`, which under `bun test` always
1676
+ // reports "dev", so the compiled branch below is unreachable from a test
1677
+ // without this seam — which is exactly how a shipped binary that could not
1678
+ // load a single prompt kept an entire offline suite green. Resolved lazily
1679
+ // inside the default branch so an explicit flag, config or env never pays
1680
+ // for asset detection.
1681
+ assets?: EngineAssets | undefined;
1682
+ }): AgentsDirResolution {
1683
+ if (input.flag) {
1684
+ return {
1685
+ dir: path.resolve(input.cwd, input.flag),
1686
+ source: "flag",
1687
+ kind: "dir",
1688
+ };
1689
+ }
1690
+ if (input.config) {
1691
+ return {
1692
+ dir: path.resolve(input.config.dir, input.config.value),
1693
+ source: input.config.layer,
1694
+ kind: "dir",
1695
+ };
1696
+ }
1697
+ if (input.env) {
1698
+ return {
1699
+ dir: path.resolve(input.cwd, input.env),
1700
+ source: "env",
1701
+ kind: "dir",
1702
+ };
1703
+ }
1704
+ const assets = input.assets ?? resolveEngineAssets();
1705
+ // The compiled binary's default set is a MAP, never a directory: its
1706
+ // `defaultAgentsDir` is `path.dirname(<embedded path>)`, i.e. "/$bunfs/root",
1707
+ // which no `existsSync` accepts and no `Bun.Glob` can scan. Handing that
1708
+ // string on as a directory is the whole defect — every consumer downstream
1709
+ // would join a logical basename onto it and read a file that is not there.
1710
+ if (assets.mode === "compiled") {
1711
+ return {
1712
+ dir: BUNDLED_AGENTS_DIR_LABEL,
1713
+ source: "default",
1714
+ kind: "bundled",
1715
+ files: assets.bundledAgentFiles,
1716
+ };
1717
+ }
1718
+ return {
1719
+ dir: assets.defaultAgentsDir,
1720
+ source: "default",
1721
+ kind: "dir",
1722
+ };
1723
+ }
1724
+
1725
+ // The seat, assembled from the merge's own source record. THIS is the one
1726
+ // place that record is load-bearing at RUNTIME rather than for display
1727
+ // (judgment ledger JD-14): a relative `"agents_dir": "./prompts"` in the
1728
+ // global file must resolve under `~/.crysk/`, while the same string in the
1729
+ // repo file resolves under `<repo>/.crysk/`. They are two different prompt
1730
+ // sets — one the operator's, one the team's — and resolving the global value
1731
+ // against the repo's directory picks a set nobody configured, or throws
1732
+ // "agents dir does not exist" naming a path that appears in neither file.
1733
+ //
1734
+ // Pure and here rather than in the shell for CLAUDE.md's split: the FILES are
1735
+ // the shell's business, the decision of which of them a value belongs to is
1736
+ // not, and it is the half that has to be provable offline.
1737
+ export function agentsDirSeat(input: {
1738
+ config: Pick<LocalConfig, "agents_dir">;
1739
+ sources: Pick<ConfigSources, "agents_dir">;
1740
+ repoConfigPath: string;
1741
+ globalConfigPath: string;
1742
+ }): AgentsDirConfigSeat | undefined {
1743
+ const value = input.config.agents_dir;
1744
+ if (value === undefined) return undefined;
1745
+ // `agents_dir` is a `person` key, so `capped` cannot occur, and `default`
1746
+ // cannot occur for a value some layer demonstrably spoke. Everything that
1747
+ // is not `global` is therefore the repo file — written as the remainder
1748
+ // rather than as a second equality so a direction change cannot land the
1749
+ // value in a branch that silently drops it.
1750
+ const fromGlobal = input.sources.agents_dir === "global";
1751
+ return {
1752
+ value,
1753
+ layer: fromGlobal ? "global" : "repo",
1754
+ dir: path.dirname(
1755
+ fromGlobal ? input.globalConfigPath : input.repoConfigPath,
1756
+ ),
1757
+ };
1758
+ }
1759
+
1760
+ export function emptyDiffMessage(
1761
+ baseRef: string,
1762
+ headRef: string,
1763
+ twoDot: boolean,
1764
+ ): string {
1765
+ return (
1766
+ `the diff ${baseRef}${twoDot ? ".." : "..."}${headRef} is empty; there ` +
1767
+ "is nothing to review. The usual cause is that head is already contained " +
1768
+ "in base (an already-merged branch), or that the branch's changes were " +
1769
+ "reverted."
1770
+ );
1771
+ }
1772
+
1773
+ // The other empty diff: the range had changes, but every one of them was in a
1774
+ // generated file the size gate excludes, so the EFFECTIVE diff — the one the
1775
+ // hunters would be handed — is empty. Treated exactly like the empty-range
1776
+ // case above rather than spawning hunters on an empty patch: three sessions
1777
+ // reading nothing is a bill for no review at all.
1778
+ export function allExcludedMessage(droppedPaths: string[]): string {
1779
+ return (
1780
+ `every changed file is excluded from review ` +
1781
+ `(${listPaths(droppedPaths)}), so the effective diff is empty and there ` +
1782
+ "is nothing to review. Nothing was spawned and nothing was spent."
1783
+ );
1784
+ }
1785
+
1786
+ export interface NumstatDiffStat {
1787
+ files: number;
1788
+ insertions: number;
1789
+ deletions: number;
1790
+ }
1791
+
1792
+ export interface NumstatFile {
1793
+ // The DESTINATION path — see resolveNumstatPath.
1794
+ path: string;
1795
+ insertions: number;
1796
+ deletions: number;
1797
+ binary: boolean;
1798
+ }
1799
+
1800
+ // `git diff --numstat` emits `<added>\t<deleted>\t<path>` per file, and for a
1801
+ // binary file both counters are a literal `-`. A binary file is still a
1802
+ // changed file (it counts toward `files`) but contributes no lines — reading
1803
+ // `-` as NaN would poison the whole cost estimate.
1804
+ export function parseNumstatFiles(raw: string): NumstatFile[] {
1805
+ const out: NumstatFile[] = [];
1806
+ for (const line of raw.split("\n")) {
1807
+ if (line.trim().length === 0) continue;
1808
+ const fields = line.split("\t");
1809
+ if (fields.length < 3) continue;
1810
+ // The path field may itself contain tabs only in quoted form, which git
1811
+ // escapes; joining the remainder keeps such a path whole instead of
1812
+ // truncating it at the first tab.
1813
+ const rawPath = fields.slice(2).join("\t");
1814
+ out.push({
1815
+ path: resolveNumstatPath(rawPath),
1816
+ insertions: countField(fields[0]),
1817
+ deletions: countField(fields[1]),
1818
+ binary: fields[0] === "-" && fields[1] === "-",
1819
+ });
1820
+ }
1821
+ return out;
1822
+ }
1823
+
1824
+ // A rename does NOT arrive as a plain path. git renders it either whole
1825
+ // (`old/name => new/name`) or with the common prefix/suffix factored out
1826
+ // (`src/{old => new}/file.ts`, and the one-sided `src/{ => sub}/file.ts` /
1827
+ // `src/{old => }/file.ts`). WHY resolving to the DESTINATION matters: every
1828
+ // consumer here matches the path against globs, and `src/{a => b}/x.min.js`
1829
+ // matches no exclusion pattern at all — a renamed lockfile would silently
1830
+ // stop being excluded and push a small PR over the gate.
1831
+ //
1832
+ // The SAME globs also meet git's C-quoting, which `core.quotepath` leaves on by
1833
+ // default for any non-ASCII path (`"canci\303\263n.min.js"`): the leading quote
1834
+ // makes every pattern miss. Found by pr-hero reviewing its own PR #1 — the patch
1835
+ // filter unquoted and this did not, so an excluded file vanished from
1836
+ // diff.patch while its lines stayed in the count. Unquote LAST: git quotes only
1837
+ // the side that needs it (`a.min.js => "canci\303\263n.min.js"`), so unquoting
1838
+ // before resolving is a no-op that leaves the destination still quoted.
1839
+ function resolveNumstatPath(field: string): string {
1840
+ return unquotePath(resolveRenameField(field));
1841
+ }
1842
+
1843
+ function resolveRenameField(field: string): string {
1844
+ const braced = /^(.*)\{(.*) => (.*)\}(.*)$/.exec(field);
1845
+ if (braced !== null) {
1846
+ // The one-sided forms leave an empty segment behind (`src/` + `` +
1847
+ // `/file`), so collapse the doubled separator the substitution creates.
1848
+ return collapseSeparators(`${braced[1]}${braced[3]}${braced[4]}`);
1849
+ }
1850
+ const arrow = field.indexOf(" => ");
1851
+ return arrow === -1 ? field : field.slice(arrow + 4);
1852
+ }
1853
+
1854
+ function collapseSeparators(p: string): string {
1855
+ return p.replace(/\/{2,}/g, "/");
1856
+ }
1857
+
1858
+ // The aggregate view, a pure sum over the per-file one: two parsers of the
1859
+ // same format would drift, and the cost estimate and the size gate must
1860
+ // never disagree about how big a diff is.
1861
+ export function parseNumstat(raw: string): NumstatDiffStat {
1862
+ let files = 0;
1863
+ let insertions = 0;
1864
+ let deletions = 0;
1865
+ for (const file of parseNumstatFiles(raw)) {
1866
+ files++;
1867
+ insertions += file.insertions;
1868
+ deletions += file.deletions;
1869
+ }
1870
+ return { files, insertions, deletions };
1871
+ }
1872
+
1873
+ function countField(field: string | undefined): number {
1874
+ const parsed = Number(field);
1875
+ return Number.isFinite(parsed) ? parsed : 0;
1876
+ }
1877
+
1878
+ export function runDirCandidate(
1879
+ root: string,
1880
+ headSha: string,
1881
+ n: number,
1882
+ ): string {
1883
+ return path.join(root, `${headSha.slice(0, 8)}-${n}`);
1884
+ }
1885
+
1886
+ export function assertOutsideRepo(runDir: string, repoRoot: string): void {
1887
+ const resolvedRun = path.resolve(runDir);
1888
+ const resolvedRepo = path.resolve(repoRoot);
1889
+ if (
1890
+ resolvedRun === resolvedRepo ||
1891
+ resolvedRun.startsWith(`${resolvedRepo}${path.sep}`)
1892
+ ) {
1893
+ throw new CliUsageError(
1894
+ `run dir ${resolvedRun} is inside the reviewed repo ${resolvedRepo}. ` +
1895
+ "Prompts and artifacts written inside the tree show up in the " +
1896
+ "hunters' own Grep results and contaminate the review — pick a " +
1897
+ "--out outside the repo.",
1898
+ );
1899
+ }
1900
+ }
1901
+
1902
+ // repoId rides along with the run dir so the caller's fail-soft metrics
1903
+ // ingest (W4 / #23) can reuse the SAME resolveRepoHome call below instead of
1904
+ // paying for a second gitOriginUrl lookup. --out still skips resolveRepoHome
1905
+ // itself (an explicit dir needs no ~/.crysk/repos/<id> registry, and must
1906
+ // never gain the side effect of creating one just to learn an id — W4 Phase
1907
+ // 6 remediation, GitHub #23 option D) — but it now tries origin via
1908
+ // tryOriginRepoId (persist:false semantics) so a --out run on a checkout
1909
+ // WITH a resolvable origin still ingests. repoId is null only when that
1910
+ // origin lookup itself fails — the same no-origin escape hatch every other
1911
+ // global-state path already has, never a throw.
1912
+ export async function createRunDir(
1913
+ options: CliOptions,
1914
+ repoRoot: string,
1915
+ headSha: string,
1916
+ ): Promise<{ runDir: string; repoId: string | null }> {
1917
+ if (options.out) {
1918
+ const explicit = path.resolve(options.out);
1919
+ assertOutsideRepo(explicit, repoRoot);
1920
+ await mkdir(explicit, { recursive: true });
1921
+ const { tryOriginRepoId } = await import("../home");
1922
+ return { runDir: explicit, repoId: await tryOriginRepoId(repoRoot) };
1923
+ }
1924
+ const { resolveRepoHome } = await import("../home");
1925
+ const repoHome = await resolveRepoHome({
1926
+ home: os.homedir(),
1927
+ operatorRoot: repoRoot,
1928
+ persist: true,
1929
+ });
1930
+ const root = repoHome.paths.runs;
1931
+ // Smallest unused integer, so a second review of the same commit never
1932
+ // overwrites the first one's artifacts — a run that cost money is evidence.
1933
+ for (let n = 1; ; n++) {
1934
+ const candidate = runDirCandidate(root, headSha, n);
1935
+ if (existsSync(candidate)) continue;
1936
+ assertOutsideRepo(candidate, repoRoot);
1937
+ await mkdir(candidate, { recursive: true });
1938
+ return { runDir: candidate, repoId: repoHome.repoId };
1939
+ }
1940
+ }
1941
+
1942
+ // Threat matrix, ported from the lab: a ReviewSpec's `file` values name the
1943
+ // .md files that become the SYSTEM PROMPTS of spawned sessions. A basename
1944
+ // that escapes agentsDir (separator, `..`, or an absolute path) must fail
1945
+ // loud before any spawn, never be silently joined against a location the
1946
+ // caller did not choose.
1947
+ export function assertBasenameOnly(file: string, index: number): void {
1948
+ if (
1949
+ file.includes("/") ||
1950
+ file.includes("\\") ||
1951
+ file.includes("..") ||
1952
+ path.isAbsolute(file)
1953
+ ) {
1954
+ throw new CliUsageError(
1955
+ `spec.agents[${index}].file must be a plain basename (no "/", "\\", ` +
1956
+ `"..", or absolute paths), got: ${JSON.stringify(file)}`,
1957
+ );
1958
+ }
1959
+ }
1960
+
1961
+ export const AGENT_FILE_PATTERNS = ["deep-review-*.md", "review-*.md"];
1962
+
1963
+ // BIDIRECTIONAL on purpose, and this is the check that pays for itself. The
1964
+ // default spec declares four agents and omits the lifecycle hunter, so
1965
+ // running the 5-file clean set with that spec silently drops the one hunter
1966
+ // the whole campaign is about — the run completes, the artifacts validate,
1967
+ // the cost looks normal, and nothing downstream notices. So: every file the
1968
+ // spec names must exist, AND every agent file present must be named.
1969
+ export function agentsDirProblems(
1970
+ specFiles: string[],
1971
+ presentFiles: string[],
1972
+ ): string[] {
1973
+ const problems: string[] = [];
1974
+ const present = new Set(presentFiles);
1975
+ const named = new Set(specFiles);
1976
+ for (const file of named) {
1977
+ if (!present.has(file)) {
1978
+ problems.push(
1979
+ `the spec references "${file}" but the dir does not have it`,
1980
+ );
1981
+ }
1982
+ }
1983
+ for (const file of presentFiles) {
1984
+ if (!named.has(file)) {
1985
+ problems.push(
1986
+ `the dir has "${file}" but no agent in the spec references it ` +
1987
+ "(it would never run)",
1988
+ );
1989
+ }
1990
+ }
1991
+ return problems.sort();
1992
+ }
1993
+
1994
+ // The impure half of the agents-dir chain: the seat's `configDir` is the
1995
+ // dirname of the file the WINNING layer lives in (agentsDirSeat, JD-14), and
1996
+ // only the existence check below touches the disk.
1997
+ export function resolveAgentsDir(
1998
+ // Narrowed to what it actually reads: `--agents` is the only flag in play,
1999
+ // and a wider type would let a caller believe this consults others.
2000
+ options: Pick<CliOptions, "agents">,
2001
+ loaded: EffectiveConfig,
2002
+ // Injected only by tests, which cannot otherwise reach the compiled branch:
2003
+ // detectAssetMode() reads `import.meta.dir` and always reports "dev" under
2004
+ // `bun test`.
2005
+ assets?: EngineAssets,
2006
+ ): AgentsDirResolution {
2007
+ const seat = agentsDirSeat({
2008
+ config: loaded.effective,
2009
+ sources: loaded.sources,
2010
+ repoConfigPath: loaded.repoConfigPath,
2011
+ globalConfigPath: loaded.globalConfigPath,
2012
+ });
2013
+ const resolution = resolveAgentsDirSetting({
2014
+ flag: options.agents,
2015
+ ...(seat === undefined ? {} : { config: seat }),
2016
+ env: readBrandEnv(process.env, "AGENTS_DIR")?.value,
2017
+ cwd: process.cwd(),
2018
+ ...(assets === undefined ? {} : { assets }),
2019
+ });
2020
+ // Only a DIRECTORY can be checked for existence, and this gate running
2021
+ // unconditionally is the whole shipped defect: the compiled binary's bundled
2022
+ // set has no directory, `existsSync` on the embedded root is false, and every
2023
+ // run of the released binary died here with "agents dir does not exist"
2024
+ // before a single step spawned. A bundled set's conformance is checked by
2025
+ // preflightAgentsDir over the manifest's keys instead.
2026
+ if (resolution.kind === "dir" && !existsSync(resolution.dir)) {
2027
+ throw new CliError(`agents dir does not exist: ${resolution.dir}`, {
2028
+ cls: { kind: "prompt-set" },
2029
+ });
2030
+ }
2031
+ return resolution;
2032
+ }
2033
+
2034
+ export async function preflightAgentsDir(
2035
+ agents: Pick<AgentsDirResolution, "kind" | "dir" | "files">,
2036
+ specFiles: string[],
2037
+ ): Promise<void> {
2038
+ const present = new Set<string>();
2039
+ if (agents.kind === "bundled") {
2040
+ // The manifest's keys ARE the present set, and there is nothing to scan:
2041
+ // Bun.Glob().scan() over the embedded root THROWS ENOENT rather than
2042
+ // yielding nothing, so a bundled set reaching the glob below is not a
2043
+ // degraded check but a crash. Key ORDER is irrelevant here — unlike the
2044
+ // fingerprint, agentsDirProblems compares sets bidirectionally.
2045
+ for (const file of Object.keys(agents.files ?? {})) present.add(file);
2046
+ } else {
2047
+ for (const pattern of AGENT_FILE_PATTERNS) {
2048
+ for await (const entry of new Bun.Glob(pattern).scan({
2049
+ cwd: agents.dir,
2050
+ })) {
2051
+ present.add(entry);
2052
+ }
2053
+ }
2054
+ }
2055
+ const problems = agentsDirProblems(specFiles, [...present]);
2056
+ if (problems.length > 0) {
2057
+ throw new CliError(
2058
+ `prompt set ${agents.dir} does not match the review spec:\n` +
2059
+ problems.map((p) => ` - ${p}`).join("\n"),
2060
+ { cls: { kind: "prompt-set" } },
2061
+ );
2062
+ }
2063
+ }
2064
+
2065
+ // EXPERIMENT (odd/tasks/logic-hunter.md T3): benchmark-only hunter fan-out,
2066
+ // parsed once at localReviewSpec()'s call site below and INERT when unset —
2067
+ // no other caller of this env var exists anywhere in production wiring.
2068
+ // Format: "key:file[,key:file...]", e.g.
2069
+ // "logic:deep-review-logic.md,reliability-b:deep-review-reliability.md" (a
2070
+ // second leg on an EXISTING hunter file, distinguished only by key). Strict
2071
+ // on purpose: a malformed value must fail loud rather than silently run
2072
+ // fewer hunters than the operator asked for.
2073
+ function parseExtraHunters(read: BrandEnvValue | undefined): AgentSpec[] {
2074
+ if (read === undefined) return [];
2075
+ const { value: raw, name } = read;
2076
+ const trimmed = raw.trim();
2077
+ if (trimmed === "") return [];
2078
+ return trimmed.split(",").map((rawEntry, i) => {
2079
+ const entry = rawEntry.trim();
2080
+ const sep = entry.indexOf(":");
2081
+ if (sep <= 0 || sep === entry.length - 1) {
2082
+ throw new CliUsageError(
2083
+ `${name}[${i}] must be "key:file.md", got: ${JSON.stringify(rawEntry)}`,
2084
+ );
2085
+ }
2086
+ const key = entry.slice(0, sep).trim();
2087
+ const file = entry.slice(sep + 1).trim();
2088
+ if (!isSafeSlug(key)) {
2089
+ throw new CliUsageError(
2090
+ `${name}[${i}].key "${key}" is not a safe slug ` +
2091
+ "(^[a-z0-9]+(?:-[a-z0-9]+)*$, 1-64 chars)",
2092
+ );
2093
+ }
2094
+ if (!file.endsWith(".md") || file.length <= ".md".length) {
2095
+ throw new CliUsageError(
2096
+ `${name}[${i}].file "${file}" must be a ".md" basename`,
2097
+ );
2098
+ }
2099
+ assertBasenameOnly(file, i);
2100
+ return { key, file, role: "hunter" as const };
2101
+ });
2102
+ }
2103
+
2104
+ // Local mode's wiring: the four unconditional hunters, the conditional
2105
+ // parity hunter, and the refuter. Deliberately NOT defaultReviewSpec() — that
2106
+ // one omits the lifecycle and logic hunters, and local mode targets the 6-file
2107
+ // clean set. Hunter keys stay inside the findings-schema v1.1.0 Hunter/specialty
2108
+ // set, which validateReviewSpec enforces.
2109
+ //
2110
+ // `env` is injectable (defaults to `process.env`) so PRHERO_EXTRA_HUNTERS can
2111
+ // be exercised offline without mutating the real environment — same pattern
2112
+ // as ui/primitives.ts's styleEnabled(). Unset or empty, this function returns
2113
+ // byte-identical output to before T3 (test/review/preflight.test.ts pins it).
2114
+ export function localReviewSpec(
2115
+ env: Record<string, string | undefined> = process.env,
2116
+ ): ReviewSpec {
2117
+ return {
2118
+ agents: [
2119
+ {
2120
+ key: "reliability",
2121
+ file: "deep-review-reliability.md",
2122
+ role: "hunter",
2123
+ },
2124
+ { key: "resilience", file: "deep-review-resilience.md", role: "hunter" },
2125
+ { key: "lifecycle", file: "deep-review-lifecycle.md", role: "hunter" },
2126
+ { key: "logic", file: "deep-review-logic.md", role: "hunter" },
2127
+ {
2128
+ key: "parity",
2129
+ file: "deep-review-parity.md",
2130
+ role: "hunter",
2131
+ trigger: "input",
2132
+ },
2133
+ // The boundary, not the three throws: assertBasenameOnly inside
2134
+ // parseExtraHunters is a fourth usage throw of the same parse (T2d-1).
2135
+ ...withUsageClass({ kind: "config-parse", source: "extra-hunters" }, () =>
2136
+ parseExtraHunters(readBrandEnv(env, "EXTRA_HUNTERS")),
2137
+ ),
2138
+ { key: "refuter", file: "review-refuter.md", role: "refuter" },
2139
+ ],
2140
+ };
2141
+ }
2142
+
2143
+ export type ConfigDirection = "person" | "repo" | "capped";
2144
+
2145
+ // Declared per key, and this table IS the known-key set for both parsers and
2146
+ // the merge — both derive from it below rather than restating it, because a
2147
+ // second hand-written key list is how the table and the parser drift apart
2148
+ // with nothing firing. A key added to LocalConfig without a row here fails
2149
+ // tsc: an undeclared direction is a bug, never a silent default.
2150
+ //
2151
+ // The `capped` rows exist because the spend rule the watcher writes down
2152
+ // (src/watch/preflight.ts:43-47) is DIRECTIONAL: the danger is a committed
2153
+ // repo file enlarging the OPERATOR's bill, never the reverse. Plain
2154
+ // specificity cannot express that asymmetry — "repo wins" lets a team raise
2155
+ // my bill, "person wins" forbids a team from being more frugal.
2156
+ export const CONFIG_DIRECTION: Record<keyof LocalConfig, ConfigDirection> = {
2157
+ agents_dir: "person",
2158
+ // `repo`, and this is the one that costs money if it is wrong:
2159
+ // resolveBaseRef checks the config value BEFORE the remote head, so a
2160
+ // global default_base would sit ahead of an autodetection that already
2161
+ // solves the common case for free. Every quiet repo whose default branch
2162
+ // differs would review the wrong range with a plausible branch name on the
2163
+ // plan card — verbatim the "wrong answer with a plausible face" failure the
2164
+ // comment at the top of this file names.
2165
+ default_base: "repo",
2166
+ // The values are paths INSIDE one repository. A global answer is meaningless
2167
+ // everywhere else and would silently arm or disarm the parity hunter across
2168
+ // every repo on the machine.
2169
+ parity_trigger_paths: "repo",
2170
+ suspicion_priors: "repo",
2171
+ // Per-field below — the two fields disagree, which is why SUMMARY_DIRECTION
2172
+ // exists. This row declares the key for the known-key set; the merge
2173
+ // descends into it rather than folding the object whole.
2174
+ summary: "capped",
2175
+ routing: "person",
2176
+ max_verification_steps: "capped",
2177
+ max_concurrent_steps: "capped",
2178
+ max_changed_lines: "capped",
2179
+ max_changed_files: "capped",
2180
+ scout: "capped",
2181
+ post: "capped",
2182
+ ci_review_policy: "repo",
2183
+ ci_max_attempts: "repo",
2184
+ ci_max_reviews: "repo",
2185
+ ci_rereview_min_score: "repo",
2186
+ ci_blocking_weight: "repo",
2187
+ ci_advisory_weight: "repo",
2188
+ ci_trusted_actors: "repo",
2189
+ ci_admission_observe_only: "repo",
2190
+ };
2191
+
2192
+ // The ONE nested key, so this is a second table and not a pattern. `enabled`
2193
+ // takes the cap because it switches spend on; `model` cannot be capped even
2194
+ // in principle — "narrower" is undefinable for a string, and a direction that
2195
+ // cannot be computed is worse than no direction at all.
2196
+ export const SUMMARY_DIRECTION: Record<keyof SummaryConfig, ConfigDirection> = {
2197
+ enabled: "capped",
2198
+ model: "person",
2199
+ };
2200
+
2201
+ export interface LocalConfig {
2202
+ parity_trigger_paths: string[];
2203
+ suspicion_priors: SuspicionPrior[];
2204
+ // Both optional, and both exist to make `pr-hero review` a zero-flag
2205
+ // command: the prompt set lives in a sibling repo, and the default branch is
2206
+ // a property of THIS repo that no constant can know.
2207
+ agents_dir?: string;
2208
+ default_base?: string;
2209
+ summary?: SummaryConfig;
2210
+ routing?: RoutingConfig;
2211
+ // Item 7: unattended bound on the verify queue. Absent means
2212
+ // DEFAULT_MAX_VERIFICATION_STEPS. 0 is legal — every queued prior lands
2213
+ // `unconfirmed` (the pause switch, same shape as watch daily_cap).
2214
+ max_verification_steps?: number;
2215
+ // Admission cap on in-flight steps (hunter, refuter, verify, adjudicate,
2216
+ // scout, summarizer attempts). Absent means unlimited: no gate is built.
2217
+ // Positive only: 0 would admit nothing and wedge every run.
2218
+ max_concurrent_steps?: number;
2219
+ max_changed_lines?: number;
2220
+ max_changed_files?: number;
2221
+ scout?: boolean;
2222
+ post?: boolean;
2223
+ // CI admission: when to spend on a synchronize push (see ci/review-admission.ts).
2224
+ ci_review_policy?: CiReviewPolicyMode;
2225
+ ci_max_attempts?: number;
2226
+ ci_max_reviews?: number;
2227
+ ci_rereview_min_score?: number;
2228
+ ci_blocking_weight?: number;
2229
+ ci_advisory_weight?: number;
2230
+ ci_trusted_actors?: string[];
2231
+ // When true, admission still evaluates and logs the would-be decision but
2232
+ // never suppresses a review (Phase 1 rollout — observe-only).
2233
+ ci_admission_observe_only?: boolean;
2234
+ }
2235
+
2236
+ export interface SummaryConfig {
2237
+ enabled?: boolean;
2238
+ model?: string;
2239
+ }
2240
+
2241
+ export interface SummarySettings {
2242
+ enabled: boolean;
2243
+ model?: string;
2244
+ }
2245
+
2246
+ export const EMPTY_LOCAL_CONFIG: LocalConfig = {
2247
+ parity_trigger_paths: [],
2248
+ suspicion_priors: [],
2249
+ };
2250
+
2251
+ // What a layer SAID, not what the engine will use — every key optional,
2252
+ // including the two arrays LocalConfig declares required.
2253
+ //
2254
+ // WHY the distinction is load-bearing rather than cosmetic: a merge whose
2255
+ // input cannot represent absence has already destroyed the fact it needs to
2256
+ // fold on. Under LocalConfig a repo file that omits `parity_trigger_paths`
2257
+ // hands the merge a materialised `[]`, the fold sees the repo layer speak,
2258
+ // and provenance reports `repo` for a value that file never named. That is a
2259
+ // lie in pipeline.json and in `pr-hero config`, and no amount of care in the
2260
+ // merge can recover the bit the parser threw away.
2261
+ //
2262
+ // LocalConfig itself is unchanged: it is the EFFECTIVE config, the single
2263
+ // shape the resolvers receive, produced once at the end of mergeConfig.
2264
+ export type ConfigLayer = Partial<LocalConfig>;
2265
+
2266
+ // Derived, never restated: D2's "the table IS the known-key set" is only true
2267
+ // if the parsers actually read the table. `Object.keys` rather than `in`,
2268
+ // because `in` would admit `toString` and every other prototype member as a
2269
+ // known key.
2270
+ const KNOWN_CONFIG_KEYS = new Set<string>(Object.keys(CONFIG_DIRECTION));
2271
+
2272
+ const LOCAL_CONFIG_KEYS = new Set<string>(
2273
+ Object.keys(CONFIG_DIRECTION).filter((key) => key !== "routing"),
2274
+ );
2275
+
2276
+ const GLOBAL_CONFIG_KEYS = new Set<string>(
2277
+ Object.keys(CONFIG_DIRECTION).filter(
2278
+ (key) => CONFIG_DIRECTION[key as keyof LocalConfig] !== "repo",
2279
+ ),
2280
+ );
2281
+
2282
+ // The two file labels every rejection is templated over. A shared validator
2283
+ // that hardcodes one file name sends the operator to edit the wrong file the
2284
+ // moment the other file is the malformed one.
2285
+ const REPO_CONFIG_LABEL = ".crysk/config.json";
2286
+ const GLOBAL_CONFIG_LABEL = "~/.crysk/config.json";
2287
+
2288
+ // `.crysk/config.json` is optional and every setting inside it is optional —
2289
+ // an absent config is a legal, complete configuration (parity simply never
2290
+ // fires, while summary activation is resolved by resolveSummary). What is NOT
2291
+ // tolerated is a malformed one: a typo'd key silently
2292
+ // read as "no triggers" is exactly how the parity hunter stops firing without
2293
+ // anyone noticing, so shape violations throw.
2294
+ // WHY summary defaults on: it is the first defaulted setting that spends
2295
+ // money, and a silent opt-out would make a normal review's bill differ from
2296
+ // the plan. `--no-summary` and `summary.enabled: false` are the explicit exits.
2297
+ //
2298
+ // WHY it returns a ConfigLayer and no longer materialises the two arrays: the
2299
+ // return object used to write `parity_trigger_paths` and `suspicion_priors`
2300
+ // unconditionally, because LocalConfig required them. That destroyed the
2301
+ // difference between "the file said []" and "the file never mentioned it" —
2302
+ // and the merge downstream can only report truthful provenance for a key it
2303
+ // can still see was absent. The `?? []` locals below stay exactly as they
2304
+ // are: they feed the validators, and validating an absent key against the
2305
+ // empty array is what keeps every error string byte-identical.
2306
+ // The repo layer's usage errors carry the repo-config class (T2d-1). It passes the
2307
+ // classed routing parser for symmetry only: `routing` is not a repo key, so the file is
2308
+ // rejected as a per-person key before any routing value is parsed. The person layer's
2309
+ // errors carry no class (see parseGlobalConfig).
2310
+ // `label` is the file name an error should show: a repo still on the legacy
2311
+ // `.prhero/` passes `.prhero/config.json`, so the message names the file that
2312
+ // was actually read.
2313
+ export function parseLocalConfig(
2314
+ raw: string,
2315
+ label: string = REPO_CONFIG_LABEL,
2316
+ ): ConfigLayer {
2317
+ return withUsageClass({ kind: "config-parse", source: "repo-config" }, () =>
2318
+ parseConfigLayer(raw, label, LOCAL_CONFIG_KEYS, parseRoutingConfig, true),
2319
+ );
2320
+ }
2321
+
2322
+ // The global layer's parser: same JSON dialect, same validators, same strict
2323
+ // unknown-key rejection — it differs only in which keys it admits and in the
2324
+ // file it names. It admits every key whose direction is not `repo`, and
2325
+ // rejects the three that are, because no global answer to them could be
2326
+ // right: two are lists of paths inside one repository and the third selects a
2327
+ // commit range ahead of an autodetection that already works.
2328
+ // Its routing object is parsed without the routing class. That class renders
2329
+ // PRH-ROUTING-INVALID, whose text names CRYSK_ROUTING and `gh variable set`: the
2330
+ // fix for the CI routing input, not for this personal file. The message is the same.
2331
+ export function parseGlobalConfig(
2332
+ raw: string,
2333
+ label: string = GLOBAL_CONFIG_LABEL,
2334
+ ): ConfigLayer {
2335
+ return parseConfigLayer(
2336
+ raw,
2337
+ label,
2338
+ GLOBAL_CONFIG_KEYS,
2339
+ parseRoutingValue,
2340
+ false,
2341
+ );
2342
+ }
2343
+
2344
+ // `??` is what makes an explicit `null` mean "absent" for the two arrays, and
2345
+ // the returned layer has to agree with it: `{"suspicion_priors": null}`
2346
+ // validates as the empty array, so it must not claim the layer spoke either.
2347
+ function given(value: unknown): boolean {
2348
+ return value !== undefined && value !== null;
2349
+ }
2350
+
2351
+ function parseOptionalBoolean(
2352
+ value: unknown,
2353
+ key: string,
2354
+ file: string,
2355
+ ): boolean | undefined {
2356
+ if (value === undefined) return undefined;
2357
+ if (typeof value !== "boolean") {
2358
+ throw new CliUsageError(`${file} ${key} must be a boolean`);
2359
+ }
2360
+ return value;
2361
+ }
2362
+
2363
+ // `parseRouting` is the layer's routing parser: the classed one for the repo file, the
2364
+ // unclassed one for the person file (see parseGlobalConfig for why it differs).
2365
+ function parseConfigLayer(
2366
+ raw: string,
2367
+ file: string,
2368
+ admitted: ReadonlySet<string>,
2369
+ parseRouting: typeof parseRoutingConfig,
2370
+ isRepoFile: boolean,
2371
+ ): ConfigLayer {
2372
+ let parsed: unknown;
2373
+ try {
2374
+ parsed = JSON.parse(raw);
2375
+ } catch (error) {
2376
+ throw new CliUsageError(
2377
+ `${file} is not valid JSON: ${(error as Error).message}`,
2378
+ );
2379
+ }
2380
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
2381
+ throw new CliUsageError(`${file} must be a JSON object`);
2382
+ }
2383
+ const config = parsed as Record<string, unknown>;
2384
+ for (const key of Object.keys(config)) {
2385
+ if (!KNOWN_CONFIG_KEYS.has(key)) {
2386
+ throw new CliUsageError(`${file} unknown key: ${redactDiagnostic(key)}`);
2387
+ }
2388
+ // Templated over the OFFENDING key, never a fixed example: one hardcoded
2389
+ // key name across three rejections sends two operators out of three
2390
+ // looking for the wrong line in their config.
2391
+ if (!admitted.has(key)) {
2392
+ if (isRepoFile) {
2393
+ throw new CliUsageError(
2394
+ // Both homes are named: the resolver picks ~/.crysk as soon as it exists, so
2395
+ // telling a pre-rename install to create it would hide its ~/.prhero data.
2396
+ `${file}: ${key} is a per-person key — put it in your person config ` +
2397
+ "(~/.crysk/config.json, or ~/.prhero/config.json on an install set up " +
2398
+ "before the rename; do not create ~/.crysk while ~/.prhero is in use)",
2399
+ );
2400
+ }
2401
+ throw new CliUsageError(
2402
+ `${file}: ${key} is a per-repo key — put it in the repo config ` +
2403
+ "(<repo>/.crysk/config.json, or <repo>/.prhero/config.json in a repo set " +
2404
+ "up before the rename)",
2405
+ );
2406
+ }
2407
+ }
2408
+ const triggers = config.parity_trigger_paths ?? [];
2409
+ if (
2410
+ !Array.isArray(triggers) ||
2411
+ !triggers.every((p) => typeof p === "string" && p.length > 0)
2412
+ ) {
2413
+ throw new CliUsageError(
2414
+ `${file} parity_trigger_paths must be an array of non-empty strings`,
2415
+ );
2416
+ }
2417
+ const priors = config.suspicion_priors ?? [];
2418
+ if (!Array.isArray(priors)) {
2419
+ throw new CliUsageError(`${file} suspicion_priors must be an array`);
2420
+ }
2421
+ for (const [i, entry] of priors.entries()) {
2422
+ if (typeof entry !== "object" || entry === null) {
2423
+ throw new CliUsageError(`suspicion_priors[${i}] must be an object`);
2424
+ }
2425
+ const prior = entry as Record<string, unknown>;
2426
+ if (typeof prior.path !== "string" || prior.path.length === 0) {
2427
+ throw new CliUsageError(`suspicion_priors[${i}].path required`);
2428
+ }
2429
+ if (typeof prior.weight !== "string" && typeof prior.weight !== "number") {
2430
+ throw new CliUsageError(
2431
+ `suspicion_priors[${i}].weight must be a string or a number`,
2432
+ );
2433
+ }
2434
+ if (typeof prior.reason !== "string" || prior.reason.length === 0) {
2435
+ throw new CliUsageError(`suspicion_priors[${i}].reason required`);
2436
+ }
2437
+ }
2438
+ const summary = parseSummaryConfig(config.summary, file);
2439
+ const routing = parseRouting(config.routing, file);
2440
+ const maxVerificationSteps = parseNonNegativeInteger(
2441
+ config.max_verification_steps,
2442
+ "max_verification_steps",
2443
+ file,
2444
+ );
2445
+ const maxConcurrentSteps = parsePositiveInteger(
2446
+ config.max_concurrent_steps,
2447
+ "max_concurrent_steps",
2448
+ file,
2449
+ );
2450
+ const maxChangedLines = parseNonNegativeInteger(
2451
+ config.max_changed_lines,
2452
+ "max_changed_lines",
2453
+ file,
2454
+ );
2455
+ const maxChangedFiles = parseNonNegativeInteger(
2456
+ config.max_changed_files,
2457
+ "max_changed_files",
2458
+ file,
2459
+ );
2460
+ const scout = parseOptionalBoolean(config.scout, "scout", file);
2461
+ const post = parseOptionalBoolean(config.post, "post", file);
2462
+ const ciReviewPolicy = parseCiReviewPolicyMode(config.ci_review_policy, file);
2463
+ const ciMaxAttempts = parseCiAdmissionInteger(
2464
+ config.ci_max_attempts,
2465
+ "ci_max_attempts",
2466
+ file,
2467
+ 1,
2468
+ );
2469
+ const ciMaxReviews = parseCiAdmissionInteger(
2470
+ config.ci_max_reviews,
2471
+ "ci_max_reviews",
2472
+ file,
2473
+ 1,
2474
+ );
2475
+ const ciRereviewMinScore = parseCiAdmissionInteger(
2476
+ config.ci_rereview_min_score,
2477
+ "ci_rereview_min_score",
2478
+ file,
2479
+ 0,
2480
+ );
2481
+ const ciBlockingWeight = parseCiAdmissionInteger(
2482
+ config.ci_blocking_weight,
2483
+ "ci_blocking_weight",
2484
+ file,
2485
+ 1,
2486
+ );
2487
+ const ciAdvisoryWeight = parseCiAdmissionInteger(
2488
+ config.ci_advisory_weight,
2489
+ "ci_advisory_weight",
2490
+ file,
2491
+ 1,
2492
+ );
2493
+ const ciTrustedActors = config.ci_trusted_actors ?? [];
2494
+ if (
2495
+ !Array.isArray(ciTrustedActors) ||
2496
+ !ciTrustedActors.every((a) => typeof a === "string" && a.length > 0)
2497
+ ) {
2498
+ throw new CliUsageError(
2499
+ `${file} ci_trusted_actors must be an array of non-empty strings`,
2500
+ );
2501
+ }
2502
+ const ciAdmissionObserveOnly = parseOptionalBoolean(
2503
+ config.ci_admission_observe_only,
2504
+ "ci_admission_observe_only",
2505
+ file,
2506
+ );
2507
+ return {
2508
+ ...(given(config.parity_trigger_paths)
2509
+ ? { parity_trigger_paths: triggers as string[] }
2510
+ : {}),
2511
+ ...(given(config.suspicion_priors)
2512
+ ? { suspicion_priors: priors as SuspicionPrior[] }
2513
+ : {}),
2514
+ ...optionalString(config, "agents_dir", file),
2515
+ ...optionalString(config, "default_base", file),
2516
+ ...(summary === undefined ? {} : { summary }),
2517
+ ...(routing === undefined ? {} : { routing }),
2518
+ ...(maxVerificationSteps === undefined
2519
+ ? {}
2520
+ : { max_verification_steps: maxVerificationSteps }),
2521
+ ...(maxConcurrentSteps === undefined
2522
+ ? {}
2523
+ : { max_concurrent_steps: maxConcurrentSteps }),
2524
+ ...(maxChangedLines === undefined
2525
+ ? {}
2526
+ : { max_changed_lines: maxChangedLines }),
2527
+ ...(maxChangedFiles === undefined
2528
+ ? {}
2529
+ : { max_changed_files: maxChangedFiles }),
2530
+ ...(scout === undefined ? {} : { scout }),
2531
+ ...(post === undefined ? {} : { post }),
2532
+ ...(ciReviewPolicy === undefined
2533
+ ? {}
2534
+ : { ci_review_policy: ciReviewPolicy }),
2535
+ ...(ciMaxAttempts === undefined ? {} : { ci_max_attempts: ciMaxAttempts }),
2536
+ ...(ciMaxReviews === undefined ? {} : { ci_max_reviews: ciMaxReviews }),
2537
+ ...(ciRereviewMinScore === undefined
2538
+ ? {}
2539
+ : { ci_rereview_min_score: ciRereviewMinScore }),
2540
+ ...(ciBlockingWeight === undefined
2541
+ ? {}
2542
+ : { ci_blocking_weight: ciBlockingWeight }),
2543
+ ...(ciAdvisoryWeight === undefined
2544
+ ? {}
2545
+ : { ci_advisory_weight: ciAdvisoryWeight }),
2546
+ ...(ciTrustedActors.length > 0
2547
+ ? { ci_trusted_actors: ciTrustedActors as string[] }
2548
+ : {}),
2549
+ ...(ciAdmissionObserveOnly === undefined
2550
+ ? {}
2551
+ : { ci_admission_observe_only: ciAdmissionObserveOnly }),
2552
+ };
2553
+ }
2554
+
2555
+ const CREDENTIAL_KEY_NAMES = new Set([
2556
+ "apikey",
2557
+ "api_key",
2558
+ "token",
2559
+ "secret",
2560
+ "password",
2561
+ "bearer",
2562
+ "auth",
2563
+ "credential",
2564
+ "credentials",
2565
+ ]);
2566
+
2567
+ function checkNoCredentials(
2568
+ obj: Record<string, unknown>,
2569
+ path: string,
2570
+ file: string,
2571
+ ): void {
2572
+ for (const key of Object.keys(obj)) {
2573
+ const lower = key.toLowerCase();
2574
+ if (
2575
+ CREDENTIAL_KEY_NAMES.has(lower) ||
2576
+ lower.includes("secret") ||
2577
+ lower.includes("password") ||
2578
+ lower.includes("token") ||
2579
+ lower.includes("apikey") ||
2580
+ lower.includes("api_key")
2581
+ ) {
2582
+ throw new CliUsageError(
2583
+ `${file} ${path}: credentials are not permitted in routing config`,
2584
+ );
2585
+ }
2586
+ const val = obj[key];
2587
+ if (typeof val === "string") {
2588
+ const redacted = redactDiagnostic(val);
2589
+ if (redacted !== val) {
2590
+ throw new CliUsageError(
2591
+ `${file} ${path}: credentials are not permitted in routing config`,
2592
+ );
2593
+ }
2594
+ }
2595
+ }
2596
+ }
2597
+
2598
+ const KNOWN_ROUTE_MAPPING_KEYS = new Set([
2599
+ "logical",
2600
+ "backend",
2601
+ "provider",
2602
+ "gateway",
2603
+ "modelFamily",
2604
+ "modelSnapshot",
2605
+ "modelVariant",
2606
+ "disabled",
2607
+ "allowSpend",
2608
+ ]);
2609
+
2610
+ function parseRouteMapping(
2611
+ m: unknown,
2612
+ path: string,
2613
+ file: string,
2614
+ ): RouteMapping {
2615
+ if (typeof m !== "object" || m === null || Array.isArray(m)) {
2616
+ throw new CliUsageError(`${file} ${path} must be an object`);
2617
+ }
2618
+ const mapping = m as Record<string, unknown>;
2619
+ checkNoCredentials(mapping, path, file);
2620
+
2621
+ for (const key of Object.keys(mapping)) {
2622
+ if (!KNOWN_ROUTE_MAPPING_KEYS.has(key)) {
2623
+ throw new CliUsageError(
2624
+ `${file} ${path} unknown key: ${redactDiagnostic(key)}`,
2625
+ );
2626
+ }
2627
+ }
2628
+
2629
+ if (mapping.logical !== undefined) {
2630
+ if (
2631
+ typeof mapping.logical !== "string" ||
2632
+ mapping.logical.trim().length === 0
2633
+ ) {
2634
+ throw new CliUsageError(
2635
+ `${file} ${path}.logical must be a non-empty string`,
2636
+ );
2637
+ }
2638
+ }
2639
+
2640
+ if (
2641
+ typeof mapping.backend !== "string" ||
2642
+ (mapping.backend !== "claude-code" && mapping.backend !== "opencode")
2643
+ ) {
2644
+ throw new CliUsageError(
2645
+ `${file} ${path}.backend must be claude-code|opencode`,
2646
+ );
2647
+ }
2648
+
2649
+ if (
2650
+ typeof mapping.provider !== "string" ||
2651
+ mapping.provider.trim().length === 0
2652
+ ) {
2653
+ throw new CliUsageError(
2654
+ `${file} ${path}.provider must be a non-empty string`,
2655
+ );
2656
+ }
2657
+
2658
+ if (mapping.gateway !== undefined) {
2659
+ if (
2660
+ typeof mapping.gateway !== "string" ||
2661
+ (mapping.gateway !== "configured" &&
2662
+ mapping.gateway !== "direct" &&
2663
+ mapping.gateway !== "openrouter")
2664
+ ) {
2665
+ throw new CliUsageError(
2666
+ `${file} ${path}.gateway must be configured|direct|openrouter`,
2667
+ );
2668
+ }
2669
+ }
2670
+
2671
+ if (
2672
+ mapping.modelFamily !== undefined &&
2673
+ typeof mapping.modelFamily !== "string"
2674
+ ) {
2675
+ throw new CliUsageError(`${file} ${path}.modelFamily must be a string`);
2676
+ }
2677
+ if (
2678
+ mapping.modelSnapshot !== undefined &&
2679
+ typeof mapping.modelSnapshot !== "string"
2680
+ ) {
2681
+ throw new CliUsageError(`${file} ${path}.modelSnapshot must be a string`);
2682
+ }
2683
+ if (
2684
+ mapping.modelVariant !== undefined &&
2685
+ typeof mapping.modelVariant !== "string"
2686
+ ) {
2687
+ throw new CliUsageError(`${file} ${path}.modelVariant must be a string`);
2688
+ }
2689
+ if (mapping.disabled !== undefined && typeof mapping.disabled !== "boolean") {
2690
+ throw new CliUsageError(`${file} ${path}.disabled must be a boolean`);
2691
+ }
2692
+ if (
2693
+ mapping.allowSpend !== undefined &&
2694
+ typeof mapping.allowSpend !== "boolean"
2695
+ ) {
2696
+ throw new CliUsageError(`${file} ${path}.allowSpend must be a boolean`);
2697
+ }
2698
+
2699
+ return {
2700
+ ...(mapping.logical ? { logical: mapping.logical as string } : {}),
2701
+ backend: mapping.backend as RunnerBackend,
2702
+ provider: mapping.provider as string,
2703
+ ...(mapping.gateway ? { gateway: mapping.gateway as ModelGateway } : {}),
2704
+ ...(mapping.modelFamily
2705
+ ? { modelFamily: mapping.modelFamily as string }
2706
+ : {}),
2707
+ ...(mapping.modelSnapshot
2708
+ ? { modelSnapshot: mapping.modelSnapshot as string }
2709
+ : {}),
2710
+ ...(mapping.modelVariant
2711
+ ? { modelVariant: mapping.modelVariant as string }
2712
+ : {}),
2713
+ ...(mapping.disabled !== undefined
2714
+ ? { disabled: mapping.disabled as boolean }
2715
+ : {}),
2716
+ ...(mapping.allowSpend !== undefined
2717
+ ? { allowSpend: mapping.allowSpend as boolean }
2718
+ : {}),
2719
+ };
2720
+ }
2721
+
2722
+ // Every usage error of the routing object carries the routing class (T2d-1). The CI
2723
+ // routing input (src/ci/setup.ts) keeps its own class and discards this one. The repo
2724
+ // layer passes this parser too, but never reaches a routing value (see
2725
+ // parseLocalConfig). The person layer calls parseRoutingValue directly, so its errors
2726
+ // carry no class.
2727
+ export function parseRoutingConfig(
2728
+ value: unknown,
2729
+ file: string,
2730
+ ): RoutingConfig | undefined {
2731
+ return withUsageClass({ kind: "config-parse", source: "routing" }, () =>
2732
+ parseRoutingValue(value, file),
2733
+ );
2734
+ }
2735
+
2736
+ function parseRoutingValue(
2737
+ value: unknown,
2738
+ file: string,
2739
+ ): RoutingConfig | undefined {
2740
+ if (value === undefined) return undefined;
2741
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
2742
+ throw new CliUsageError(`${file} routing must be an object`);
2743
+ }
2744
+ const routing = value as Record<string, unknown>;
2745
+ checkNoCredentials(routing, "routing", file);
2746
+
2747
+ for (const key of Object.keys(routing)) {
2748
+ if (key !== "mappings" && key !== "default" && key !== "disabled") {
2749
+ throw new CliUsageError(
2750
+ `${file} routing unknown key: ${redactDiagnostic(key)}`,
2751
+ );
2752
+ }
2753
+ }
2754
+
2755
+ let mappings: RouteMapping[] | Record<string, RouteMapping> | undefined;
2756
+ if (routing.mappings !== undefined) {
2757
+ if (Array.isArray(routing.mappings)) {
2758
+ mappings = routing.mappings.map((m, i) =>
2759
+ parseRouteMapping(m, `routing.mappings[${i}]`, file),
2760
+ );
2761
+ } else if (
2762
+ typeof routing.mappings === "object" &&
2763
+ routing.mappings !== null
2764
+ ) {
2765
+ const rec = routing.mappings as Record<string, unknown>;
2766
+ const result: Record<string, RouteMapping> = {};
2767
+ for (const [k, v] of Object.entries(rec)) {
2768
+ result[k] = parseRouteMapping(v, `routing.mappings.${k}`, file);
2769
+ }
2770
+ mappings = result;
2771
+ } else {
2772
+ throw new CliUsageError(
2773
+ `${file} routing.mappings must be an array or object`,
2774
+ );
2775
+ }
2776
+ }
2777
+
2778
+ let def: RouteMapping | undefined;
2779
+ if (routing.default !== undefined) {
2780
+ def = parseRouteMapping(routing.default, "routing.default", file);
2781
+ }
2782
+
2783
+ if (routing.disabled !== undefined && typeof routing.disabled !== "boolean") {
2784
+ throw new CliUsageError(`${file} routing.disabled must be a boolean`);
2785
+ }
2786
+
2787
+ return {
2788
+ ...(mappings ? { mappings } : {}),
2789
+ ...(def ? { default: def } : {}),
2790
+ ...(routing.disabled !== undefined
2791
+ ? { disabled: routing.disabled as boolean }
2792
+ : {}),
2793
+ };
2794
+ }
2795
+
2796
+ function parseSummaryConfig(
2797
+ value: unknown,
2798
+ file: string,
2799
+ ): SummaryConfig | undefined {
2800
+ if (value === undefined) return undefined;
2801
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
2802
+ throw new CliUsageError(`${file} summary must be an object`);
2803
+ }
2804
+ const config = value as Record<string, unknown>;
2805
+ for (const key of Object.keys(config)) {
2806
+ if (key !== "enabled" && key !== "model") {
2807
+ throw new CliUsageError(`${file} summary unknown key: ${key}`);
2808
+ }
2809
+ }
2810
+ if (config.enabled !== undefined && typeof config.enabled !== "boolean") {
2811
+ throw new CliUsageError(`${file} summary.enabled must be a boolean`);
2812
+ }
2813
+ if (
2814
+ config.model !== undefined &&
2815
+ (typeof config.model !== "string" || config.model.trim().length === 0)
2816
+ ) {
2817
+ throw new CliUsageError(`${file} summary.model must be a non-empty string`);
2818
+ }
2819
+ return {
2820
+ ...(config.enabled === undefined ? {} : { enabled: config.enabled }),
2821
+ ...(config.model === undefined ? {} : { model: config.model as string }),
2822
+ };
2823
+ }
2824
+
2825
+ export const DEFAULT_MAX_VERIFICATION_STEPS = 8;
2826
+
2827
+ function parseNonNegativeInteger(
2828
+ value: unknown,
2829
+ key: string,
2830
+ file: string,
2831
+ ): number | undefined {
2832
+ if (value === undefined) return undefined;
2833
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
2834
+ throw new CliUsageError(`${file} ${key} must be a non-negative integer`);
2835
+ }
2836
+ return value;
2837
+ }
2838
+
2839
+ function parsePositiveInteger(
2840
+ value: unknown,
2841
+ key: string,
2842
+ file: string,
2843
+ ): number | undefined {
2844
+ if (value === undefined) return undefined;
2845
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
2846
+ throw new CliUsageError(`${file} ${key} must be a positive integer`);
2847
+ }
2848
+ return value;
2849
+ }
2850
+
2851
+ function parseCiAdmissionInteger(
2852
+ value: unknown,
2853
+ key: string,
2854
+ file: string,
2855
+ min: number,
2856
+ ): number | undefined {
2857
+ if (value === undefined) return undefined;
2858
+ const parsed = parseNonNegativeInteger(value, key, file);
2859
+ if (parsed === undefined) return undefined;
2860
+ if (parsed < min) {
2861
+ throw new CliUsageError(`${file} ${key} must be an integer >= ${min}`);
2862
+ }
2863
+ return parsed;
2864
+ }
2865
+
2866
+ function parseCiReviewPolicyMode(
2867
+ value: unknown,
2868
+ file: string,
2869
+ ): CiReviewPolicyMode | undefined {
2870
+ if (value === undefined) return undefined;
2871
+ if (typeof value !== "string") {
2872
+ throw new CliUsageError(
2873
+ `${file} ci_review_policy must be one of: ${CI_REVIEW_POLICY_MODES.join(", ")}`,
2874
+ );
2875
+ }
2876
+ if (!(CI_REVIEW_POLICY_MODES as readonly string[]).includes(value)) {
2877
+ throw new CliUsageError(
2878
+ `${file} ci_review_policy must be one of: ${CI_REVIEW_POLICY_MODES.join(", ")}`,
2879
+ );
2880
+ }
2881
+ return value as CiReviewPolicyMode;
2882
+ }
2883
+
2884
+ // Widened, not weakened. Each of these reads exactly ONE property, so the
2885
+ // parameter names that property instead of demanding a whole LocalConfig —
2886
+ // which is what lets a caller hand over a raw parsed layer, before the merge
2887
+ // has run, without either side lying about what it needs. The precedence each
2888
+ // resolver applies is untouched.
2889
+ export function resolveMaxVerificationSteps(
2890
+ config: Pick<ConfigLayer, "max_verification_steps">,
2891
+ ): number {
2892
+ return config.max_verification_steps ?? DEFAULT_MAX_VERIFICATION_STEPS;
2893
+ }
2894
+
2895
+ // Undefined, not a default: an absent cap means no gate is constructed at all,
2896
+ // which is today's unlimited behavior byte for byte.
2897
+ export function resolveMaxConcurrentSteps(
2898
+ config: Pick<ConfigLayer, "max_concurrent_steps">,
2899
+ ): number | undefined {
2900
+ return config.max_concurrent_steps;
2901
+ }
2902
+
2903
+ export function resolveSummary(
2904
+ options: Pick<CliOptions, "summary" | "model">,
2905
+ config: Pick<ConfigLayer, "summary">,
2906
+ ): SummarySettings {
2907
+ const model = options.model ?? config.summary?.model;
2908
+ return {
2909
+ enabled: options.summary ?? config.summary?.enabled ?? true,
2910
+ ...(model === undefined ? {} : { model }),
2911
+ };
2912
+ }
2913
+
2914
+ // On by default since the 2026-10-22 Claude bench (musive 1722/1858/853, R=2,
2915
+ // one variable): −28% $/review, −27% wall, no recall loss on the known bugs or
2916
+ // the planted defect. Only an explicit --no-shared-prefix turns it off.
2917
+ export function resolveSharedPrefix(
2918
+ options: Pick<CliOptions, "sharedPrefix">,
2919
+ ): boolean {
2920
+ return options.sharedPrefix !== false;
2921
+ }
2922
+
2923
+ export function resolveScout(
2924
+ options: Pick<CliOptions, "scout">,
2925
+ config: Pick<ConfigLayer, "scout">,
2926
+ ): boolean {
2927
+ return options.scout ?? config.scout ?? false;
2928
+ }
2929
+
2930
+ export function resolvePost(
2931
+ options: Pick<CliOptions, "post">,
2932
+ config: Pick<ConfigLayer, "post">,
2933
+ ): boolean {
2934
+ return options.post ?? config.post ?? false;
2935
+ }
2936
+
2937
+ // Which layer produced each effective value. `capped` is deliberately NOT the
2938
+ // same answer as `global`: the operator needs to see that a ceiling BOUND —
2939
+ // that the team asked for something and was narrowed away — not merely that a
2940
+ // global file happened to exist. `default` means no layer spoke at all and
2941
+ // the downstream resolver's own fallback decides.
2942
+ export type ConfigSource = "global" | "repo" | "capped" | "default";
2943
+
2944
+ // `summary` gets a per-field seat rather than one entry, because its two
2945
+ // fields have DIFFERENT directions and a flat record cannot say
2946
+ // `{ enabled: "capped", model: "global" }`. It is the only nested key, so this
2947
+ // is one seat, not a pattern.
2948
+ export type ConfigSources = Record<
2949
+ Exclude<keyof LocalConfig, "summary">,
2950
+ ConfigSource
2951
+ > & {
2952
+ summary: Record<keyof SummaryConfig, ConfigSource>;
2953
+ };
2954
+
2955
+ type ConfigLayerName = Exclude<ConfigSource, "capped" | "default">;
2956
+
2957
+ interface ConfigLayerEntry {
2958
+ name: ConfigLayerName;
2959
+ layer: ConfigLayer;
2960
+ // WHY a flag and not a name comparison: a `repo`-direction key may only be
2961
+ // folded from a layer that IS scoped to one repository. parseGlobalConfig
2962
+ // rejects those keys, but a fold that leans on another function's rejection
2963
+ // starts reporting `global` for a per-repo key the day that guarantee slips
2964
+ // — and D3b's deferred config.local.json is a second repo-scoped entry, so
2965
+ // `name === "repo"` would be wrong the moment the list grows.
2966
+ repoScoped: boolean;
2967
+ }
2968
+
2969
+ interface FoldedValue<T> {
2970
+ value: T | undefined;
2971
+ source: ConfigSource;
2972
+ }
2973
+
2974
+ function foldKey<T>(
2975
+ layers: readonly ConfigLayerEntry[],
2976
+ direction: ConfigDirection,
2977
+ read: (layer: ConfigLayer) => T | undefined,
2978
+ narrower?: (a: T, b: T) => T,
2979
+ ): FoldedValue<T> {
2980
+ let value: T | undefined;
2981
+ let source: ConfigSource = "default";
2982
+ for (const entry of layers) {
2983
+ if (direction === "repo" && !entry.repoScoped) continue;
2984
+ const spoken = read(entry.layer);
2985
+ if (spoken === undefined) continue;
2986
+ if (
2987
+ value === undefined ||
2988
+ direction !== "capped" ||
2989
+ narrower === undefined
2990
+ ) {
2991
+ value = spoken;
2992
+ source = entry.name;
2993
+ continue;
2994
+ }
2995
+ const narrowed = narrower(value, spoken);
2996
+ // WHY a tie reports the more specific layer and not `capped`: `capped` has
2997
+ // to mean the ceiling actually BOUND, or the operator cannot tell a
2998
+ // narrowing from a coincidence — and deleting the global file would change
2999
+ // nothing about a value both layers already agree on. (Judgment ledger
3000
+ // JD-20 left this label undefined; this is the choice, and it is tested.)
3001
+ value = narrowed;
3002
+ source = narrowed === spoken ? entry.name : "capped";
3003
+ }
3004
+ return { value, source };
3005
+ }
3006
+
3007
+ // The merge, pure: two layers in, one effective LocalConfig plus its per-key
3008
+ // provenance out. The signature names the two layers there are today, but the
3009
+ // body folds over an ORDERED LIST, least specific first — so D3b's deferred
3010
+ // third layer is one entry appended here plus a row in the direction table,
3011
+ // not a rewrite of every rule below.
3012
+ export function mergeConfig(
3013
+ global: ConfigLayer | undefined,
3014
+ repo: ConfigLayer,
3015
+ ): { effective: LocalConfig; sources: ConfigSources } {
3016
+ const layers: ConfigLayerEntry[] = [
3017
+ ...(global === undefined
3018
+ ? []
3019
+ : [{ name: "global" as const, layer: global, repoScoped: false }]),
3020
+ { name: "repo" as const, layer: repo, repoScoped: true },
3021
+ ];
3022
+
3023
+ const agentsDir = foldKey(
3024
+ layers,
3025
+ CONFIG_DIRECTION.agents_dir,
3026
+ (layer) => layer.agents_dir,
3027
+ );
3028
+ const defaultBase = foldKey(
3029
+ layers,
3030
+ CONFIG_DIRECTION.default_base,
3031
+ (layer) => layer.default_base,
3032
+ );
3033
+ const triggers = foldKey(
3034
+ layers,
3035
+ CONFIG_DIRECTION.parity_trigger_paths,
3036
+ (layer) => layer.parity_trigger_paths,
3037
+ );
3038
+ const priors = foldKey(
3039
+ layers,
3040
+ CONFIG_DIRECTION.suspicion_priors,
3041
+ (layer) => layer.suspicion_priors,
3042
+ );
3043
+ // `summary` is descended into per-field: CONFIG_DIRECTION.summary declares
3044
+ // the key for the parsers, SUMMARY_DIRECTION decides each field. Folding the
3045
+ // object whole would silently adopt one layer's entire block.
3046
+ const summaryEnabled = foldKey(
3047
+ layers,
3048
+ SUMMARY_DIRECTION.enabled,
3049
+ (layer) => layer.summary?.enabled,
3050
+ (a, b) => a && b,
3051
+ );
3052
+ const summaryModel = foldKey(
3053
+ layers,
3054
+ SUMMARY_DIRECTION.model,
3055
+ (layer) => layer.summary?.model,
3056
+ );
3057
+ const maxSteps = foldKey(
3058
+ layers,
3059
+ CONFIG_DIRECTION.max_verification_steps,
3060
+ (layer) => layer.max_verification_steps,
3061
+ Math.min,
3062
+ );
3063
+ const maxConcurrentSteps = foldKey(
3064
+ layers,
3065
+ CONFIG_DIRECTION.max_concurrent_steps,
3066
+ (layer) => layer.max_concurrent_steps,
3067
+ Math.min,
3068
+ );
3069
+ const narrowSizeLimit = (a: number, b: number): number => {
3070
+ if (a === 0) return b;
3071
+ if (b === 0) return a;
3072
+ return Math.min(a, b);
3073
+ };
3074
+ const maxLines = foldKey(
3075
+ layers,
3076
+ CONFIG_DIRECTION.max_changed_lines,
3077
+ (layer) => layer.max_changed_lines,
3078
+ narrowSizeLimit,
3079
+ );
3080
+ const maxFiles = foldKey(
3081
+ layers,
3082
+ CONFIG_DIRECTION.max_changed_files,
3083
+ (layer) => layer.max_changed_files,
3084
+ narrowSizeLimit,
3085
+ );
3086
+ const scout = foldKey(
3087
+ layers,
3088
+ CONFIG_DIRECTION.scout,
3089
+ (layer) => layer.scout,
3090
+ (a, b) => a && b,
3091
+ );
3092
+ const post = foldKey(
3093
+ layers,
3094
+ CONFIG_DIRECTION.post,
3095
+ (layer) => layer.post,
3096
+ (a, b) => a && b,
3097
+ );
3098
+ const routing = foldKey(
3099
+ layers,
3100
+ CONFIG_DIRECTION.routing,
3101
+ (layer) => layer.routing,
3102
+ );
3103
+ const ciReviewPolicy = foldKey(
3104
+ layers,
3105
+ CONFIG_DIRECTION.ci_review_policy,
3106
+ (layer) => layer.ci_review_policy,
3107
+ );
3108
+ const ciMaxAttempts = foldKey(
3109
+ layers,
3110
+ CONFIG_DIRECTION.ci_max_attempts,
3111
+ (layer) => layer.ci_max_attempts,
3112
+ );
3113
+ const ciMaxReviews = foldKey(
3114
+ layers,
3115
+ CONFIG_DIRECTION.ci_max_reviews,
3116
+ (layer) => layer.ci_max_reviews,
3117
+ );
3118
+ const ciRereviewMinScore = foldKey(
3119
+ layers,
3120
+ CONFIG_DIRECTION.ci_rereview_min_score,
3121
+ (layer) => layer.ci_rereview_min_score,
3122
+ );
3123
+ const ciBlockingWeight = foldKey(
3124
+ layers,
3125
+ CONFIG_DIRECTION.ci_blocking_weight,
3126
+ (layer) => layer.ci_blocking_weight,
3127
+ );
3128
+ const ciAdvisoryWeight = foldKey(
3129
+ layers,
3130
+ CONFIG_DIRECTION.ci_advisory_weight,
3131
+ (layer) => layer.ci_advisory_weight,
3132
+ );
3133
+ const ciTrustedActors = foldKey(
3134
+ layers,
3135
+ CONFIG_DIRECTION.ci_trusted_actors,
3136
+ (layer) => layer.ci_trusted_actors,
3137
+ (a, b) => [...(a ?? []), ...(b ?? [])],
3138
+ );
3139
+ const ciAdmissionObserveOnly = foldKey(
3140
+ layers,
3141
+ CONFIG_DIRECTION.ci_admission_observe_only,
3142
+ (layer) => layer.ci_admission_observe_only,
3143
+ );
3144
+
3145
+ const summary: SummaryConfig = {
3146
+ ...(summaryEnabled.value === undefined
3147
+ ? {}
3148
+ : { enabled: summaryEnabled.value }),
3149
+ ...(summaryModel.value === undefined ? {} : { model: summaryModel.value }),
3150
+ };
3151
+
3152
+ const effective: LocalConfig = {
3153
+ // The ONE place `[]` is materialised, and it is here on purpose: the fold
3154
+ // above ran on absence and has already recorded `source: "default"` for a
3155
+ // key nobody named, so the array can be handed to the resolvers without
3156
+ // that fact being lost. Materialising it any earlier is what made
3157
+ // provenance a lie.
3158
+ parity_trigger_paths: triggers.value ?? [],
3159
+ suspicion_priors: priors.value ?? [],
3160
+ ...(agentsDir.value === undefined ? {} : { agents_dir: agentsDir.value }),
3161
+ ...(defaultBase.value === undefined
3162
+ ? {}
3163
+ : { default_base: defaultBase.value }),
3164
+ ...(summaryEnabled.value === undefined && summaryModel.value === undefined
3165
+ ? {}
3166
+ : { summary }),
3167
+ ...(routing.value === undefined ? {} : { routing: routing.value }),
3168
+ ...(maxSteps.value === undefined
3169
+ ? {}
3170
+ : { max_verification_steps: maxSteps.value }),
3171
+ ...(maxConcurrentSteps.value === undefined
3172
+ ? {}
3173
+ : { max_concurrent_steps: maxConcurrentSteps.value }),
3174
+ ...(maxLines.value === undefined
3175
+ ? {}
3176
+ : { max_changed_lines: maxLines.value }),
3177
+ ...(maxFiles.value === undefined
3178
+ ? {}
3179
+ : { max_changed_files: maxFiles.value }),
3180
+ ...(scout.value === undefined ? {} : { scout: scout.value }),
3181
+ ...(post.value === undefined ? {} : { post: post.value }),
3182
+ ...(ciReviewPolicy.value === undefined
3183
+ ? {}
3184
+ : { ci_review_policy: ciReviewPolicy.value }),
3185
+ ...(ciMaxAttempts.value === undefined
3186
+ ? {}
3187
+ : { ci_max_attempts: ciMaxAttempts.value }),
3188
+ ...(ciMaxReviews.value === undefined
3189
+ ? {}
3190
+ : { ci_max_reviews: ciMaxReviews.value }),
3191
+ ...(ciRereviewMinScore.value === undefined
3192
+ ? {}
3193
+ : { ci_rereview_min_score: ciRereviewMinScore.value }),
3194
+ ...(ciBlockingWeight.value === undefined
3195
+ ? {}
3196
+ : { ci_blocking_weight: ciBlockingWeight.value }),
3197
+ ...(ciAdvisoryWeight.value === undefined
3198
+ ? {}
3199
+ : { ci_advisory_weight: ciAdvisoryWeight.value }),
3200
+ ...(ciTrustedActors.value === undefined ||
3201
+ ciTrustedActors.value.length === 0
3202
+ ? {}
3203
+ : { ci_trusted_actors: ciTrustedActors.value }),
3204
+ ...(ciAdmissionObserveOnly.value === undefined
3205
+ ? {}
3206
+ : { ci_admission_observe_only: ciAdmissionObserveOnly.value }),
3207
+ };
3208
+
3209
+ const sources: ConfigSources = {
3210
+ agents_dir: agentsDir.source,
3211
+ default_base: defaultBase.source,
3212
+ parity_trigger_paths: triggers.source,
3213
+ suspicion_priors: priors.source,
3214
+ summary: { enabled: summaryEnabled.source, model: summaryModel.source },
3215
+ routing: routing.source,
3216
+ max_verification_steps: maxSteps.source,
3217
+ max_concurrent_steps: maxConcurrentSteps.source,
3218
+ max_changed_lines: maxLines.source,
3219
+ max_changed_files: maxFiles.source,
3220
+ scout: scout.source,
3221
+ post: post.source,
3222
+ ci_review_policy: ciReviewPolicy.source,
3223
+ ci_max_attempts: ciMaxAttempts.source,
3224
+ ci_max_reviews: ciMaxReviews.source,
3225
+ ci_rereview_min_score: ciRereviewMinScore.source,
3226
+ ci_blocking_weight: ciBlockingWeight.source,
3227
+ ci_advisory_weight: ciAdvisoryWeight.source,
3228
+ ci_trusted_actors: ciTrustedActors.source,
3229
+ ci_admission_observe_only: ciAdmissionObserveOnly.source,
3230
+ };
3231
+
3232
+ return { effective, sources };
3233
+ }
3234
+
3235
+ // Same fail-loud discipline as the two array keys: an `agents_dir` that is a
3236
+ // number, or an empty `default_base`, must not be read as "absent" — that is
3237
+ // how a config silently stops configuring anything.
3238
+ function optionalString(
3239
+ config: Record<string, unknown>,
3240
+ key: "agents_dir" | "default_base",
3241
+ file: string,
3242
+ ): Record<string, string> {
3243
+ const value = config[key];
3244
+ if (value === undefined || value === null) return {};
3245
+ if (typeof value !== "string" || value.trim().length === 0) {
3246
+ throw new CliUsageError(`${file} ${key} must be a non-empty string`);
3247
+ }
3248
+ return { [key]: value };
3249
+ }
3250
+
3251
+ export interface InitTemplateInput {
3252
+ agentsDir?: string | undefined;
3253
+ defaultBase: string;
3254
+ // What `~/.crysk/config.json` ALREADY says, or undefined when the operator
3255
+ // has no global file. C5 O-9: a scaffold that re-states what the global
3256
+ // layer already supplies ships the exact duplication C5 exists to delete —
3257
+ // §0.5 measured three byte-identical 212-byte configs on one machine.
3258
+ global?: ConfigLayer;
3259
+ // True when `--agents` named the prompt set on THIS init. A deliberate
3260
+ // narrowing of O-9's letter ("does not write a person key when the global
3261
+ // supplies it"), and D5's reasoning one command earlier: a flag is the
3262
+ // operator typing an intent, and a flag that parses and then writes nothing
3263
+ // is an operator believing they scaffolded a repo they did not. `PRHERO_
3264
+ // AGENTS_DIR` gets no such exception — the merged config already beats the
3265
+ // env var at review time (judgment ledger JD-9), so writing the env value
3266
+ // into the repo file would silently CHANGE which prompt set runs, not
3267
+ // preserve it.
3268
+ agentsDirFromFlag?: boolean;
3269
+ }
3270
+
3271
+ export interface InitTemplateOmissions {
3272
+ agentsDir: boolean;
3273
+ summaryEnabled: boolean;
3274
+ summaryModel: boolean;
3275
+ // The same three facts as config-file key names, for init's log. Derived
3276
+ // here rather than rebuilt at the call site, because a scaffold that omits a
3277
+ // key and a log that does not mention it is worse than either alone: the
3278
+ // operator reads "agents_dir <path>" and never learns the file does not
3279
+ // contain that line.
3280
+ keys: string[];
3281
+ }
3282
+
3283
+ // Which person/capped keys the repo scaffold LEAVES OUT, decided once and read
3284
+ // by both the template below and init's own log.
3285
+ //
3286
+ // `default_base` is NOT here and must never be: it is a `repo` key (D4),
3287
+ // `parseGlobalConfig` rejects it by name, so no global file can supply it and
3288
+ // omitting it would scaffold a repo with no base ref at all. The two array
3289
+ // keys are `repo` for the same reason. `summary.enabled` IS here even though
3290
+ // O-9's wording names only the person keys — the template hardcodes `true`,
3291
+ // which is exactly the value `capped` forbids the team file from raising over
3292
+ // a global `false` (judgment ledger JD-17), so seeding it against a global
3293
+ // that already spoke writes a line that is either dead on arrival or pure
3294
+ // duplication.
3295
+ export function initTemplateOmissions(
3296
+ input: InitTemplateInput,
3297
+ ): InitTemplateOmissions {
3298
+ const agentsDir =
3299
+ input.agentsDir === undefined ||
3300
+ (input.global?.agents_dir !== undefined &&
3301
+ input.agentsDirFromFlag !== true);
3302
+ const summaryEnabled = input.global?.summary?.enabled !== undefined;
3303
+ const summaryModel = input.global?.summary?.model !== undefined;
3304
+ return {
3305
+ agentsDir,
3306
+ summaryEnabled,
3307
+ summaryModel,
3308
+ keys: [
3309
+ ...(agentsDir ? ["agents_dir"] : []),
3310
+ ...(summaryEnabled ? ["summary.enabled"] : []),
3311
+ ...(summaryModel ? ["summary.model"] : []),
3312
+ ],
3313
+ };
3314
+ }
3315
+
3316
+ // The scaffold `pr-hero init` writes. Kept pure and next to parseLocalConfig
3317
+ // on purpose: a template its own parser would reject is a bug that only shows
3318
+ // up on someone else's machine, and a round-trip test through parseLocalConfig
3319
+ // costs nothing.
3320
+ //
3321
+ // With no global layer the bytes are exactly what they were before C5 — the
3322
+ // regression boundary, and the reason `global` is optional rather than
3323
+ // required.
3324
+ export function initConfigTemplate(input: InitTemplateInput): string {
3325
+ const omit = initTemplateOmissions(input);
3326
+ const summary: SummaryConfig = {
3327
+ ...(omit.summaryEnabled ? {} : { enabled: true }),
3328
+ ...(omit.summaryModel ? {} : { model: DEFAULT_SUMMARY_MODEL }),
3329
+ };
3330
+ return `${JSON.stringify(
3331
+ {
3332
+ ...(omit.agentsDir ? {} : { agents_dir: input.agentsDir }),
3333
+ // Always written, whatever the global file says.
3334
+ default_base: input.defaultBase,
3335
+ // Dropped WHOLE when both fields hoisted: `"summary": {}` parses fine
3336
+ // and configures nothing, which is a line whose only effect is to make
3337
+ // the next reader wonder what it does.
3338
+ ...(Object.keys(summary).length === 0 ? {} : { summary }),
3339
+ parity_trigger_paths: [],
3340
+ suspicion_priors: [],
3341
+ },
3342
+ null,
3343
+ 2,
3344
+ )}\n`;
3345
+ }
3346
+
3347
+ // WHY init says this out loud: an untracked file under .crysk/ dirties the
3348
+ // working tree, and the clean-tree gate in cli.ts then refuses to run at all.
3349
+ // A first-time user who scaffolds and immediately hits "the working tree is
3350
+ // dirty" has no way to connect the two.
3351
+ // `dirName` is the directory the command actually wrote into (an existing
3352
+ // legacy .prhero/ is updated in place), so the advice names a real path.
3353
+ export function initGitReminder(dirName: string = REPO_DIR_NAME): string {
3354
+ return (
3355
+ `Now either commit ${dirName}/ or add it to .gitignore. Every review step ` +
3356
+ "reads the checkout directly, so Crysk refuses to run on a dirty tree — " +
3357
+ `and an untracked ${dirName}/ is exactly that.`
3358
+ );
3359
+ }
3360
+
3361
+ // The token every scaffolded gotchas file carries, and the primary signal
3362
+ // that distinguishes "nobody has written this yet" from a real file (the
3363
+ // exact-line rule further down is the only other one). It is not a
3364
+ // new invention: `pr-hero setup`'s fallback already wrote it (wizard.ts), it
3365
+ // simply had no reader. `pr-hero init`'s template now carries it too, so both
3366
+ // scaffolds are detectable by one token instead of by matching their prose.
3367
+ //
3368
+ // WHY a marker rather than a heuristic (a `<subsystem>` scan, a length floor):
3369
+ // a marker is a file DECLARING itself unfinished. Anything inferred from the
3370
+ // prose would eventually reject somebody's real gotchas for looking generic,
3371
+ // and the cost of a false positive here is a refused review.
3372
+ //
3373
+ // The one inference allowed beside the marker is an EXACT one: a file whose
3374
+ // every non-blank line is a line one of our own scaffolds wrote. That is not
3375
+ // a heuristic about prose — no real gotchas file consists solely of our
3376
+ // template lines — and a real file that keeps one stray template line beside
3377
+ // real ones still passes. It exists because a scaffold without its marker
3378
+ // line — deleted by hand, or committed before the marker existed — reached
3379
+ // every hunter as if it were real.
3380
+ export const GOTCHAS_PLACEHOLDER_MARKER = "human-attention-required";
3381
+
3382
+ export const GOTCHAS_TEMPLATE = `<!-- ${GOTCHAS_PLACEHOLDER_MARKER}: delete THIS line once the gotchas below are real — Crysk refuses to review while it is here. -->
3383
+ # Repo gotchas
3384
+
3385
+ Facts a reviewer cannot infer from the diff alone. Each line is injected
3386
+ verbatim into every hunter's system prompt, so keep them short and true.
3387
+
3388
+ - <subsystem>: <the thing that looks like a bug but is deliberate, and why>
3389
+ - <subsystem>: <the invariant that is enforced somewhere the diff does not show>
3390
+ - <subsystem>: <the naming/ownership rule a newcomer would violate>
3391
+ `;
3392
+
3393
+ // `pr-hero setup`'s fallback scaffold (wizard.ts writes it when onboarding
3394
+ // collected zero invariants). It lives here, beside GOTCHAS_TEMPLATE, so the
3395
+ // gate below can recognise both scaffolds from one place.
3396
+ export const SETUP_GOTCHAS_FALLBACK = `<!-- ${GOTCHAS_PLACEHOLDER_MARKER}: zero invariants defined during onboarding -->\n\n# Repository Gotchas & Invariants\n\n(No invariants defined during onboarding. Replace this with your project's real failure modes, then delete the marker line at the top — Crysk refuses to review while it is there.)\n`;
3397
+
3398
+ // Every non-blank line the two scaffolds write, minus the marker line. A file
3399
+ // made ONLY of these lines is a scaffold nobody filled in, whether its marker
3400
+ // was deleted or it predates the marker. musive committed the pre-marker
3401
+ // template, and its three `<subsystem>` lines were injected into every hunter.
3402
+ //
3403
+ // RETIRED lines are ones an earlier release's scaffold wrote and today's no
3404
+ // longer does. A repo may still have them committed, so when a scaffold's
3405
+ // wording changes, its old lines move here — otherwise that repo's scaffold
3406
+ // slips past the gate again. (GOTCHAS_TEMPLATE's body has never changed; the
3407
+ // setup fallback's sentence did, in 60c28c6.)
3408
+ const RETIRED_SCAFFOLD_LINES = [
3409
+ "(No invariants defined during onboarding. Edit this file with project failure modes.)",
3410
+ ];
3411
+
3412
+ const SCAFFOLD_BODY_LINES = new Set([
3413
+ ...[GOTCHAS_TEMPLATE, SETUP_GOTCHAS_FALLBACK]
3414
+ .flatMap((scaffold) => scaffold.split("\n"))
3415
+ .map((line) => line.trim())
3416
+ .filter(
3417
+ (line) => line.length > 0 && !line.includes(GOTCHAS_PLACEHOLDER_MARKER),
3418
+ ),
3419
+ ...RETIRED_SCAFFOLD_LINES,
3420
+ ]);
3421
+
3422
+ export type GotchasUnusableReason = "empty" | "placeholder";
3423
+
3424
+ // The one gate every gotchas call site asks — local review, PR review, the
3425
+ // pipeline's fail-loud abort, and `doctor`. It is a single exported predicate
3426
+ // on purpose: four copies of `gotchas.trim().length === 0` are four things
3427
+ // that drift apart, and the one they had already drifted from was the promise
3428
+ // printed above them ("pr-hero refuses to run without it").
3429
+ //
3430
+ // The two arms are disjoint, so their order is NOT observable: a file holding
3431
+ // the marker holds a non-whitespace token and therefore cannot also trim to
3432
+ // empty. `empty` goes first only because it is the cheaper test. (The two
3433
+ // reasons still render different messages — that is about what the caller
3434
+ // says, not about which branch wins.)
3435
+ export function gotchasUnusableReason(
3436
+ text: string,
3437
+ ): GotchasUnusableReason | undefined {
3438
+ if (text.trim().length === 0) return "empty";
3439
+ if (text.includes(GOTCHAS_PLACEHOLDER_MARKER)) return "placeholder";
3440
+ const lines = text
3441
+ .split("\n")
3442
+ .map((line) => line.trim())
3443
+ .filter((line) => line.length > 0);
3444
+ if (lines.every((line) => SCAFFOLD_BODY_LINES.has(line))) {
3445
+ return "placeholder";
3446
+ }
3447
+ return undefined;
3448
+ }
3449
+
3450
+ // `pr-hero init`'s closing instruction block, as data.
3451
+ //
3452
+ // WHY it is a function of the outcome rather than a constant: `init` never
3453
+ // overwrites, so the file the block talks about is either the scaffold this
3454
+ // run just wrote or somebody else's file that was left alone — and those two
3455
+ // need different sentences. Printed unconditionally, this block told a repo
3456
+ // with real gotchas to "replace the <subsystem> lines" and "delete the
3457
+ // marker line", neither of which is in its file. That is the same defect the
3458
+ // `gotchas.trim().length === 0` gate was: a message asserting a state nobody
3459
+ // checked.
3460
+ //
3461
+ // The KEPT arms therefore assert nothing of their own. They report what
3462
+ // `gotchasUnusableReason` — the one gate every other call site uses — says
3463
+ // about the bytes actually on disk, so the block cannot drift from the
3464
+ // behaviour a following `pr-hero review` will have.
3465
+ //
3466
+ // The union is discriminated rather than a pair of optional fields on
3467
+ // purpose: there is no `{ written: true, contents }` to get wrong, and no
3468
+ // kept arm that forgot to pass the bytes.
3469
+ export function initGotchasInstructions(
3470
+ outcome: { written: true } | { written: false; contents: string },
3471
+ dirName: string = REPO_DIR_NAME,
3472
+ ): string[] {
3473
+ if (outcome.written) {
3474
+ // Safe ONLY on this arm: the file is GOTCHAS_TEMPLATE, so it really does
3475
+ // carry `<subsystem>` lines and the marker.
3476
+ //
3477
+ // "refuses to run without it" was true of an ABSENT file and false of the
3478
+ // one this command just wrote: the scaffold is non-empty, so it used to
3479
+ // sail through the old gate and prime every hunter with `<subsystem>`
3480
+ // placeholders. The marker is what makes the old sentence true, so the
3481
+ // instruction has to name the marker.
3482
+ return [
3483
+ `Then edit ${dirName}/gotchas.md — two steps, both required:`,
3484
+ " 1. replace the <subsystem> lines with facts about this repo",
3485
+ ` 2. delete the \`${GOTCHAS_PLACEHOLDER_MARKER}\` marker line at the top`,
3486
+ "",
3487
+ "Crysk refuses to review while that marker is present. It is not " +
3488
+ "pedantry: the file above is non-empty, so without the marker a " +
3489
+ "review would bill in full for hunters primed with placeholder text " +
3490
+ "and report a clean-LOOKING result.",
3491
+ ];
3492
+ }
3493
+
3494
+ const reason = gotchasUnusableReason(outcome.contents);
3495
+ if (reason === "placeholder") {
3496
+ // NOT "replace the <subsystem> lines": a kept scaffold may be `pr-hero
3497
+ // setup`'s fallback (wizard.ts), which carries the marker and has no
3498
+ // `<subsystem>` lines at all. Naming them would be this same defect one
3499
+ // layer down.
3500
+ return [
3501
+ `The ${dirName}/gotchas.md already on disk is still a scaffold: it carries ` +
3502
+ `the \`${GOTCHAS_PLACEHOLDER_MARKER}\` marker line or nothing but the ` +
3503
+ "scaffold's own lines, and Crysk refuses to review it.",
3504
+ "",
3505
+ "Write facts about THIS repo into it, and delete the marker line if it " +
3506
+ "is still there.",
3507
+ ];
3508
+ }
3509
+ if (reason === "empty") {
3510
+ // No marker in an empty file, so nothing to delete — saying otherwise
3511
+ // would send the reader looking for a line that is not there.
3512
+ return [
3513
+ `The ${dirName}/gotchas.md already on disk is empty, and Crysk refuses ` +
3514
+ "to review without gotchas: an empty file makes the whole review a " +
3515
+ "zero-cost no-op that LOOKS like a clean result.",
3516
+ "",
3517
+ "Write facts about THIS repo into it — the deliberate oddities, the " +
3518
+ "invariants enforced somewhere the diff does not show.",
3519
+ ];
3520
+ }
3521
+ // Deliberately modest wording. The gate proves only that the file is
3522
+ // non-empty and marker-free; it does not prove the contents are good, so
3523
+ // this line reports the gate and claims nothing beyond it.
3524
+ return [
3525
+ `The ${dirName}/gotchas.md already on disk passes the gotchas gate and will ` +
3526
+ "be used as-is.",
3527
+ ];
3528
+ }
3529
+
3530
+ // The pipeline treats unusable gotchas as a fail-loud abort and returns a
3531
+ // zero-cost partial run. Correct, but a bare "partial, 0 findings" tells the
3532
+ // user nothing — so the CLI checks first and explains.
3533
+ export function gotchasErrorMessage(
3534
+ gotchasPath: string,
3535
+ reason: GotchasUnusableReason,
3536
+ ): string {
3537
+ const why = [
3538
+ "Gotchas are the repo-specific facts a hunter cannot infer from the diff",
3539
+ "— deliberate oddities, invariants enforced elsewhere, conventions worth",
3540
+ "more than they look. They are injected verbatim into every hunter's",
3541
+ "system prompt, and the engine refuses to run without them.",
3542
+ ];
3543
+ if (reason === "placeholder") {
3544
+ return [
3545
+ `gotchas file is still the scaffold nobody filled in: ${gotchasPath}`,
3546
+ "",
3547
+ ...why,
3548
+ "",
3549
+ `It still carries the \`${GOTCHAS_PLACEHOLDER_MARKER}\` marker line, or`,
3550
+ "nothing but the lines `crysk init` and `crysk setup` scaffold.",
3551
+ "Reviewing with it would spend real money feeding every hunter",
3552
+ "placeholder text, and return a clean-LOOKING result.",
3553
+ "",
3554
+ "Replace the placeholder lines with facts about THIS repo, and delete",
3555
+ "the marker line at the top if it is still there.",
3556
+ ].join("\n");
3557
+ }
3558
+ return [
3559
+ `missing or empty gotchas file: ${gotchasPath}`,
3560
+ "",
3561
+ ...why,
3562
+ "An empty file makes the whole review a zero-cost no-op that LOOKS like a",
3563
+ "clean result.",
3564
+ "",
3565
+ "Create it with something like:",
3566
+ "",
3567
+ GOTCHAS_TEMPLATE,
3568
+ // The template above ships the marker, and the marker is itself a
3569
+ // refusal — so a reader who copies this and stops has produced a file
3570
+ // pr-hero still rejects. Saying the last step out loud is not politeness;
3571
+ // without it this message hands you the next error.
3572
+ `Then replace the <subsystem> lines and delete the \`${GOTCHAS_PLACEHOLDER_MARKER}\``,
3573
+ "marker line — Crysk refuses to review while that line is present.",
3574
+ ].join("\n");
3575
+ }