crysk 0.0.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +611 -3
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/SKILL-y8rv8msh.md +134 -0
  10. package/dist/SKILL-ygka1bs0.md +515 -0
  11. package/dist/adjudicator-dtg2axnh.md +86 -0
  12. package/dist/admission-config.example-a9vqmmad.json +9 -0
  13. package/dist/ci-admission-camfbx2b.md +122 -0
  14. package/dist/ci-admission-qk9r9taq.md +124 -0
  15. package/dist/cli.js +42501 -0
  16. package/dist/consolidate-ac0mnfyj.md +24 -0
  17. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  18. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  19. package/dist/deep-review-parity-0ec904db.md +120 -0
  20. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  21. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  22. package/dist/index.js +20190 -0
  23. package/dist/opencode-ci-7b0be64p.md +141 -0
  24. package/dist/review-refuter-j4e9gezy.md +71 -0
  25. package/dist/scout-yvp153q7.md +140 -0
  26. package/dist/summarizer-zca44nxa.md +18 -0
  27. package/dist/workflow-w1g9szna.yml +151 -0
  28. package/package.json +81 -4
  29. package/prompts/consolidate.md +24 -0
  30. package/prompts/default/PROVENANCE.md +18 -0
  31. package/prompts/default/deep-review-lifecycle.md +362 -0
  32. package/prompts/default/deep-review-logic.md +156 -0
  33. package/prompts/default/deep-review-parity.md +120 -0
  34. package/prompts/default/deep-review-reliability.md +125 -0
  35. package/prompts/default/deep-review-resilience.md +118 -0
  36. package/prompts/default/review-refuter.md +71 -0
  37. package/prompts/scout.md +140 -0
  38. package/prompts/summarizer.md +18 -0
  39. package/skills/crysk/SKILL.md +74 -0
  40. package/skills/crysk-ci-setup/SKILL.md +134 -0
  41. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  42. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  43. package/skills/crysk-ci-setup/references/ci-admission.md +124 -0
  44. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  45. package/skills/crysk-loop/SKILL.md +515 -0
  46. package/skills/crysk-loop/adjudicator.md +86 -0
  47. package/skills/crysk-pr/SKILL.md +66 -0
  48. package/src/agent-env.ts +1084 -0
  49. package/src/asset-manifest.ts +83 -0
  50. package/src/assets.d.ts +6 -0
  51. package/src/assets.ts +183 -0
  52. package/src/brand-paths.ts +155 -0
  53. package/src/brand.ts +255 -0
  54. package/src/ci/admission-ledger.ts +350 -0
  55. package/src/ci/classify-error.ts +73 -0
  56. package/src/ci/cli-record.ts +271 -0
  57. package/src/ci/force-comment.ts +39 -0
  58. package/src/ci/gates.ts +945 -0
  59. package/src/ci/outcome.ts +2181 -0
  60. package/src/ci/override.ts +187 -0
  61. package/src/ci/publish.ts +1639 -0
  62. package/src/ci/reporter.ts +626 -0
  63. package/src/ci/review-admission.ts +910 -0
  64. package/src/ci/review-levels.ts +310 -0
  65. package/src/ci/review-policy.ts +18 -0
  66. package/src/ci/review-risk.ts +184 -0
  67. package/src/ci/setup.ts +844 -0
  68. package/src/ci/trigger.ts +1353 -0
  69. package/src/cli.ts +348 -0
  70. package/src/commands/activity.ts +67 -0
  71. package/src/commands/ci-setup-questions.ts +397 -0
  72. package/src/commands/ci-setup.ts +381 -0
  73. package/src/commands/config.ts +99 -0
  74. package/src/commands/doctor.ts +108 -0
  75. package/src/commands/init.ts +139 -0
  76. package/src/commands/mcp.ts +10 -0
  77. package/src/commands/menu.ts +129 -0
  78. package/src/commands/post.ts +302 -0
  79. package/src/commands/skills.ts +83 -0
  80. package/src/commands/status.ts +173 -0
  81. package/src/commands/triage.ts +342 -0
  82. package/src/commands/uninstall.ts +37 -0
  83. package/src/commands/upgrade.ts +214 -0
  84. package/src/commands/usage.ts +98 -0
  85. package/src/compare/compare.ts +28 -0
  86. package/src/compare/floor-test.ts +471 -0
  87. package/src/compare/martian-adapter.ts +80 -0
  88. package/src/config/config.ts +267 -0
  89. package/src/corpus/corpus.ts +1094 -0
  90. package/src/corpus/preflight.ts +1789 -0
  91. package/src/diversity/accounting.ts +90 -0
  92. package/src/diversity/adjudication.ts +145 -0
  93. package/src/diversity/admission.ts +60 -0
  94. package/src/diversity/benchmark.ts +195 -0
  95. package/src/diversity/clustering.ts +285 -0
  96. package/src/diversity/errors.ts +7 -0
  97. package/src/diversity/identity.ts +285 -0
  98. package/src/diversity/index.ts +11 -0
  99. package/src/diversity/pipeline-integration.ts +448 -0
  100. package/src/diversity/projection.ts +57 -0
  101. package/src/diversity/self-contained.ts +68 -0
  102. package/src/diversity/target-validation.ts +179 -0
  103. package/src/doctor-migration.ts +209 -0
  104. package/src/doctor.ts +723 -0
  105. package/src/errors.ts +83 -0
  106. package/src/execution/admission.ts +75 -0
  107. package/src/execution/atomic-write.ts +35 -0
  108. package/src/execution/attempt-evidence.ts +415 -0
  109. package/src/execution/bucket-id.ts +136 -0
  110. package/src/execution/concurrency-limiter.ts +175 -0
  111. package/src/execution/contracts.ts +443 -0
  112. package/src/execution/failure-classification.ts +42 -0
  113. package/src/execution/failure-policy.ts +240 -0
  114. package/src/execution/harness.ts +2548 -0
  115. package/src/execution/settlement.ts +348 -0
  116. package/src/execution/spawned-process.ts +66 -0
  117. package/src/execution/spend-limiter.ts +424 -0
  118. package/src/execution/step-artifacts.ts +55 -0
  119. package/src/execution/usage-normalized.ts +469 -0
  120. package/src/git/git.ts +396 -0
  121. package/src/git/identity.ts +64 -0
  122. package/src/git/refs.ts +140 -0
  123. package/src/home-preflight.ts +443 -0
  124. package/src/home.ts +243 -0
  125. package/src/ignore-file.ts +336 -0
  126. package/src/ignore-read.ts +118 -0
  127. package/src/index.ts +34 -0
  128. package/src/legacy-launchd.ts +29 -0
  129. package/src/mcp/mcp.ts +150 -0
  130. package/src/mcp/preflight.ts +407 -0
  131. package/src/menu-context.ts +192 -0
  132. package/src/model/catalog.ts +251 -0
  133. package/src/model/exec-snapshots.ts +390 -0
  134. package/src/model/free-discovery.ts +302 -0
  135. package/src/model/provider-capabilities.ts +814 -0
  136. package/src/model/routing.ts +600 -0
  137. package/src/pr/admission.ts +984 -0
  138. package/src/pr/answered-findings.ts +169 -0
  139. package/src/pr/ci-admission-gate.ts +743 -0
  140. package/src/pr/ci-publish.ts +76 -0
  141. package/src/pr/discovery.ts +432 -0
  142. package/src/pr/inline.ts +507 -0
  143. package/src/pr/plan.ts +366 -0
  144. package/src/pr/posting.ts +115 -0
  145. package/src/pr/pr-status.ts +845 -0
  146. package/src/pr/pr.ts +3642 -0
  147. package/src/pr/preflight.ts +1031 -0
  148. package/src/pr/publish-outcome.ts +361 -0
  149. package/src/pr/range.ts +119 -0
  150. package/src/pr/reverts-preflight.ts +606 -0
  151. package/src/pr/reverts.ts +377 -0
  152. package/src/pr/review-pr.ts +927 -0
  153. package/src/pr/status.ts +154 -0
  154. package/src/pr/target.ts +388 -0
  155. package/src/pr/teardown.ts +437 -0
  156. package/src/pr/worktree-setup.ts +60 -0
  157. package/src/production-runtime.ts +1877 -0
  158. package/src/progress.ts +487 -0
  159. package/src/rereview/adjudicate.ts +89 -0
  160. package/src/rereview/classify.ts +362 -0
  161. package/src/rereview/identity.ts +211 -0
  162. package/src/rereview/plan.ts +308 -0
  163. package/src/rereview/prepare.ts +1025 -0
  164. package/src/rereview/state.ts +767 -0
  165. package/src/rereview/verify.ts +241 -0
  166. package/src/review/boundary.ts +105 -0
  167. package/src/review/consolidate.ts +246 -0
  168. package/src/review/dedupe.ts +368 -0
  169. package/src/review/drafts.ts +448 -0
  170. package/src/review/findings-conformance.ts +120 -0
  171. package/src/review/findings.ts +714 -0
  172. package/src/review/pipeline.ts +3977 -0
  173. package/src/review/preflight.ts +3575 -0
  174. package/src/review/prompt-set.ts +177 -0
  175. package/src/review/proof-refs.ts +187 -0
  176. package/src/review/report.ts +1821 -0
  177. package/src/review/review.ts +490 -0
  178. package/src/review/root-cause.ts +120 -0
  179. package/src/review/route-preflight.ts +289 -0
  180. package/src/review/run.ts +601 -0
  181. package/src/review/scout.ts +323 -0
  182. package/src/review/size-gate.ts +595 -0
  183. package/src/review/spec.ts +235 -0
  184. package/src/review/step-runner.ts +233 -0
  185. package/src/runner-authority.ts +596 -0
  186. package/src/security/binding-policy.ts +115 -0
  187. package/src/security/credential-broker.ts +773 -0
  188. package/src/security/evidence-redaction.ts +62 -0
  189. package/src/security/execution-authority.ts +27 -0
  190. package/src/security/redact.ts +71 -0
  191. package/src/security/workspace-read-broker.ts +466 -0
  192. package/src/server/client.ts +190 -0
  193. package/src/server/preflight.ts +217 -0
  194. package/src/server/server.ts +327 -0
  195. package/src/signal-handler.ts +50 -0
  196. package/src/store/activity.ts +413 -0
  197. package/src/store/backfill-preflight.ts +49 -0
  198. package/src/store/backfill.ts +141 -0
  199. package/src/store/gc-preflight.ts +206 -0
  200. package/src/store/gc.ts +424 -0
  201. package/src/store/metrics-preflight.ts +229 -0
  202. package/src/store/metrics.ts +236 -0
  203. package/src/store/preflight.ts +748 -0
  204. package/src/store/store.ts +693 -0
  205. package/src/system-tools.ts +355 -0
  206. package/src/transport-registry.ts +1124 -0
  207. package/src/transports/claude-code-cli.ts +1348 -0
  208. package/src/transports/opencode-admission.ts +515 -0
  209. package/src/transports/opencode-client.ts +3328 -0
  210. package/src/transports/opencode-evidence.ts +557 -0
  211. package/src/transports/opencode-mcp.ts +248 -0
  212. package/src/transports/opencode-sdk.ts +2294 -0
  213. package/src/transports/opencode-server.ts +535 -0
  214. package/src/triage/adjudication.ts +113 -0
  215. package/src/triage/reply.ts +125 -0
  216. package/src/triage/triage.ts +255 -0
  217. package/src/ui/activity.ts +173 -0
  218. package/src/ui/config-edit.ts +816 -0
  219. package/src/ui/config.ts +462 -0
  220. package/src/ui/menu.ts +1325 -0
  221. package/src/ui/plan.ts +1039 -0
  222. package/src/ui/primitives.ts +300 -0
  223. package/src/ui/progress.ts +298 -0
  224. package/src/ui/result.ts +552 -0
  225. package/src/ui/review-menu.ts +312 -0
  226. package/src/ui/select.ts +528 -0
  227. package/src/ui/tree.ts +178 -0
  228. package/src/uninstaller.ts +479 -0
  229. package/src/updater.ts +836 -0
  230. package/src/usage.ts +77 -0
  231. package/src/watch/preflight.ts +1389 -0
  232. package/src/watch/watch.ts +1235 -0
  233. package/src/wizard.ts +877 -0
@@ -0,0 +1,2181 @@
1
+ // The pure error contract for the agent-first CI (odd/tasks/agent-first-ci.md,
2
+ // T2a / S2). Every failure pr-hero reports in action mode is classified into
3
+ // one ErrorClass, named by one stable ErrorCode, given an owner that says whose
4
+ // fix it is (your configuration, a provider, pr-hero itself, or unclassified:
5
+ // never a guess), and rendered as one workflow-command annotation plus a
6
+ // Markdown summary block.
7
+ //
8
+ // Consumers: test/ci/outcome.test.ts (now); the publisher and status mapping
9
+ // (T2b) and classify-error / CliError.cls (T2c) later. Every export is one of
10
+ // those. ERROR_CODES and ERROR_CATALOG are exported so the tests can walk every
11
+ // code and check the docs section against the catalog text.
12
+ //
13
+ // WHY ONLY BUILTINS: the action step that prints these errors runs BEFORE
14
+ // `bun install` (the same rule as src/ci/trigger.ts), so this module may import
15
+ // nothing but `node:` / `bun` builtins at runtime. Repository modules are
16
+ // imported with `import type` only: those are erased at transpile time and need
17
+ // no node_modules. test/ci/outcome.test.ts fails if a runtime import of a repo
18
+ // module appears here.
19
+ //
20
+ // The escape rule in escapeCommandData is a COPY of the one in
21
+ // src/ci/trigger.ts. That copy is private there, so it cannot be imported
22
+ // without widening trigger.ts; the drift test compares the two source texts.
23
+
24
+ import { commandHint, MARKER_OPEN, matchMarkerPrefix } from "../brand";
25
+ import type {
26
+ FailureCredential,
27
+ TransportFailureCause,
28
+ } from "../execution/contracts";
29
+ import type { CredentialProjectionFailureClass } from "../security/credential-broker";
30
+
31
+ export type Owner = "config" | "provider" | "pr-hero" | "unclassified";
32
+ export type OutcomeContext = "action" | "local";
33
+ // An owner is fixed, or depends on the context (PRH-RUNTIME-UNAVAILABLE).
34
+ type OwnerRule = Owner | Readonly<Record<OutcomeContext, Owner>>;
35
+
36
+ type CapabilityIssue =
37
+ | "binary_unresolved"
38
+ | "sdk_unavailable"
39
+ | "version_unsupported";
40
+ type RouteReason =
41
+ | "unmapped"
42
+ | "ambiguous"
43
+ | "spend-disabled"
44
+ | "multiple-opencode-providers";
45
+
46
+ export type ErrorClass =
47
+ | {
48
+ kind: "trigger";
49
+ check: "no-credential" | "routing-missing" | "pr-unresolved";
50
+ }
51
+ | {
52
+ kind: "config-parse";
53
+ source: "routing" | "repo-config" | "person-config" | "extra-hunters";
54
+ }
55
+ | { kind: "prompt-set" }
56
+ | { kind: "gotchas"; reason: "empty" | "placeholder" }
57
+ | { kind: "route"; reason: RouteReason }
58
+ | {
59
+ kind: "credential";
60
+ failureClass: CredentialProjectionFailureClass | "env-absent";
61
+ }
62
+ | { kind: "capability"; issue: CapabilityIssue }
63
+ | { kind: "transport"; cause: TransportFailureCause | "legacy_terminal" }
64
+ // `rateLimited` is the caller's reading of the response body: GitHub answers
65
+ // a spent rate limit with 403 or 429, and a refused permission with 403.
66
+ | { kind: "github"; status: number; rateLimited?: boolean }
67
+ | { kind: "install"; step: string }
68
+ | { kind: "invariant" }
69
+ | { kind: "unknown" };
70
+
71
+ type GithubClass = Extract<ErrorClass, { kind: "github" }>;
72
+
73
+ export const ERROR_CODES = [
74
+ "PRH-CRED-MISSING",
75
+ "PRH-CRED-UNUSABLE",
76
+ "PRH-CRED-REJECTED",
77
+ "PRH-ROUTING-MISSING",
78
+ "PRH-ROUTING-INVALID",
79
+ "PRH-ROUTE-UNRESOLVABLE",
80
+ "PRH-MODEL-UNAVAILABLE",
81
+ "PRH-PROMPTSET-INVALID",
82
+ "PRH-GOTCHAS-MISSING",
83
+ "PRH-CONFIG-INVALID",
84
+ "PRH-TOKEN-PERMISSION",
85
+ "PRH-GITHUB-TOKEN-INVALID",
86
+ "PRH-GITHUB-UNAVAILABLE",
87
+ "PRH-PR-UNRESOLVED",
88
+ "PRH-STATUS-WRITE-FAILED",
89
+ "PRH-RUNTIME-UNAVAILABLE",
90
+ "PRH-INSTALL-FAILED",
91
+ "PRH-PROVIDER-LIMITED",
92
+ "PRH-PROVIDER-UNAVAILABLE",
93
+ "PRH-PROVIDER-REFUSED",
94
+ "PRH-ENGINE-DEFECT",
95
+ "PRH-HUNTERS-FAILED",
96
+ "PRH-UNCLASSIFIED",
97
+ "PRH-CANCELLED",
98
+ ] as const;
99
+
100
+ export type ErrorCode = (typeof ERROR_CODES)[number];
101
+
102
+ interface CatalogVariant {
103
+ // Replaces the entry's `what` for this sub-class.
104
+ readonly what?: string;
105
+ // Replaces `what` when no model is given, so the sentence never names a placeholder
106
+ // (PRH-MODEL-UNAVAILABLE's every_hunter variant). Filled like `what`.
107
+ readonly whatWithoutModel?: string;
108
+ // Replaces the entry's owner for this sub-class.
109
+ readonly owner?: OwnerRule;
110
+ readonly why: string;
111
+ // A list of fix lines, or a function of the params when the steps depend on
112
+ // them (the backend: missing_subscription_record, and PRH-CRED-MISSING's
113
+ // routing variable).
114
+ readonly fixes:
115
+ | readonly string[]
116
+ | ((params: ErrorParams) => readonly string[]);
117
+ // The annotation's Fix: ONE short imperative sentence that names the real
118
+ // fixing step, with no trailing period. A string is filled like the other
119
+ // text; a function reads the params when one value picks the step.
120
+ readonly annotationFix: string | ((params: ErrorParams) => string);
121
+ }
122
+
123
+ // A fix line starting with "$ " is a command; any other line is prose. Each
124
+ // placeholder {name} is one ErrorParams key (see NEUTRAL below for the words
125
+ // used when a value is missing).
126
+ export interface CatalogEntry {
127
+ readonly level: "error" | "notice";
128
+ readonly owner: OwnerRule;
129
+ readonly headline?: string;
130
+ readonly lead?: string;
131
+ readonly providerName?: string;
132
+ readonly what: string;
133
+ // Replaces `what` when no step is given, so the sentence never names the
134
+ // placeholder ("The this step step failed"). Filled like `what`.
135
+ readonly whatWithoutStep?: string;
136
+ // "default" is always present. Keys "action" / "local" select by context
137
+ // (PRH-RUNTIME-UNAVAILABLE); other keys are the failure's sub-class
138
+ // (credential failureClass, route reason, GitHub status family), chosen by
139
+ // renderError or by the caller through renderCode.
140
+ readonly variants: Readonly<Record<string, CatalogVariant>>;
141
+ }
142
+
143
+ export interface ErrorParams {
144
+ backend?: string;
145
+ provider?: string;
146
+ step?: string;
147
+ secret?: string;
148
+ scope?: string;
149
+ pr?: number;
150
+ runId?: string;
151
+ runUrl?: string;
152
+ detail?: string;
153
+ // The model a provider does not serve, when the record names it (PRH-MODEL-UNAVAILABLE).
154
+ model?: string;
155
+ }
156
+
157
+ export interface RenderedError {
158
+ code: ErrorCode;
159
+ owner: Owner;
160
+ // The one sentence the owner lead introduces, filled and without the lead.
161
+ // The publisher uses it for the commit status description.
162
+ what: string;
163
+ annotation: string;
164
+ summary: string[];
165
+ }
166
+
167
+ // The record the trigger step writes to `trigger.json` in the outcome
168
+ // directory, and the publisher reads back (odd/tasks/agent-first-ci.md, T2b).
169
+ // It carries the decision, never a secret, a comment body or gh's own text.
170
+ export interface TriggerRecord {
171
+ v: 1;
172
+ decision:
173
+ | "review"
174
+ | "ignore"
175
+ | "denied"
176
+ | "unverifiable"
177
+ | "no-credentials"
178
+ | "override";
179
+ cls?: ErrorClass;
180
+ params: ErrorParams;
181
+ pr?: number;
182
+ head_sha?: string;
183
+ // Only for an override: the login that unlocked the gate (odd/tasks/agent-first-ci.md,
184
+ // S8). The override must name who acted, so an override without one is refused.
185
+ actor?: string;
186
+ repository: string;
187
+ run_id: string;
188
+ // The attempt of this run. gh run rerun keeps run_id for every attempt, so
189
+ // the attempt is what tells a re-run from the run it repeats. A record with
190
+ // no attempt was written before attempts were recorded: parseTriggerRecord
191
+ // reads it as attempt 1.
192
+ run_attempt: number;
193
+ run_url: string;
194
+ }
195
+
196
+ // The record the setup step writes to `setup.json` in the outcome directory when a
197
+ // routing or OpenCode auth input is malformed (odd/tasks/agent-first-ci.md, A1).
198
+ // The publisher reads it back, so the failure is named instead of reported as a
199
+ // generic install failure. `detail` is a fixed phrase per failure site that names
200
+ // the input which is wrong; it never carries that input's content.
201
+ export interface SetupRecord {
202
+ v: 1;
203
+ cls: ErrorClass;
204
+ detail: string;
205
+ }
206
+
207
+ // The record the CLI writes to `cli.json` in the outcome directory for its own
208
+ // terminal outcome (odd/tasks/agent-first-ci.md, T2c). The publisher reads it
209
+ // back, and no record at all means the CLI stopped before reporting. It never
210
+ // carries a secret, raw error text, a comment body or gh's output: `cls` names a
211
+ // class, never a message.
212
+ export const CLI_RECORD_FILE = "cli.json";
213
+ // SB3: the created_at GitHub returned for the CLI's own pending status, written once the
214
+ // pending landed. The cancel settle overwrites only the pending with exactly this time.
215
+ export const PENDING_AT_FILE = "pending-at";
216
+
217
+ // The URL of this run's attempt, or undefined outside GitHub Actions. The CLI's pending names
218
+ // it as its target_url, and the cancel settle compares a pending with it (SB3 follow-up), so
219
+ // the CLI and the publisher share this one builder: they cannot disagree on the URL. An attempt
220
+ // that is not a positive integer reads as the first attempt, as the trigger record writes it.
221
+ export function actionsRunUrl(
222
+ env: Readonly<Record<string, string | undefined>> = process.env,
223
+ ): string | undefined {
224
+ if (env.GITHUB_ACTIONS !== "true") return undefined;
225
+ const server = env.GITHUB_SERVER_URL ?? "";
226
+ const repository = env.GITHUB_REPOSITORY ?? "";
227
+ const runId = env.GITHUB_RUN_ID ?? "";
228
+ if (server === "" || repository === "" || runId === "") return undefined;
229
+ const attempt = /^[0-9]+$/.test(env.GITHUB_RUN_ATTEMPT ?? "")
230
+ ? Number(env.GITHUB_RUN_ATTEMPT)
231
+ : 0;
232
+ const first = attempt > 0 ? attempt : 1;
233
+ return `${server}/${repository}/actions/runs/${runId}/attempts/${first}`;
234
+ }
235
+
236
+ // The only classes the CLI writes (src/ci/classify-error.ts). A wider reader
237
+ // would hide a writer's bug, the same rule as parseRecordClass below. The config
238
+ // classes are the ones a throw site names (T2d-1). The person layer is not one of
239
+ // them: its catalog text names the repo file, so the record would send the reader
240
+ // to the wrong file.
241
+ export type CliErrorClass =
242
+ | { kind: "unknown" }
243
+ | { kind: "route"; reason: "unmapped" | "ambiguous" | "spend-disabled" }
244
+ | { kind: "capability"; issue: "sdk_unavailable" | "version_unsupported" }
245
+ | {
246
+ kind: "config-parse";
247
+ source: "routing" | "repo-config" | "extra-hunters";
248
+ }
249
+ | { kind: "prompt-set" }
250
+ | { kind: "gotchas"; reason: "empty" | "placeholder" }
251
+ | { kind: "invariant" };
252
+
253
+ // The final commit status a gate run could not write after its review was delivered.
254
+ // The publisher posts it once more on the record's head (see CliRecord.unsettled_status).
255
+ export interface UnsettledStatus {
256
+ state: "success" | "failure";
257
+ description: string;
258
+ }
259
+
260
+ // GitHub's limit on a commit status description. The publisher clips to it, and the
261
+ // record refuses a longer description, so the two cannot drift apart.
262
+ export const STATUS_DESCRIPTION_MAX = 140;
263
+
264
+ export interface CliRecord {
265
+ v: 1;
266
+ // "reviewing" is progress, not an outcome: the CLI took the pending lock on
267
+ // head_sha and has not reported one yet. Every outcome overwrites it, and the
268
+ // publisher reads it as the one case where the lock is this run's own.
269
+ outcome:
270
+ | "reviewing"
271
+ | "reviewed"
272
+ | "hunters-failed"
273
+ | "skipped"
274
+ | "yielded"
275
+ | "error";
276
+ // Only for outcome "skipped".
277
+ skip?: "size" | "budget" | "coverage" | "manual-required";
278
+ // The head the CLI reviewed or resolved, when it knows one. 40 lowercase hex.
279
+ // Required for "reviewing": the head the CLI is about to post its pending
280
+ // status on (the head it holds the review lock for).
281
+ head_sha?: string;
282
+ // Only for outcome "error".
283
+ cls?: CliErrorClass;
284
+ // Only for outcome "error", and the writer does not set it today.
285
+ params?: ErrorParams;
286
+ // Only for outcome "reviewed". The review was delivered, but the CLI's final status
287
+ // write on head_sha failed, so the head's required check is still pending. The
288
+ // publisher posts this status once more (src/ci/publish.ts), exactly as the CLI tried
289
+ // to write it.
290
+ unsettled_status?: UnsettledStatus;
291
+ // Only for outcome "reviewed", beside unsettled_status: the override cutoff, in ms, that the
292
+ // CLI computed for this run (overrideCutoffMs, src/ci/override.ts): the instant at or after
293
+ // which an override counts as posted during the run. The publisher compares with it as it is,
294
+ // and never re-derives it. Absent on a record without one, and then the publisher reposts as
295
+ // before.
296
+ override_cutoff_ms?: number;
297
+ // Only for outcome "hunters-failed": one entry per failed hunter step, in the order
298
+ // they settled, and never an empty list. Each entry names what its transport
299
+ // reported and the route it ran on, when it knows them. An entry with no cause is a
300
+ // failure the CLI did not classify, so the publisher keeps the generic code for it.
301
+ hunter_failures?: HunterFailureRecord[];
302
+ }
303
+
304
+ export interface HunterFailureRecord {
305
+ cause?: TransportFailureCause;
306
+ // The route's provider and model, as short safe strings (see safeProviderName).
307
+ provider?: string;
308
+ model?: string;
309
+ // One short line saying why the hunter failed, in the provider's words (see
310
+ // safeFailureDetail). Present only when the transport knew it.
311
+ detail?: string;
312
+ // The secret the hunter ran on (ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN), so a
313
+ // credential or quota failure can name which one to replace or top up.
314
+ credential?: FailureCredential;
315
+ }
316
+
317
+ // Every TransportFailureCause, as a runtime lookup the record reader can check a
318
+ // cause against. The `satisfies` clause fails tsc when the union gains or loses a
319
+ // cause this list does not match (the record reads the same vocabulary the transport
320
+ // writes). This file cannot import the runtime list from execution/contracts.
321
+ const TRANSPORT_CAUSE_LOOKUP = {
322
+ auth_invalid: true,
323
+ quota_exhausted: true,
324
+ rate_limit: true,
325
+ network_transient: true,
326
+ protocol_truncation: true,
327
+ protocol_mismatch: true,
328
+ protocol_overflow: true,
329
+ output_limit_exceeded: true,
330
+ context_window_exceeded: true,
331
+ safety_refusal: true,
332
+ provider_configuration_invalid: true,
333
+ model_unavailable: true,
334
+ missing_provider_record: true,
335
+ runtime_unavailable: true,
336
+ remote_abort_unconfirmed: true,
337
+ } satisfies Record<TransportFailureCause, true>;
338
+
339
+ // The cause when it is a transport cause, otherwise undefined.
340
+ export function knownTransportCause(
341
+ value: unknown,
342
+ ): TransportFailureCause | undefined {
343
+ return typeof value === "string" &&
344
+ Object.hasOwn(TRANSPORT_CAUSE_LOOKUP, value)
345
+ ? (value as TransportFailureCause)
346
+ : undefined;
347
+ }
348
+
349
+ // A provider name or a model name, as the record may carry it. Both are configuration
350
+ // the operator wrote, never provider text, but the record is a file the publisher
351
+ // reads back, so a value that could carry a control character or a path is refused.
352
+ const PROVIDER_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
353
+ const MODEL_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,95}$/;
354
+
355
+ export function safeProviderName(value: unknown): string | undefined {
356
+ return typeof value === "string" && PROVIDER_NAME_PATTERN.test(value)
357
+ ? value
358
+ : undefined;
359
+ }
360
+
361
+ export function safeModelName(value: unknown): string | undefined {
362
+ return typeof value === "string" && MODEL_NAME_PATTERN.test(value)
363
+ ? value
364
+ : undefined;
365
+ }
366
+
367
+ // Every FailureCredential, as a runtime lookup (tied to the union by `satisfies`, like the
368
+ // cause list above: this file cannot import the runtime list from execution/contracts).
369
+ const FAILURE_CREDENTIAL_LOOKUP = {
370
+ ANTHROPIC_API_KEY: true,
371
+ ANTHROPIC_AUTH_TOKEN: true,
372
+ CLAUDE_CODE_OAUTH_TOKEN: true,
373
+ } satisfies Record<FailureCredential, true>;
374
+
375
+ export function knownFailureCredential(
376
+ value: unknown,
377
+ ): FailureCredential | undefined {
378
+ return typeof value === "string" &&
379
+ Object.hasOwn(FAILURE_CREDENTIAL_LOOKUP, value)
380
+ ? (value as FailureCredential)
381
+ : undefined;
382
+ }
383
+
384
+ // A failure detail, as the record may carry it. Unlike a provider or model name it is the
385
+ // provider's own text, so the record accepts only one short line with no control
386
+ // characters: it is later placed in a commit status, an annotation and a comment. The
387
+ // writer (hunterFailureRecords) and the reader share this one check, and the cap matches
388
+ // the engine's failure reason (stepFailureReason).
389
+ const FAILURE_DETAIL_MAX = 160;
390
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the point is to refuse control characters
391
+ const FAILURE_DETAIL_PATTERN = /^[^\u0000-\u001f\u007f]+$/;
392
+
393
+ export function safeFailureDetail(value: unknown): string | undefined {
394
+ return typeof value === "string" &&
395
+ value.trim() === value &&
396
+ value.length <= FAILURE_DETAIL_MAX &&
397
+ FAILURE_DETAIL_PATTERN.test(value)
398
+ ? value
399
+ : undefined;
400
+ }
401
+
402
+ const TRIGGER_DECISIONS: readonly TriggerRecord["decision"][] = [
403
+ "review",
404
+ "ignore",
405
+ "denied",
406
+ "unverifiable",
407
+ "no-credentials",
408
+ "override",
409
+ ];
410
+ // A GitHub login, with the bound and characters of the trigger's check (GITHUB_LOGIN in
411
+ // src/ci/trigger.ts), including the 91-character limit that keeps the override's status
412
+ // description within GitHub's 140. A copy, not an import: this file and trigger.ts may
413
+ // import builtins only at runtime (see the header of src/ci/trigger.ts), and
414
+ // test/ci/outcome.test.ts fails if the two texts differ.
415
+ const LOGIN_PATTERN = /^(?=.{1,91}$)[A-Za-z0-9][A-Za-z0-9_-]{0,90}(\[bot\])?$/;
416
+ const RECORD_PARAM_KEYS: readonly string[] = [
417
+ "backend",
418
+ "provider",
419
+ "step",
420
+ "secret",
421
+ "scope",
422
+ "runId",
423
+ "runUrl",
424
+ "detail",
425
+ ];
426
+ const SHA_PATTERN = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
427
+
428
+ function isRecordObject(value: unknown): value is Record<string, unknown> {
429
+ return typeof value === "object" && value !== null && !Array.isArray(value);
430
+ }
431
+
432
+ function isPositiveInteger(value: unknown): value is number {
433
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
434
+ }
435
+
436
+ function parseRecordParams(value: unknown): ErrorParams | undefined {
437
+ if (!isRecordObject(value)) return undefined;
438
+ const params: Record<string, string | number> = {};
439
+ for (const [key, field] of Object.entries(value)) {
440
+ if (key === "pr") {
441
+ if (!isPositiveInteger(field)) return undefined;
442
+ params.pr = field;
443
+ } else if (RECORD_PARAM_KEYS.includes(key) && typeof field === "string") {
444
+ params[key] = field;
445
+ } else {
446
+ return undefined;
447
+ }
448
+ }
449
+ return params as ErrorParams;
450
+ }
451
+
452
+ // The two classes the setup step writes, and no others: a wider reader would hide
453
+ // a writer's bug, the same rule as parseRecordClass below.
454
+ function parseSetupClass(value: unknown): ErrorClass | undefined {
455
+ if (!isRecordObject(value)) return undefined;
456
+ if (value.kind === "config-parse" && value.source === "routing") {
457
+ return { kind: "config-parse", source: "routing" };
458
+ }
459
+ if (
460
+ value.kind === "credential" &&
461
+ value.failureClass === "malformed_payload"
462
+ ) {
463
+ return { kind: "credential", failureClass: "malformed_payload" };
464
+ }
465
+ return undefined;
466
+ }
467
+
468
+ // Returns undefined for anything the publisher must not act on. The publisher
469
+ // then reports the generic install failure, with a warning that says why.
470
+ export function parseSetupRecord(text: string): SetupRecord | undefined {
471
+ let value: unknown;
472
+ try {
473
+ value = JSON.parse(text);
474
+ } catch {
475
+ return undefined;
476
+ }
477
+ if (!isRecordObject(value) || value.v !== 1) return undefined;
478
+ const cls = parseSetupClass(value.cls);
479
+ if (cls === undefined) return undefined;
480
+ if (typeof value.detail !== "string" || value.detail.trim() === "") {
481
+ return undefined;
482
+ }
483
+ return { v: 1, cls, detail: value.detail };
484
+ }
485
+
486
+ // The classes the trigger writes. Any other kind is refused: the record is a
487
+ // contract between two modules, and a wider reader would hide a writer's bug.
488
+ // The trigger's writer type (RecordClass in src/ci/trigger.ts) allows exactly
489
+ // one trigger check, pr-unresolved. The other trigger checks are classes the
490
+ // publisher builds itself, so a record that names one is refused too.
491
+ function parseRecordClass(value: unknown): ErrorClass | undefined {
492
+ if (!isRecordObject(value)) return undefined;
493
+ if (value.kind === "unknown") return { kind: "unknown" };
494
+ if (value.kind === "trigger") {
495
+ return value.check === "pr-unresolved"
496
+ ? { kind: "trigger", check: "pr-unresolved" }
497
+ : undefined;
498
+ }
499
+ if (value.kind === "github") {
500
+ if (!Number.isInteger(value.status)) return undefined;
501
+ const status = value.status as number;
502
+ if (value.rateLimited === undefined) return { kind: "github", status };
503
+ return value.rateLimited === true
504
+ ? { kind: "github", status, rateLimited: true }
505
+ : undefined;
506
+ }
507
+ return undefined;
508
+ }
509
+
510
+ // Returns undefined for anything the publisher must not act on. A file that
511
+ // exists but fails here is an error for the publisher to report, never a
512
+ // silent skip: see runPublish in src/ci/publish.ts.
513
+ export function parseTriggerRecord(text: string): TriggerRecord | undefined {
514
+ let value: unknown;
515
+ try {
516
+ value = JSON.parse(text);
517
+ } catch {
518
+ return undefined;
519
+ }
520
+ if (!isRecordObject(value) || value.v !== 1) return undefined;
521
+ const decision = TRIGGER_DECISIONS.find(
522
+ (candidate) => candidate === value.decision,
523
+ );
524
+ const params = parseRecordParams(value.params);
525
+ if (decision === undefined || params === undefined) return undefined;
526
+ if (
527
+ typeof value.repository !== "string" ||
528
+ !/^[^\s/]+\/[^\s/]+$/.test(value.repository) ||
529
+ typeof value.run_id !== "string" ||
530
+ !/^[0-9]+$/.test(value.run_id) ||
531
+ typeof value.run_url !== "string" ||
532
+ !/^\S+$/.test(value.run_url)
533
+ ) {
534
+ return undefined;
535
+ }
536
+ let runAttempt = 1;
537
+ if (value.run_attempt !== undefined) {
538
+ if (!isPositiveInteger(value.run_attempt)) return undefined;
539
+ runAttempt = value.run_attempt;
540
+ }
541
+ const record: TriggerRecord = {
542
+ v: 1,
543
+ decision,
544
+ params,
545
+ repository: value.repository,
546
+ run_id: value.run_id,
547
+ run_attempt: runAttempt,
548
+ run_url: value.run_url,
549
+ };
550
+ if (value.pr !== undefined) {
551
+ if (!isPositiveInteger(value.pr)) return undefined;
552
+ record.pr = value.pr;
553
+ }
554
+ if (value.head_sha !== undefined) {
555
+ if (
556
+ typeof value.head_sha !== "string" ||
557
+ !SHA_PATTERN.test(value.head_sha)
558
+ ) {
559
+ return undefined;
560
+ }
561
+ record.head_sha = value.head_sha;
562
+ }
563
+ if (value.cls !== undefined) {
564
+ const cls = parseRecordClass(value.cls);
565
+ if (cls === undefined) return undefined;
566
+ record.cls = cls;
567
+ }
568
+ // WHY fail closed here: an override names who unlocked the gate, and the
569
+ // publisher posts both the status and that name from this record. A record
570
+ // without a valid actor or without its PR is refused, and an actor on any
571
+ // other decision is refused, because the writer produces neither.
572
+ if (decision === "override") {
573
+ if (
574
+ typeof value.actor !== "string" ||
575
+ !LOGIN_PATTERN.test(value.actor) ||
576
+ record.pr === undefined
577
+ ) {
578
+ return undefined;
579
+ }
580
+ record.actor = value.actor;
581
+ } else if (value.actor !== undefined) {
582
+ return undefined;
583
+ }
584
+ return record;
585
+ }
586
+
587
+ const CLI_OUTCOMES: readonly CliRecord["outcome"][] = [
588
+ "reviewing",
589
+ "reviewed",
590
+ "hunters-failed",
591
+ "skipped",
592
+ "yielded",
593
+ "error",
594
+ ];
595
+ const CLI_SKIPS: readonly NonNullable<CliRecord["skip"]>[] = [
596
+ "size",
597
+ "budget",
598
+ "coverage",
599
+ "manual-required",
600
+ ];
601
+ const CLI_HEAD_PATTERN = /^[0-9a-f]{40}$/;
602
+
603
+ // The CLI's own classes, and only those. A record naming any other class is
604
+ // refused, because the writer can produce no other.
605
+ function parseCliClass(value: unknown): CliErrorClass | undefined {
606
+ if (!isRecordObject(value)) return undefined;
607
+ if (value.kind === "unknown") return { kind: "unknown" };
608
+ if (value.kind === "route") {
609
+ if (
610
+ value.reason === "unmapped" ||
611
+ value.reason === "ambiguous" ||
612
+ value.reason === "spend-disabled"
613
+ ) {
614
+ return { kind: "route", reason: value.reason };
615
+ }
616
+ return undefined;
617
+ }
618
+ if (value.kind === "capability") {
619
+ if (
620
+ value.issue === "sdk_unavailable" ||
621
+ value.issue === "version_unsupported"
622
+ ) {
623
+ return { kind: "capability", issue: value.issue };
624
+ }
625
+ }
626
+ if (value.kind === "config-parse") {
627
+ if (
628
+ value.source === "routing" ||
629
+ value.source === "repo-config" ||
630
+ value.source === "extra-hunters"
631
+ ) {
632
+ return { kind: "config-parse", source: value.source };
633
+ }
634
+ return undefined;
635
+ }
636
+ if (value.kind === "prompt-set") return { kind: "prompt-set" };
637
+ if (value.kind === "gotchas") {
638
+ if (value.reason === "empty" || value.reason === "placeholder") {
639
+ return { kind: "gotchas", reason: value.reason };
640
+ }
641
+ return undefined;
642
+ }
643
+ if (value.kind === "invariant") return { kind: "invariant" };
644
+ return undefined;
645
+ }
646
+
647
+ // The final status a delivered review could not write. A delivered review's status is
648
+ // success or failure, so the state is one of those two. The description is the text the
649
+ // publisher posts, so it must say something and fit GitHub's limit.
650
+ function parseUnsettledStatus(value: unknown): UnsettledStatus | undefined {
651
+ if (!isRecordObject(value)) return undefined;
652
+ const state = (["success", "failure"] as const).find(
653
+ (candidate) => candidate === value.state,
654
+ );
655
+ if (state === undefined) return undefined;
656
+ const description = value.description;
657
+ if (
658
+ typeof description !== "string" ||
659
+ description.trim() === "" ||
660
+ description.length > STATUS_DESCRIPTION_MAX
661
+ ) {
662
+ return undefined;
663
+ }
664
+ return { state, description };
665
+ }
666
+
667
+ // The per-hunter entries of a hunters-failed record. Each entry carries only the five
668
+ // keys, and each value is checked: a cause against the transport vocabulary, a provider
669
+ // and a model against their safe-string patterns, a detail as one short plain line, a
670
+ // credential against the two secret names. An empty list is refused, since the writer
671
+ // never writes one.
672
+ function parseHunterFailures(
673
+ value: unknown,
674
+ ): HunterFailureRecord[] | undefined {
675
+ if (!Array.isArray(value) || value.length === 0) return undefined;
676
+ const failures: HunterFailureRecord[] = [];
677
+ for (const entry of value) {
678
+ if (!isRecordObject(entry)) return undefined;
679
+ const failure: HunterFailureRecord = {};
680
+ for (const [key, field] of Object.entries(entry)) {
681
+ if (key === "cause") {
682
+ const cause = knownTransportCause(field);
683
+ if (cause === undefined) return undefined;
684
+ failure.cause = cause;
685
+ } else if (key === "provider") {
686
+ const provider = safeProviderName(field);
687
+ if (provider === undefined) return undefined;
688
+ failure.provider = provider;
689
+ } else if (key === "model") {
690
+ const model = safeModelName(field);
691
+ if (model === undefined) return undefined;
692
+ failure.model = model;
693
+ } else if (key === "detail") {
694
+ const detail = safeFailureDetail(field);
695
+ if (detail === undefined) return undefined;
696
+ failure.detail = detail;
697
+ } else if (key === "credential") {
698
+ const credential = knownFailureCredential(field);
699
+ if (credential === undefined) return undefined;
700
+ failure.credential = credential;
701
+ } else {
702
+ return undefined;
703
+ }
704
+ }
705
+ failures.push(failure);
706
+ }
707
+ return failures;
708
+ }
709
+
710
+ // Returns undefined for anything the publisher must not act on. The rules mirror
711
+ // the writer's: `skip` is present exactly for a skipped outcome, `cls` exactly
712
+ // for an error, `params` only for an error, carrying only the keys a record
713
+ // may name, `unsettled_status` only for a reviewed outcome, and `head_sha` is
714
+ // required for a reviewing record, which names the lock's head and nothing else.
715
+ // The publisher reads this shape, so a looser reader would accept a record the
716
+ // writer never produces.
717
+ export function parseCliRecord(text: string): CliRecord | undefined {
718
+ let value: unknown;
719
+ try {
720
+ value = JSON.parse(text);
721
+ } catch {
722
+ return undefined;
723
+ }
724
+ if (!isRecordObject(value) || value.v !== 1) return undefined;
725
+ const outcome = CLI_OUTCOMES.find((candidate) => candidate === value.outcome);
726
+ if (outcome === undefined) return undefined;
727
+ const record: CliRecord = { v: 1, outcome };
728
+ if (outcome === "skipped") {
729
+ const skip = CLI_SKIPS.find((candidate) => candidate === value.skip);
730
+ if (skip === undefined) return undefined;
731
+ record.skip = skip;
732
+ } else if (value.skip !== undefined) {
733
+ return undefined;
734
+ }
735
+ if (value.head_sha !== undefined) {
736
+ if (
737
+ typeof value.head_sha !== "string" ||
738
+ !CLI_HEAD_PATTERN.test(value.head_sha)
739
+ ) {
740
+ return undefined;
741
+ }
742
+ record.head_sha = value.head_sha;
743
+ }
744
+ if (outcome === "reviewing" && record.head_sha === undefined) {
745
+ return undefined;
746
+ }
747
+ if (outcome === "error") {
748
+ const cls = parseCliClass(value.cls);
749
+ if (cls === undefined) return undefined;
750
+ record.cls = cls;
751
+ } else if (value.cls !== undefined) {
752
+ return undefined;
753
+ }
754
+ if (value.params !== undefined) {
755
+ if (outcome !== "error") return undefined;
756
+ const params = parseRecordParams(value.params);
757
+ if (params === undefined) return undefined;
758
+ record.params = params;
759
+ }
760
+ if (value.unsettled_status !== undefined) {
761
+ if (outcome !== "reviewed") return undefined;
762
+ const unsettled = parseUnsettledStatus(value.unsettled_status);
763
+ if (unsettled === undefined) return undefined;
764
+ record.unsettled_status = unsettled;
765
+ }
766
+ if (value.hunter_failures !== undefined) {
767
+ if (outcome !== "hunters-failed") return undefined;
768
+ const failures = parseHunterFailures(value.hunter_failures);
769
+ if (failures === undefined) return undefined;
770
+ record.hunter_failures = failures;
771
+ }
772
+ if (value.override_cutoff_ms !== undefined) {
773
+ if (outcome !== "reviewed") return undefined;
774
+ const cutoff = value.override_cutoff_ms;
775
+ if (typeof cutoff !== "number" || !Number.isSafeInteger(cutoff)) {
776
+ return undefined;
777
+ }
778
+ if (cutoff <= 0) return undefined;
779
+ record.override_cutoff_ms = cutoff;
780
+ }
781
+ return record;
782
+ }
783
+
784
+ // A switch over a closed union ends in `unmapped(value, fallback)`. A new
785
+ // member fails to compile at that call (the `never` argument), and a value
786
+ // outside the union at runtime still gets the honest fallback, never a
787
+ // guessed owner.
788
+ function unmapped<T>(_value: never, fallback: T): T {
789
+ return fallback;
790
+ }
791
+
792
+ export function codeOf(cls: ErrorClass): ErrorCode {
793
+ switch (cls.kind) {
794
+ case "trigger":
795
+ switch (cls.check) {
796
+ case "no-credential":
797
+ return "PRH-CRED-MISSING";
798
+ case "routing-missing":
799
+ return "PRH-ROUTING-MISSING";
800
+ case "pr-unresolved":
801
+ return "PRH-PR-UNRESOLVED";
802
+ default:
803
+ return unmapped(cls.check, "PRH-UNCLASSIFIED");
804
+ }
805
+ case "config-parse":
806
+ switch (cls.source) {
807
+ case "routing":
808
+ return "PRH-ROUTING-INVALID";
809
+ case "repo-config":
810
+ case "person-config":
811
+ return "PRH-CONFIG-INVALID";
812
+ case "extra-hunters":
813
+ return "PRH-PROMPTSET-INVALID";
814
+ default:
815
+ return unmapped(cls.source, "PRH-UNCLASSIFIED");
816
+ }
817
+ case "prompt-set":
818
+ return "PRH-PROMPTSET-INVALID";
819
+ // `reason` is captured in a local: it is a discriminant shared by the
820
+ // gotchas and route members, so narrowing on `cls.reason` in the inner
821
+ // default would collapse `cls` itself to never.
822
+ case "gotchas": {
823
+ const reason = cls.reason;
824
+ switch (reason) {
825
+ case "empty":
826
+ case "placeholder":
827
+ return "PRH-GOTCHAS-MISSING";
828
+ default:
829
+ return unmapped(reason, "PRH-UNCLASSIFIED");
830
+ }
831
+ }
832
+ case "route": {
833
+ const reason = cls.reason;
834
+ switch (reason) {
835
+ case "unmapped":
836
+ case "ambiguous":
837
+ case "spend-disabled":
838
+ case "multiple-opencode-providers":
839
+ return "PRH-ROUTE-UNRESOLVABLE";
840
+ default:
841
+ return unmapped(reason, "PRH-UNCLASSIFIED");
842
+ }
843
+ }
844
+ case "credential":
845
+ switch (cls.failureClass) {
846
+ case "missing_provider_record":
847
+ case "missing_subscription_record":
848
+ case "malformed_payload":
849
+ case "source_read_failed":
850
+ case "env-absent":
851
+ return "PRH-CRED-UNUSABLE";
852
+ case "unsupported_kind":
853
+ case "projection_layout_invalid":
854
+ return "PRH-ENGINE-DEFECT";
855
+ default:
856
+ return unmapped(cls.failureClass, "PRH-UNCLASSIFIED");
857
+ }
858
+ case "capability":
859
+ switch (cls.issue) {
860
+ case "binary_unresolved":
861
+ case "sdk_unavailable":
862
+ case "version_unsupported":
863
+ return "PRH-RUNTIME-UNAVAILABLE";
864
+ default:
865
+ return unmapped(cls.issue, "PRH-UNCLASSIFIED");
866
+ }
867
+ case "transport":
868
+ return transportCode(cls.cause);
869
+ case "github":
870
+ return githubCode(cls);
871
+ case "install":
872
+ return "PRH-INSTALL-FAILED";
873
+ case "invariant":
874
+ return "PRH-ENGINE-DEFECT";
875
+ case "unknown":
876
+ return "PRH-UNCLASSIFIED";
877
+ default:
878
+ return unmapped(cls, "PRH-UNCLASSIFIED");
879
+ }
880
+ }
881
+
882
+ // WHY a 403 splits on `rateLimited`: GitHub answers a refused permission and a
883
+ // spent rate limit with the same status, and only the caller reads the body. A
884
+ // 403 without the flag is a permission problem. A 429 is always a rate limit.
885
+ // A status outside the mapped families is unclassified, never an outage.
886
+ function githubCode(cls: GithubClass): ErrorCode {
887
+ if (cls.status === 401) return "PRH-GITHUB-TOKEN-INVALID";
888
+ if (cls.status === 403) {
889
+ return cls.rateLimited === true
890
+ ? "PRH-GITHUB-UNAVAILABLE"
891
+ : "PRH-TOKEN-PERMISSION";
892
+ }
893
+ if (cls.status === 429 || cls.status >= 500) return "PRH-GITHUB-UNAVAILABLE";
894
+ return "PRH-UNCLASSIFIED";
895
+ }
896
+
897
+ function transportCode(
898
+ cause: TransportFailureCause | "legacy_terminal",
899
+ ): ErrorCode {
900
+ switch (cause) {
901
+ case "auth_invalid":
902
+ return "PRH-CRED-REJECTED";
903
+ case "quota_exhausted":
904
+ case "rate_limit":
905
+ return "PRH-PROVIDER-LIMITED";
906
+ case "network_transient":
907
+ case "remote_abort_unconfirmed":
908
+ return "PRH-PROVIDER-UNAVAILABLE";
909
+ case "safety_refusal":
910
+ return "PRH-PROVIDER-REFUSED";
911
+ case "provider_configuration_invalid":
912
+ case "model_unavailable":
913
+ return "PRH-MODEL-UNAVAILABLE";
914
+ case "missing_provider_record":
915
+ return "PRH-CRED-UNUSABLE";
916
+ case "protocol_truncation":
917
+ case "protocol_mismatch":
918
+ case "protocol_overflow":
919
+ case "output_limit_exceeded":
920
+ case "context_window_exceeded":
921
+ return "PRH-ENGINE-DEFECT";
922
+ // WHY runtime_unavailable is unclassified, not an engine defect: one cause
923
+ // covers failures with different owners. OpenCodeSdkTransport raises it
924
+ // from classifyFailure for a provider refusal the provider marked not
925
+ // retryable (the MARKER_PROVIDER_REFUSAL branch in
926
+ // src/transports/opencode-sdk.ts). The same cause also covers pr-hero's own
927
+ // permission control failing (MARKER_PERMISSION_REJECT_FAILED) and a
928
+ // session or prompt that failed (MARKER_SESSION_CREATE, MARKER_PROMPT_REFUSED).
929
+ // ClaudeCodeCliTransport raises it when the child process cannot spawn
930
+ // (src/transports/claude-code-cli.ts). Naming one owner would be the guess
931
+ // this contract exists to prevent.
932
+ case "runtime_unavailable":
933
+ case "legacy_terminal":
934
+ return "PRH-UNCLASSIFIED";
935
+ default:
936
+ return unmapped(cause, "PRH-UNCLASSIFIED");
937
+ }
938
+ }
939
+
940
+ export function ownerOf(cls: ErrorClass, ctx: OutcomeContext): Owner {
941
+ switch (cls.kind) {
942
+ case "trigger":
943
+ switch (cls.check) {
944
+ case "no-credential":
945
+ case "routing-missing":
946
+ case "pr-unresolved":
947
+ return "config";
948
+ default:
949
+ return unmapped(cls.check, "unclassified");
950
+ }
951
+ case "config-parse":
952
+ switch (cls.source) {
953
+ case "routing":
954
+ case "repo-config":
955
+ case "person-config":
956
+ case "extra-hunters":
957
+ return "config";
958
+ default:
959
+ return unmapped(cls.source, "unclassified");
960
+ }
961
+ case "prompt-set":
962
+ case "gotchas":
963
+ case "route":
964
+ return "config";
965
+ case "credential":
966
+ switch (cls.failureClass) {
967
+ case "missing_provider_record":
968
+ case "missing_subscription_record":
969
+ case "malformed_payload":
970
+ case "source_read_failed":
971
+ case "env-absent":
972
+ return "config";
973
+ case "unsupported_kind":
974
+ case "projection_layout_invalid":
975
+ return "pr-hero";
976
+ default:
977
+ return unmapped(cls.failureClass, "unclassified");
978
+ }
979
+ case "capability":
980
+ switch (cls.issue) {
981
+ case "binary_unresolved":
982
+ case "sdk_unavailable":
983
+ case "version_unsupported":
984
+ // pr-hero installs these runtimes in the action; locally a tool is
985
+ // missing from the user's own environment.
986
+ return ctx === "action" ? "pr-hero" : "config";
987
+ default:
988
+ return unmapped(cls.issue, "unclassified");
989
+ }
990
+ case "transport":
991
+ return transportOwner(cls.cause);
992
+ case "github":
993
+ return githubOwner(cls);
994
+ case "install":
995
+ return "unclassified";
996
+ case "invariant":
997
+ return "pr-hero";
998
+ case "unknown":
999
+ return "unclassified";
1000
+ default:
1001
+ return unmapped(cls, "unclassified");
1002
+ }
1003
+ }
1004
+
1005
+ function githubOwner(cls: GithubClass): Owner {
1006
+ switch (githubCode(cls)) {
1007
+ case "PRH-TOKEN-PERMISSION":
1008
+ case "PRH-GITHUB-TOKEN-INVALID":
1009
+ return "config";
1010
+ case "PRH-GITHUB-UNAVAILABLE":
1011
+ return "provider";
1012
+ default:
1013
+ return "unclassified";
1014
+ }
1015
+ }
1016
+
1017
+ function transportOwner(
1018
+ cause: TransportFailureCause | "legacy_terminal",
1019
+ ): Owner {
1020
+ switch (cause) {
1021
+ // WHY a rejected credential is the user's to fix: the provider refused the
1022
+ // secret the user configured, and only the user can replace it (S2, L12).
1023
+ case "auth_invalid":
1024
+ case "provider_configuration_invalid":
1025
+ // The auth store has no record for the route's provider: the user's secret is the
1026
+ // thing to fix, the same owner as the credential class with this failure.
1027
+ case "missing_provider_record":
1028
+ return "config";
1029
+ case "quota_exhausted":
1030
+ case "rate_limit":
1031
+ case "network_transient":
1032
+ case "remote_abort_unconfirmed":
1033
+ case "safety_refusal":
1034
+ case "model_unavailable":
1035
+ return "provider";
1036
+ case "protocol_truncation":
1037
+ case "protocol_mismatch":
1038
+ case "protocol_overflow":
1039
+ case "output_limit_exceeded":
1040
+ case "context_window_exceeded":
1041
+ return "pr-hero";
1042
+ // See transportCode: runtime_unavailable has no single owner.
1043
+ case "runtime_unavailable":
1044
+ case "legacy_terminal":
1045
+ return "unclassified";
1046
+ default:
1047
+ return unmapped(cause, "unclassified");
1048
+ }
1049
+ }
1050
+
1051
+ export function ownerLead(owner: Owner, provider?: string): string {
1052
+ switch (owner) {
1053
+ case "config":
1054
+ return "Your configuration:";
1055
+ case "provider": {
1056
+ const name = provider?.trim();
1057
+ return name ? `Provider ${name}:` : "Provider:";
1058
+ }
1059
+ case "pr-hero":
1060
+ return "Crysk defect:";
1061
+ case "unclassified":
1062
+ return "Unclassified:";
1063
+ default:
1064
+ return unmapped(owner, "Unclassified:");
1065
+ }
1066
+ }
1067
+
1068
+ // The words a missing value renders as. Identifiers use angle placeholders so a
1069
+ // command that cannot be filled is visibly unfinished; prose uses plain words.
1070
+ const NEUTRAL: Record<keyof ErrorParams, string> = {
1071
+ backend: "<backend>",
1072
+ provider: "<provider>",
1073
+ step: "this step",
1074
+ secret: "<secret-name>",
1075
+ scope: "<scope>",
1076
+ pr: "<pr>",
1077
+ runId: "<run-id>",
1078
+ runUrl: "<run-url>",
1079
+ detail: "no further detail",
1080
+ model: "<model>",
1081
+ };
1082
+
1083
+ // The human phrase a failure's detail renders as. A raw identifier never reaches
1084
+ // an annotation or summary. Each table is typed over its whole union, so a new
1085
+ // member fails `tsc` here instead of leaking its name into user-facing text.
1086
+ const CREDENTIAL_PHRASE: Record<
1087
+ CredentialProjectionFailureClass | "env-absent",
1088
+ string
1089
+ > = {
1090
+ unsupported_kind:
1091
+ "this credential kind is not supported by this Crysk version",
1092
+ projection_layout_invalid: "the credential layout Crysk built is invalid",
1093
+ source_read_failed: "the credential store could not be read",
1094
+ malformed_payload: "the auth store is not a JSON object",
1095
+ // Raised for a Claude keychain record and for an OpenAI OAuth record alike.
1096
+ missing_subscription_record:
1097
+ "the expected subscription login is missing or of the wrong kind",
1098
+ missing_provider_record:
1099
+ "the OpenCode auth store has no entry for this provider",
1100
+ "env-absent": "the secret is not set",
1101
+ };
1102
+
1103
+ const CAPABILITY_PHRASE: Record<CapabilityIssue, string> = {
1104
+ binary_unresolved: "a required program is not installed",
1105
+ sdk_unavailable: "the OpenCode SDK is not installed",
1106
+ version_unsupported: "an unsupported OpenCode version is installed",
1107
+ };
1108
+
1109
+ const ROUTE_PHRASE: Record<RouteReason, string> = {
1110
+ unmapped: "no mapping covers this route",
1111
+ ambiguous: "more than one mapping matches this route",
1112
+ "spend-disabled": "spend is turned off for this route",
1113
+ "multiple-opencode-providers":
1114
+ "more than one OpenCode provider is configured",
1115
+ };
1116
+
1117
+ const TRANSPORT_PHRASE: Record<
1118
+ TransportFailureCause | "legacy_terminal",
1119
+ string
1120
+ > = {
1121
+ auth_invalid: "the provider rejected the credential",
1122
+ quota_exhausted: "the provider's quota is used up",
1123
+ rate_limit: "the provider rate-limited the request",
1124
+ network_transient: "the network failed before the provider answered",
1125
+ remote_abort_unconfirmed: "the remote abort could not be confirmed",
1126
+ safety_refusal: "the provider's safety system declined the input",
1127
+ provider_configuration_invalid: "the provider configuration is invalid",
1128
+ model_unavailable: "the provider does not serve the configured model",
1129
+ missing_provider_record:
1130
+ "the OpenCode auth store has no entry for this provider",
1131
+ protocol_truncation: "the reply was cut short",
1132
+ protocol_mismatch: "the reply did not match the expected protocol",
1133
+ protocol_overflow: "the reply overflowed the protocol limit",
1134
+ output_limit_exceeded: "the output exceeded its limit",
1135
+ context_window_exceeded: "the input exceeded the model's context window",
1136
+ runtime_unavailable: "the agent runtime was unavailable",
1137
+ legacy_terminal: "the run ended in a state Crysk no longer produces",
1138
+ };
1139
+
1140
+ const DOCS_BASE =
1141
+ "https://github.com/cryskai/crysk/blob/v0/docs/github-actions.md#";
1142
+
1143
+ const ENGINE_DEFECT_ISSUE =
1144
+ 'gh issue create -R cryskai/crysk --title "PRH-ENGINE-DEFECT {detail}" --body "{runUrl}"';
1145
+ const RERUN_FAILED = "$ gh run rerun {runId} --failed";
1146
+ const REVIEW_AGAIN = '$ gh pr comment {pr} --body "/crysk review"';
1147
+ // A workflow set up before the rename filters only `/pr-hero`, and the
1148
+ // floating action tag still delivers this text to it.
1149
+ const LEGACY_REVIEW_NOTE =
1150
+ "On a workflow set up before the rename, comment `/pr-hero review` instead.";
1151
+ const OPENCODE_STORE =
1152
+ "$ gh secret set OPENCODE_AUTH_JSON < ~/.local/share/opencode/auth.json";
1153
+ const CRED_STORE_WHY =
1154
+ "the credential store does not hold what this route needs";
1155
+ // missing_subscription_record is raised for a Claude keychain record and for an
1156
+ // OpenAI OAuth record alike, so each route's fix names the login it really uses.
1157
+ const CLAUDE_SUBSCRIPTION_FIXES = [
1158
+ "Log in again with `claude setup-token`, then set `CLAUDE_CODE_OAUTH_TOKEN`:",
1159
+ "$ claude setup-token && gh secret set CLAUDE_CODE_OAUTH_TOKEN",
1160
+ ];
1161
+ const OPENCODE_SUBSCRIPTION_FIXES = [
1162
+ "Provider `openai` expects a ChatGPT login: run `opencode auth login` and choose ChatGPT, then re-set the secret:",
1163
+ "$ opencode auth login",
1164
+ OPENCODE_STORE,
1165
+ "Or rename the provider in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename).",
1166
+ ];
1167
+ // Only the OpenCode route stores a ChatGPT login; any other backend, or none, is
1168
+ // the Claude route.
1169
+ function isOpencodeRoute(params: ErrorParams): boolean {
1170
+ return params.backend?.trim() === "opencode";
1171
+ }
1172
+ const MODEL_NOT_SERVED: CatalogVariant = {
1173
+ why: "the routing names a model this provider does not offer",
1174
+ fixes: [
1175
+ "Fix the `modelSnapshot` for this step in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename).",
1176
+ "List the models this provider serves:",
1177
+ "$ opencode models {provider}",
1178
+ ],
1179
+ annotationFix:
1180
+ "fix the `modelSnapshot` for {step} in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename) to a model that {provider} serves",
1181
+ };
1182
+
1183
+ const ROUTE_WHY = "every agent needs exactly one backend, provider and model";
1184
+ const PROVIDER_REFUSED_WHY = "the provider's safety system declined this input";
1185
+ const UNCLASSIFIED_FIXES = [
1186
+ "Re-run the failed jobs:",
1187
+ RERUN_FAILED,
1188
+ "If it repeats, read the log and report it:",
1189
+ "$ gh run view {runId} --log-failed",
1190
+ ] as const;
1191
+ const UNCLASSIFIED_FIX =
1192
+ "re-run the failed jobs with `gh run rerun {runId} --failed`";
1193
+ // The GitHub Actions expression is spliced in from two literals so the source
1194
+ // never holds a `${` pair that reads as a template placeholder here.
1195
+ const GITHUB_TOKEN_INPUT = "github-token: $" + "{{ secrets.GITHUB_TOKEN }}";
1196
+ // The `with:` line that hands the Claude secret to the action, spliced the same way.
1197
+ const CLAUDE_TOKEN_INPUT =
1198
+ "claude-token: $" + "{{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}";
1199
+ // The `with:` line that hands the OpenCode auth store to the action, spliced the same way.
1200
+ const OPENCODE_AUTH_INPUT =
1201
+ "opencode-auth: $" + "{{ secrets.OPENCODE_AUTH_JSON }}";
1202
+ // The `with:` line for the Claude API key, the alternative to the OAuth token.
1203
+ const ANTHROPIC_API_KEY_INPUT =
1204
+ "anthropic-api-key: $" + "{{ secrets.ANTHROPIC_API_KEY }}";
1205
+ // The fix for a missing credential, by route. A Claude route names only the Claude
1206
+ // secrets. An OpenCode route leads with the OpenCode secret, and names the Claude
1207
+ // token only as the route it does not use (odd/tasks/agent-first-ci.md, A5).
1208
+ const CLAUDE_CREDENTIAL_FIXES = [
1209
+ "Set one credential for the route you use:",
1210
+ "$ claude setup-token && gh secret set CLAUDE_CODE_OAUTH_TOKEN",
1211
+ "$ gh secret set ANTHROPIC_API_KEY",
1212
+ "$ opencode auth login && gh secret set OPENCODE_AUTH_JSON < ~/.local/share/opencode/auth.json",
1213
+ `If the secret is already set, check that the workflow passes it to the action under \`with:\`, for example \`${CLAUDE_TOKEN_INPUT}\` or \`${ANTHROPIC_API_KEY_INPUT}\`: a secret the workflow does not pass never reaches Crysk.`,
1214
+ "Dependabot PRs read Dependabot secrets, so set this one too:",
1215
+ "$ gh secret set --app dependabot CLAUDE_CODE_OAUTH_TOKEN",
1216
+ "Then re-run the workflow:",
1217
+ "$ gh run rerun {runId}",
1218
+ ] as const;
1219
+ // A workflow scaffolded before the rename to Crysk passes only
1220
+ // vars.PRHERO_ROUTING to the action, so a fix that names CRYSK_ROUTING alone
1221
+ // would send its owner to set a variable nothing reads.
1222
+ const LEGACY_ROUTING_NOTE =
1223
+ "A workflow set up before the rename reads PRHERO_ROUTING instead: set that one, or run `crysk ci init --force` so the workflow also reads CRYSK_ROUTING.";
1224
+ const OPENCODE_CREDENTIAL_FIXES = [
1225
+ "Set the OpenCode credential for the route you use:",
1226
+ "$ opencode auth login && gh secret set OPENCODE_AUTH_JSON < ~/.local/share/opencode/auth.json",
1227
+ `If the secret is already set, check that the workflow passes it to the action under \`with:\`, for example \`${OPENCODE_AUTH_INPUT}\`: a secret the workflow does not pass never reaches Crysk.`,
1228
+ "An OpenCode route also needs the routing variable:",
1229
+ "$ gh variable set CRYSK_ROUTING --body '<routing-object-json>'",
1230
+ LEGACY_ROUTING_NOTE,
1231
+ "Dependabot PRs read Dependabot secrets, so set this one too:",
1232
+ "$ gh secret set --app dependabot OPENCODE_AUTH_JSON < ~/.local/share/opencode/auth.json",
1233
+ "A Claude route uses `CLAUDE_CODE_OAUTH_TOKEN` instead, from `claude setup-token`.",
1234
+ "Then re-run the workflow:",
1235
+ "$ gh run rerun {runId}",
1236
+ ] as const;
1237
+
1238
+ function single(
1239
+ why: string,
1240
+ fixes: CatalogVariant["fixes"],
1241
+ annotationFix: CatalogVariant["annotationFix"],
1242
+ ): Readonly<Record<string, CatalogVariant>> {
1243
+ return { default: { why, fixes, annotationFix } };
1244
+ }
1245
+
1246
+ const PROVIDER_LIMITED: CatalogVariant = {
1247
+ why: "the provider has throttled this account or key, so an immediate retry would fail the same way",
1248
+ fixes: [
1249
+ "Wait, or raise the quota, then ask for a new review:",
1250
+ REVIEW_AGAIN,
1251
+ LEGACY_REVIEW_NOTE,
1252
+ ],
1253
+ annotationFix: `wait for the limit to reset or raise the quota, then comment ${commandHint("/crysk review", "")} on the PR`,
1254
+ };
1255
+
1256
+ const CREDENTIAL_UNUSABLE_ENV: CatalogVariant = {
1257
+ why: CRED_STORE_WHY,
1258
+ fixes: ["Set the secret again:", "$ gh secret set {secret}"],
1259
+ annotationFix: "set the {secret} secret with `gh secret set {secret}`",
1260
+ };
1261
+
1262
+ // Two UnmappedRouteError throw sites (src/model/routing.ts) share this variant: a
1263
+ // model with no mapping at all, and a mapping that names no modelSnapshot. "Add or
1264
+ // complete" covers both; "add a modelSnapshot" alone was false for the first.
1265
+ const ROUTE_UNMAPPED: CatalogVariant = {
1266
+ why: ROUTE_WHY,
1267
+ fixes: [
1268
+ "Add or complete this model's route in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename), with an explicit `modelSnapshot`.",
1269
+ ],
1270
+ annotationFix:
1271
+ "add or complete this model's route in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename), with an explicit `modelSnapshot`",
1272
+ };
1273
+
1274
+ const RUNTIME_LOCAL: CatalogVariant = {
1275
+ why: "a required tool is missing from your environment",
1276
+ fixes: ["Reconcile the crysk install:", "$ crysk upgrade --reconcile"],
1277
+ annotationFix: "reconcile the crysk install with `crysk upgrade --reconcile`",
1278
+ };
1279
+
1280
+ const GITHUB_SERVER: CatalogVariant = {
1281
+ why: "the failure happened on GitHub's side, and a retry may succeed",
1282
+ fixes: ["Re-run the workflow:", "$ gh run rerun {runId}"],
1283
+ annotationFix: "re-run the workflow once GitHub is serving requests again",
1284
+ };
1285
+
1286
+ // WHY no class maps to PRH-STATUS-WRITE-FAILED, PRH-HUNTERS-FAILED or
1287
+ // PRH-CANCELLED: each is a condition the caller observes directly (a status
1288
+ // write, the hunter set, a superseded run), so the caller requests the code
1289
+ // through renderCode. The class-to-code table cannot see those conditions.
1290
+ export const ERROR_CATALOG: Readonly<Record<ErrorCode, CatalogEntry>> = {
1291
+ "PRH-CRED-MISSING": {
1292
+ level: "error",
1293
+ owner: "config",
1294
+ what: "No credential for the {backend} route reached the action",
1295
+ variants: single(
1296
+ "Crysk cannot authenticate, so it cannot review this PR",
1297
+ (params) =>
1298
+ isOpencodeRoute(params)
1299
+ ? OPENCODE_CREDENTIAL_FIXES
1300
+ : CLAUDE_CREDENTIAL_FIXES,
1301
+ (params) =>
1302
+ params.backend?.trim() === "opencode"
1303
+ ? "set the OPENCODE_AUTH_JSON secret: `gh secret set OPENCODE_AUTH_JSON < ~/.local/share/opencode/auth.json`"
1304
+ : "set a Claude credential: `claude setup-token && gh secret set CLAUDE_CODE_OAUTH_TOKEN`",
1305
+ ),
1306
+ },
1307
+ "PRH-CRED-UNUSABLE": {
1308
+ level: "error",
1309
+ owner: "config",
1310
+ what: "The {backend}/{provider} route for {step} has no usable credential ({detail})",
1311
+ variants: {
1312
+ // WHY the model is named when the run knows it: the hunter record carries the route's
1313
+ // provider and model, and "route opencode/<model> has no usable credential record" is
1314
+ // the sentence an operator can act on. The credential path has no model and keeps the
1315
+ // generic sentence (whatWithoutModel), so its rendering is unchanged.
1316
+ missing_provider_record: {
1317
+ what: "The route {provider}/{model} has no usable credential record",
1318
+ whatWithoutModel:
1319
+ "The {backend}/{provider} route for {step} has no usable credential ({detail})",
1320
+ why: CRED_STORE_WHY,
1321
+ fixes: [
1322
+ "Add {provider} to the OpenCode store, then re-set the secret:",
1323
+ "$ opencode auth login",
1324
+ OPENCODE_STORE,
1325
+ ],
1326
+ annotationFix:
1327
+ "add {provider} to the OpenCode store with `opencode auth login`, then set OPENCODE_AUTH_JSON again",
1328
+ },
1329
+ missing_subscription_record: {
1330
+ why: CRED_STORE_WHY,
1331
+ fixes: (params) =>
1332
+ isOpencodeRoute(params)
1333
+ ? OPENCODE_SUBSCRIPTION_FIXES
1334
+ : CLAUDE_SUBSCRIPTION_FIXES,
1335
+ annotationFix: (params) =>
1336
+ isOpencodeRoute(params)
1337
+ ? "run `opencode auth login` and choose ChatGPT for provider `openai`, then re-set OPENCODE_AUTH_JSON, or rename the provider in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename)"
1338
+ : "log in again with `claude setup-token` and set `CLAUDE_CODE_OAUTH_TOKEN` (`gh secret set CLAUDE_CODE_OAUTH_TOKEN`)",
1339
+ },
1340
+ malformed_payload: {
1341
+ // WHY no route in the sentence: this class is raised for the OpenCode auth
1342
+ // store and for a Claude keychain payload alike, and {detail} names which.
1343
+ what: "The credential store is not usable: {detail}",
1344
+ why: CRED_STORE_WHY,
1345
+ fixes: [
1346
+ "Check that the store is a JSON object:",
1347
+ "$ jq -e 'type==\"object\"' ~/.local/share/opencode/auth.json",
1348
+ "Then re-set the secret:",
1349
+ OPENCODE_STORE,
1350
+ ],
1351
+ annotationFix:
1352
+ "make the OpenCode auth store a JSON object, then set OPENCODE_AUTH_JSON again",
1353
+ },
1354
+ source_read_failed: CREDENTIAL_UNUSABLE_ENV,
1355
+ "env-absent": CREDENTIAL_UNUSABLE_ENV,
1356
+ default: CREDENTIAL_UNUSABLE_ENV,
1357
+ },
1358
+ },
1359
+ "PRH-CRED-REJECTED": {
1360
+ level: "error",
1361
+ owner: "config",
1362
+ what: "provider {provider} rejected the credential in {secret}",
1363
+ variants: {
1364
+ // The rejected secret is a per-token credential (ANTHROPIC_API_KEY or
1365
+ // ANTHROPIC_AUTH_TOKEN): the CLI prefers it to the OAuth token, so
1366
+ // setting CLAUDE_CODE_OAUTH_TOKEN alone leaves the next run rejected the same way.
1367
+ api_key: {
1368
+ why: "the key is invalid, expired or revoked, and the CLI uses it ahead of CLAUDE_CODE_OAUTH_TOKEN",
1369
+ fixes: [
1370
+ // Prose between the two commands keeps them in separate code blocks: they are
1371
+ // alternatives, and one copied block would set the new key and then delete it.
1372
+ "Create a new key in the Claude Console and set it:",
1373
+ "$ gh secret set {secret}",
1374
+ "Or delete the secret so the review uses CLAUDE_CODE_OAUTH_TOKEN (setting CLAUDE_CODE_OAUTH_TOKEN alone changes nothing while {secret} is set):",
1375
+ "$ gh secret delete {secret}",
1376
+ "Then ask for a new review:",
1377
+ REVIEW_AGAIN,
1378
+ LEGACY_REVIEW_NOTE,
1379
+ ],
1380
+ annotationFix:
1381
+ "create a new key and run `gh secret set {secret}`, or delete the {secret} secret so the OAuth token is used (setting CLAUDE_CODE_OAUTH_TOKEN alone changes nothing while the key is set)",
1382
+ },
1383
+ oauth: {
1384
+ why: "it is expired, revoked, or a short-lived /login session token",
1385
+ fixes: [
1386
+ "$ claude setup-token && gh secret set CLAUDE_CODE_OAUTH_TOKEN",
1387
+ "Then ask for a new review:",
1388
+ REVIEW_AGAIN,
1389
+ LEGACY_REVIEW_NOTE,
1390
+ ],
1391
+ annotationFix:
1392
+ "log in again with `claude setup-token` and set `CLAUDE_CODE_OAUTH_TOKEN` (`gh secret set CLAUDE_CODE_OAUTH_TOKEN`)",
1393
+ },
1394
+ default: {
1395
+ why: "it is expired, revoked, or a short-lived /login session token",
1396
+ fixes: [
1397
+ "$ claude setup-token && gh secret set CLAUDE_CODE_OAUTH_TOKEN",
1398
+ "Or, for an API key, create a new key in the Claude Console and set it:",
1399
+ "$ gh secret set ANTHROPIC_API_KEY",
1400
+ "Or, for OpenCode, re-export the auth store and re-set the secret:",
1401
+ OPENCODE_STORE,
1402
+ "Then ask for a new review:",
1403
+ REVIEW_AGAIN,
1404
+ LEGACY_REVIEW_NOTE,
1405
+ ],
1406
+ annotationFix:
1407
+ "replace the credential in {secret} with a new one, then run `gh secret set {secret}`",
1408
+ },
1409
+ },
1410
+ },
1411
+ "PRH-ROUTING-MISSING": {
1412
+ level: "error",
1413
+ owner: "config",
1414
+ what: "OpenCode auth is set but the routing variable is empty, so the default Claude route is used",
1415
+ variants: single(
1416
+ "the run would fail later at the Claude credential check",
1417
+ [
1418
+ '$ gh variable set CRYSK_ROUTING --body "$(jq -c .routing ~/.crysk/config.json)"',
1419
+ "On a machine set up before the rename the config is ~/.prhero/config.json: use that path in the command.",
1420
+ LEGACY_ROUTING_NOTE,
1421
+ ],
1422
+ `set CRYSK_ROUTING from your routing config: \`gh variable set CRYSK_ROUTING --body "$(jq -c .routing ~/.crysk/config.json)"\` (~/.prhero/config.json on a machine set up before the rename; PRHERO_ROUTING on a workflow set up before the rename)`,
1423
+ ),
1424
+ },
1425
+ "PRH-ROUTING-INVALID": {
1426
+ level: "error",
1427
+ owner: "config",
1428
+ what: "The routing variable is invalid: {detail}",
1429
+ variants: single(
1430
+ "Crysk cannot tell which backend and model each agent should use",
1431
+ [
1432
+ "Edit the JSON, then set it again:",
1433
+ '$ gh variable set CRYSK_ROUTING --body "$(jq -c . routing.json)"',
1434
+ LEGACY_ROUTING_NOTE,
1435
+ ],
1436
+ "fix the routing JSON ({detail}), then set it again with `gh variable set CRYSK_ROUTING` (PRHERO_ROUTING on a workflow set up before the rename)",
1437
+ ),
1438
+ },
1439
+ "PRH-ROUTE-UNRESOLVABLE": {
1440
+ level: "error",
1441
+ owner: "config",
1442
+ what: "Model routing for {step} has no usable route: {detail}",
1443
+ variants: {
1444
+ unmapped: ROUTE_UNMAPPED,
1445
+ ambiguous: {
1446
+ why: ROUTE_WHY,
1447
+ fixes: [
1448
+ "Remove the duplicate mapping for this route from CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename).",
1449
+ ],
1450
+ annotationFix:
1451
+ "remove the duplicate mapping for this route from CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename)",
1452
+ },
1453
+ "spend-disabled": {
1454
+ why: ROUTE_WHY,
1455
+ fixes: [
1456
+ "Enable spend for this route in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename).",
1457
+ ],
1458
+ annotationFix:
1459
+ "enable spend for this route in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename)",
1460
+ },
1461
+ "multiple-opencode-providers": {
1462
+ why: ROUTE_WHY,
1463
+ fixes: [
1464
+ "Keep one OpenCode provider per review in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename).",
1465
+ ],
1466
+ annotationFix:
1467
+ "keep one OpenCode provider per review in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename)",
1468
+ },
1469
+ default: ROUTE_UNMAPPED,
1470
+ },
1471
+ },
1472
+ // WHY provider-owned: the provider refused the model, so the lead reads
1473
+ // "Provider <name>:". provider_configuration_invalid shares this code and keeps
1474
+ // its own owner (config) through its variant, so its rendering is unchanged.
1475
+ "PRH-MODEL-UNAVAILABLE": {
1476
+ level: "error",
1477
+ owner: "provider",
1478
+ what: "Provider {provider} does not serve the model configured for {step}",
1479
+ variants: {
1480
+ default: MODEL_NOT_SERVED,
1481
+ // Every failed hunter was refused for one model (the CLI record names it): the lead
1482
+ // already names the provider, so the sentence names the model, and only when known.
1483
+ // A transport model_unavailable keeps the default wording (renderError picks by cause).
1484
+ every_hunter: {
1485
+ ...MODEL_NOT_SERVED,
1486
+ what: "the configured model {model} is not served by this provider",
1487
+ whatWithoutModel: "the configured model is not served by this provider",
1488
+ },
1489
+ provider_configuration_invalid: { ...MODEL_NOT_SERVED, owner: "config" },
1490
+ },
1491
+ },
1492
+ "PRH-PROMPTSET-INVALID": {
1493
+ level: "error",
1494
+ owner: "config",
1495
+ what: "The prompt set is invalid: {detail}",
1496
+ variants: single(
1497
+ "an agent file or PRHERO_EXTRA_HUNTERS entry cannot be loaded",
1498
+ [
1499
+ "Fix the file or `agents_dir`, then check for free:",
1500
+ "$ crysk review --pr {pr} --dry-run",
1501
+ ],
1502
+ "fix the agent file or `agents_dir` ({detail}), then check it with `crysk review --pr {pr} --dry-run`",
1503
+ ),
1504
+ },
1505
+ "PRH-GOTCHAS-MISSING": {
1506
+ level: "error",
1507
+ owner: "config",
1508
+ what: ".crysk/gotchas.md is missing or still the scaffold",
1509
+ variants: single(
1510
+ "reviews need real repository facts to be accurate",
1511
+ [
1512
+ "Run `npx -y crysk init` in a clone of the repository (it creates .crysk/config.json and .crysk/gotchas.md), then write real facts about this repository, delete the scaffold marker line if it is there, and commit the file to the base branch (comment-triggered runs read the base branch).",
1513
+ ],
1514
+ "write real facts into .crysk/gotchas.md, remove the scaffold marker line if present, and commit it to the base branch",
1515
+ ),
1516
+ },
1517
+ "PRH-CONFIG-INVALID": {
1518
+ level: "error",
1519
+ owner: "config",
1520
+ what: ".crysk/config.json is invalid: {detail}",
1521
+ variants: single(
1522
+ "Crysk refuses to guess repository settings",
1523
+ ["Fix the file, then check it:", "$ crysk review --pr {pr} --dry-run"],
1524
+ "fix `.crysk/config.json` ({detail}), then check it with `crysk review --pr {pr} --dry-run`",
1525
+ ),
1526
+ },
1527
+ "PRH-TOKEN-PERMISSION": {
1528
+ level: "error",
1529
+ owner: "config",
1530
+ what: "The workflow token lacks `{scope}: write`",
1531
+ variants: {
1532
+ ...single(
1533
+ "Crysk cannot post its result on the PR",
1534
+ [
1535
+ "Add `{scope}: write` to the job's `permissions:`, or re-scaffold the workflow:",
1536
+ "$ crysk ci init --force",
1537
+ ],
1538
+ "add `{scope}: write` under the job's `permissions:` in the workflow",
1539
+ ),
1540
+ // WHY a separate variant: a 403 whose scope is not known names no scope.
1541
+ // renderCode picks it for every caller when the scope is blank.
1542
+ "no-scope": {
1543
+ what: "GitHub refused the workflow token (HTTP 403) during {step}",
1544
+ why: "Crysk cannot post its result on the PR",
1545
+ fixes: [
1546
+ `Check that the workflow passes \`${GITHUB_TOKEN_INPUT}\` on the action step, and keeps the \`permissions:\` block that \`crysk ci init\` scaffolds:`,
1547
+ "$ crysk ci init --force",
1548
+ ],
1549
+ annotationFix: `check that the workflow passes \`${GITHUB_TOKEN_INPUT}\` and keeps the \`permissions:\` block that \`crysk ci init\` scaffolds`,
1550
+ },
1551
+ },
1552
+ },
1553
+ "PRH-GITHUB-TOKEN-INVALID": {
1554
+ level: "error",
1555
+ owner: "config",
1556
+ what: "The github-token input is invalid",
1557
+ variants: single(
1558
+ "every GitHub API call is rejected",
1559
+ [`Set \`${GITHUB_TOKEN_INPUT}\` on the action step.`],
1560
+ `set \`${GITHUB_TOKEN_INPUT}\` on the action step`,
1561
+ ),
1562
+ },
1563
+ "PRH-GITHUB-UNAVAILABLE": {
1564
+ level: "error",
1565
+ owner: "provider",
1566
+ providerName: "GitHub",
1567
+ what: "the GitHub API failed (HTTP {detail})",
1568
+ variants: {
1569
+ rate_limit: {
1570
+ what: "the GitHub API rate limit was reached",
1571
+ why: "GitHub has throttled this token, so an immediate retry would fail the same way",
1572
+ fixes: [
1573
+ "Wait for the limit to reset, then re-run the workflow:",
1574
+ "$ gh run rerun {runId}",
1575
+ ],
1576
+ annotationFix:
1577
+ "wait for the GitHub rate limit to reset, then re-run the workflow",
1578
+ },
1579
+ server: GITHUB_SERVER,
1580
+ default: GITHUB_SERVER,
1581
+ },
1582
+ },
1583
+ "PRH-PR-UNRESOLVED": {
1584
+ level: "error",
1585
+ owner: "config",
1586
+ what: "Crysk could not determine the pull request number or head",
1587
+ variants: {
1588
+ ...single(
1589
+ "nothing can be posted on a PR it cannot identify",
1590
+ [
1591
+ "Run from a pull_request or issue_comment event, or pass the `pr-number` input.",
1592
+ ],
1593
+ "run from a pull_request or issue_comment event, or pass the `pr-number` input",
1594
+ ),
1595
+ // The pr-number input was given but is not a positive integer. The record's
1596
+ // detail names the input, so the fix tells the reader to correct it.
1597
+ "malformed-input": {
1598
+ what: "Crysk could not determine the pull request number or head ({detail})",
1599
+ why: "nothing can be posted on a PR it cannot identify",
1600
+ fixes: ["Pass a positive integer as the `pr-number` input."],
1601
+ annotationFix: "pass a positive integer as the `pr-number` input",
1602
+ },
1603
+ },
1604
+ },
1605
+ "PRH-STATUS-WRITE-FAILED": {
1606
+ level: "error",
1607
+ owner: "unclassified",
1608
+ providerName: "GitHub",
1609
+ what: "Crysk could not write its commit status ({detail})",
1610
+ variants: {
1611
+ default: {
1612
+ why: "the required check has no result for this head without it",
1613
+ fixes: [
1614
+ "Re-run the failed jobs:",
1615
+ RERUN_FAILED,
1616
+ "If it repeats, report it.",
1617
+ ],
1618
+ annotationFix: UNCLASSIFIED_FIX,
1619
+ },
1620
+ permission: {
1621
+ owner: "config",
1622
+ why: "the required check has no result for this head without it",
1623
+ fixes: [
1624
+ "Add `statuses: write` to the job's `permissions:`, or re-scaffold the workflow:",
1625
+ "$ crysk ci init --force",
1626
+ ],
1627
+ annotationFix:
1628
+ "add `statuses: write` under the job's `permissions:` in the workflow",
1629
+ },
1630
+ server: {
1631
+ owner: "provider",
1632
+ why: "the required check has no result for this head without it",
1633
+ fixes: ["Re-run the workflow:", "$ gh run rerun {runId}"],
1634
+ annotationFix:
1635
+ "re-run the workflow once GitHub accepts commit statuses again",
1636
+ },
1637
+ },
1638
+ },
1639
+ "PRH-RUNTIME-UNAVAILABLE": {
1640
+ level: "error",
1641
+ owner: { action: "pr-hero", local: "config" },
1642
+ what: "a runtime Crysk depends on is unusable: {detail}",
1643
+ variants: {
1644
+ action: {
1645
+ why: "the action installs this runtime itself, so this is a Crysk defect",
1646
+ fixes: [
1647
+ "Report it with this run:",
1648
+ '$ gh issue create -R cryskai/crysk --title "PRH-RUNTIME-UNAVAILABLE" --body "{runUrl}"',
1649
+ ],
1650
+ annotationFix: "report it at cryskai/crysk with this run's URL",
1651
+ },
1652
+ local: RUNTIME_LOCAL,
1653
+ default: RUNTIME_LOCAL,
1654
+ },
1655
+ },
1656
+ "PRH-INSTALL-FAILED": {
1657
+ level: "error",
1658
+ owner: "unclassified",
1659
+ what: "The {step} step failed",
1660
+ whatWithoutStep: "An install step failed",
1661
+ variants: single(
1662
+ "a download or install step failed, and Crysk cannot tell which external cause it was",
1663
+ [
1664
+ "Re-run only the failed jobs:",
1665
+ RERUN_FAILED,
1666
+ "If it repeats, report it.",
1667
+ ],
1668
+ "re-run only the failed jobs with `gh run rerun {runId} --failed`",
1669
+ ),
1670
+ },
1671
+ "PRH-PROVIDER-LIMITED": {
1672
+ level: "error",
1673
+ owner: "provider",
1674
+ what: "rate limit or quota reached",
1675
+ variants: {
1676
+ default: PROVIDER_LIMITED,
1677
+ // Every failed hunter hit the same limit and the provider said which one (an empty
1678
+ // credit balance, say): the sentence quotes it, and the fix is the default's. The
1679
+ // quote comes FIRST in this and the next two variants: the commit status clips the
1680
+ // code plus the sentence at 140 characters, and the provider's words (with a reset
1681
+ // time) must survive that. The explanation after them is for the comment.
1682
+ every_hunter: {
1683
+ ...PROVIDER_LIMITED,
1684
+ what: "{detail} (rate limit or quota reached)",
1685
+ },
1686
+ // The credit balance or spend limit of the account behind ANTHROPIC_API_KEY (the CLI
1687
+ // prefers that key over the subscription token, so it is the credential in use).
1688
+ // Waiting does not help: the fix is to top up, or to stop using the key.
1689
+ api_key: {
1690
+ what: "{detail}: the Anthropic account behind ANTHROPIC_API_KEY has no credit left or reached its spend limit",
1691
+ why: "the provider refuses every request until the account has credit again, so a retry would fail the same way",
1692
+ fixes: [
1693
+ "Add credit to the Anthropic account behind ANTHROPIC_API_KEY (Claude Console → Plans & Billing), or delete the secret so the review uses CLAUDE_CODE_OAUTH_TOKEN:",
1694
+ "$ gh secret delete ANTHROPIC_API_KEY",
1695
+ "Then ask for a new review:",
1696
+ REVIEW_AGAIN,
1697
+ LEGACY_REVIEW_NOTE,
1698
+ ],
1699
+ annotationFix:
1700
+ "add credit to the Anthropic account behind ANTHROPIC_API_KEY (Claude Console → Plans & Billing), or delete the ANTHROPIC_API_KEY secret so the review uses CLAUDE_CODE_OAUTH_TOKEN",
1701
+ },
1702
+ // The Claude subscription behind CLAUDE_CODE_OAUTH_TOKEN reached a usage window. The
1703
+ // provider's own sentence carries the reset time, so the what quotes it.
1704
+ subscription: {
1705
+ what: "{detail}: the Claude subscription behind CLAUDE_CODE_OAUTH_TOKEN reached its usage limit",
1706
+ why: "the subscription refuses requests until its usage window resets, so an immediate retry would fail the same way",
1707
+ fixes: [
1708
+ "Re-run after the limit resets (the reset time is in the sentence above):",
1709
+ REVIEW_AGAIN,
1710
+ LEGACY_REVIEW_NOTE,
1711
+ "Or set ANTHROPIC_API_KEY to bill per token:",
1712
+ "$ gh secret set ANTHROPIC_API_KEY",
1713
+ ],
1714
+ annotationFix:
1715
+ "re-run after the limit resets, or set ANTHROPIC_API_KEY to bill per token",
1716
+ },
1717
+ },
1718
+ },
1719
+ "PRH-PROVIDER-UNAVAILABLE": {
1720
+ level: "error",
1721
+ owner: "provider",
1722
+ what: "unreachable",
1723
+ variants: single(
1724
+ "the request did not complete, and the provider's outcome cannot be confirmed from here",
1725
+ ["Re-run the workflow:", "$ gh run rerun {runId}"],
1726
+ "re-run the workflow with `gh run rerun {runId}`",
1727
+ ),
1728
+ },
1729
+ "PRH-PROVIDER-REFUSED": {
1730
+ level: "error",
1731
+ owner: "provider",
1732
+ what: "the request was refused",
1733
+ variants: single(
1734
+ PROVIDER_REFUSED_WHY,
1735
+ [
1736
+ "Ask for a new review once:",
1737
+ REVIEW_AGAIN,
1738
+ LEGACY_REVIEW_NOTE,
1739
+ "If it repeats, report it.",
1740
+ ],
1741
+ "ask for a new review once, and report it if the provider refuses again",
1742
+ ),
1743
+ },
1744
+ "PRH-ENGINE-DEFECT": {
1745
+ level: "error",
1746
+ owner: "pr-hero",
1747
+ what: "Crysk hit an internal error ({detail}) in {step}",
1748
+ variants: single(
1749
+ "this is a defect in Crysk, not in your configuration",
1750
+ ["Report it, with this run:", `$ ${ENGINE_DEFECT_ISSUE}`],
1751
+ "report it at cryskai/crysk with this run's URL",
1752
+ ),
1753
+ },
1754
+ "PRH-HUNTERS-FAILED": {
1755
+ level: "error",
1756
+ owner: "unclassified",
1757
+ // WHY a lead of its own: the caller requests this code for a condition it
1758
+ // sees directly (the hunter set), so "Unclassified:" would blame an unknown
1759
+ // cause that does not exist. The owner stays unclassified for the table.
1760
+ lead: "Not reviewed:",
1761
+ what: "Every hunter failed in {step}: {detail}",
1762
+ variants: {
1763
+ default: {
1764
+ why: "no hunter returned a result, so there is no finding to report",
1765
+ fixes: [
1766
+ "Re-run the failed jobs:",
1767
+ RERUN_FAILED,
1768
+ "If it repeats, report it.",
1769
+ ],
1770
+ annotationFix:
1771
+ "re-run the failed jobs with `gh run rerun {runId} --failed`",
1772
+ },
1773
+ // Every hunter was refused for the size of the request: a re-run sends the same one.
1774
+ context_window_exceeded: {
1775
+ why: "the review input is too large for the model, so every hunter was refused and a re-run would send the same request",
1776
+ fixes: [
1777
+ "Lower `max-changed-lines` in the workflow's `with:` block (or `max_changed_lines` in the repo config), or exclude paths in `.cryskignore` (`.prheroignore` in a repo set up before the rename), then ask for a new review:",
1778
+ REVIEW_AGAIN,
1779
+ LEGACY_REVIEW_NOTE,
1780
+ ],
1781
+ annotationFix:
1782
+ "lower `max-changed-lines` (or `max_changed_lines` in the repo config) or exclude paths in `.cryskignore` (`.prheroignore` before the rename)",
1783
+ },
1784
+ },
1785
+ },
1786
+ "PRH-UNCLASSIFIED": {
1787
+ level: "error",
1788
+ owner: "unclassified",
1789
+ what: "Crysk stopped at {step} and could not tell why",
1790
+ variants: {
1791
+ default: {
1792
+ why: "rather than guess, it reports this honestly",
1793
+ fixes: UNCLASSIFIED_FIXES,
1794
+ annotationFix: UNCLASSIFIED_FIX,
1795
+ },
1796
+ github: {
1797
+ what: "GitHub returned {detail} at {step}, and Crysk cannot tell whose fix it is",
1798
+ why: "Crysk does not map this GitHub status to an owner, so it does not guess",
1799
+ fixes: UNCLASSIFIED_FIXES,
1800
+ annotationFix: UNCLASSIFIED_FIX,
1801
+ },
1802
+ },
1803
+ },
1804
+ "PRH-CANCELLED": {
1805
+ level: "notice",
1806
+ owner: "unclassified",
1807
+ lead: "Not reviewed:",
1808
+ headline: "PRH-CANCELLED: not reviewed",
1809
+ what: "The review was cancelled or superseded by a newer push",
1810
+ variants: single(
1811
+ "a newer run replaces this one, so this result would describe an outdated head",
1812
+ [
1813
+ "Ask for a review of the current head:",
1814
+ REVIEW_AGAIN,
1815
+ LEGACY_REVIEW_NOTE,
1816
+ ],
1817
+ 'ask for a review of the current head with `gh pr comment {pr} --body "/crysk review"` (or "/pr-hero review" on a workflow set up before the rename)',
1818
+ ),
1819
+ },
1820
+ };
1821
+
1822
+ export function renderError(
1823
+ cls: ErrorClass,
1824
+ params: ErrorParams,
1825
+ ctx: OutcomeContext,
1826
+ ): RenderedError {
1827
+ const detail = isBlank(params.detail) ? classDetail(cls) : params.detail;
1828
+ // An install class carries the step it failed on; an explicit non-blank step wins.
1829
+ const step =
1830
+ cls.kind === "install" && isBlank(params.step) ? cls.step : params.step;
1831
+ const merged: ErrorParams = { ...params, detail, step };
1832
+ return renderCode(codeOf(cls), merged, ctx, variantOf(cls));
1833
+ }
1834
+
1835
+ // The rendering of a run whose every failed hunter shares one transport cause, or undefined
1836
+ // when the cause is not on the allowlist below. WHY an allowlist, not "every cause with a
1837
+ // code": a shared cause's sentence and fixes name params that this path does not always
1838
+ // have (the secret, the backend, the step) and would ship a placeholder to the PR. A cause
1839
+ // is rendered only when its message is complete with the params the path has: provider,
1840
+ // model, pr, runId, runUrl, step and detail. Every other cause, or a missing param, keeps the
1841
+ // caller's generic PRH-HUNTERS-FAILED.
1842
+ export function renderHunterCause(
1843
+ cause: TransportFailureCause,
1844
+ params: ErrorParams,
1845
+ ctx: OutcomeContext,
1846
+ // What every failed hunter reported identically, when they agree: the provider's words
1847
+ // and the secret they ran on. Only the causes whose sentence has room for them use them.
1848
+ shared: {
1849
+ readonly detail?: string;
1850
+ readonly credential?: FailureCredential;
1851
+ } = {},
1852
+ ): RenderedError | undefined {
1853
+ // A rejected credential is rendered from its own code only when the secret and the
1854
+ // provider are known, so the sentence names both and never a placeholder.
1855
+ if (cause === "auth_invalid") {
1856
+ if (shared.credential === undefined || isBlank(params.provider)) {
1857
+ return undefined;
1858
+ }
1859
+ return renderCode(
1860
+ "PRH-CRED-REJECTED",
1861
+ { ...params, secret: shared.credential },
1862
+ ctx,
1863
+ );
1864
+ }
1865
+ // An empty balance or a spent quota. The provider's words say which limit it was, and the
1866
+ // credential says whose: a credit balance on an API key is fixed by topping up, a
1867
+ // subscription window by waiting for its reset. Without the words the default wording
1868
+ // stands.
1869
+ if (cause === "quota_exhausted") {
1870
+ if (shared.detail === undefined) {
1871
+ return renderCode("PRH-PROVIDER-LIMITED", params, ctx);
1872
+ }
1873
+ const quoted = { ...params, detail: shared.detail };
1874
+ const variant =
1875
+ shared.credential === "ANTHROPIC_API_KEY"
1876
+ ? "api_key"
1877
+ : shared.credential === "CLAUDE_CODE_OAUTH_TOKEN"
1878
+ ? "subscription"
1879
+ : "every_hunter";
1880
+ return renderCode("PRH-PROVIDER-LIMITED", quoted, ctx, variant);
1881
+ }
1882
+ // The provider's 404 names the model, so the every_hunter wording keeps it. Its fixes name
1883
+ // the provider, so the provider must be known; the model is optional (whatWithoutModel).
1884
+ if (cause === "model_unavailable") {
1885
+ if (isBlank(params.provider)) return undefined;
1886
+ return renderCode("PRH-MODEL-UNAVAILABLE", params, ctx, "every_hunter");
1887
+ }
1888
+ // The credential sentence and its fixes name both the route's provider and model.
1889
+ if (cause === "missing_provider_record") {
1890
+ if (isBlank(params.provider) || isBlank(params.model)) return undefined;
1891
+ return renderError({ kind: "transport", cause }, params, ctx);
1892
+ }
1893
+ return undefined;
1894
+ }
1895
+
1896
+ // For a code the caller requests directly. `variant` picks the sub-class, which
1897
+ // fixes the owner, the wording and the fix; renderError supplies it for classes.
1898
+ export function renderCode(
1899
+ code: ErrorCode,
1900
+ params: ErrorParams,
1901
+ ctx: OutcomeContext,
1902
+ variant?: string,
1903
+ ): RenderedError {
1904
+ const entry = ERROR_CATALOG[code];
1905
+ const picked = pickVariant(entry, ctx, paramVariant(code, params, variant));
1906
+ const owner = ownerFor(picked.owner ?? entry.owner, ctx);
1907
+ const providerName = entry.providerName ?? cleanName(params.provider);
1908
+ const lead = entry.lead ?? ownerLead(owner, providerName);
1909
+ const link = `${DOCS_BASE}${code.toLowerCase()}`;
1910
+ const what =
1911
+ picked.what === undefined
1912
+ ? whatOf(entry, params)
1913
+ : isBlank(params.model) && picked.whatWithoutModel !== undefined
1914
+ ? picked.whatWithoutModel
1915
+ : picked.what;
1916
+ const sentence = capitalized(fill(what, params, "annotation"));
1917
+ const message =
1918
+ `${lead} ${sentence}. ` +
1919
+ `Why: ${fill(picked.why, params, "annotation")}. ` +
1920
+ `Fix: ${annotationFixOf(picked, params)}. ` +
1921
+ `Docs: ${link}`;
1922
+ return {
1923
+ code,
1924
+ owner,
1925
+ what: sentence,
1926
+ annotation: `::${entry.level} title=crysk ${code}::${escapeCommandData(message)}`,
1927
+ summary: summaryLines(code, entry, lead, what, picked, params, link),
1928
+ };
1929
+ }
1930
+
1931
+ // The entry's sentence, or its step-free form when no step is given.
1932
+ function whatOf(entry: CatalogEntry, params: ErrorParams): string {
1933
+ return entry.whatWithoutStep !== undefined && isBlank(params.step)
1934
+ ? entry.whatWithoutStep
1935
+ : entry.what;
1936
+ }
1937
+
1938
+ // Upper-cases the first character only. The owner lead ends in a colon, so the
1939
+ // sentence after it must start with a capital; backticked code and the rest of
1940
+ // the text are left as they are.
1941
+ function capitalized(text: string): string {
1942
+ // WHY: the product name is always lowercase `pr-hero`; upper-casing it reads as "Pr-hero".
1943
+ if (text.startsWith("crysk")) return text;
1944
+ const first = text.slice(0, 1);
1945
+ return first.toUpperCase() + text.slice(first.length);
1946
+ }
1947
+
1948
+ // WHY the catalog picks the variant from the params, not the caller: a permission
1949
+ // 403 with no scope names no scope, so every caller (a class or a direct
1950
+ // renderCode) gets the same text and no placeholder reaches the PR. The same
1951
+ // holds for an unresolved PR: a detail means the pr-number input was given and
1952
+ // is malformed, so the fix must name that input, not ask for one that was passed.
1953
+ function paramVariant(
1954
+ code: ErrorCode,
1955
+ params: ErrorParams,
1956
+ variant: string | undefined,
1957
+ ): string | undefined {
1958
+ if (code === "PRH-TOKEN-PERMISSION" && isBlank(params.scope)) {
1959
+ return "no-scope";
1960
+ }
1961
+ // The credential in the secret picks the fix: a rejected API key and a rejected OAuth
1962
+ // token are replaced differently, and the CLI uses the key ahead of the token.
1963
+ if (code === "PRH-CRED-REJECTED" && variant === undefined) {
1964
+ if (
1965
+ params.secret === "ANTHROPIC_API_KEY" ||
1966
+ params.secret === "ANTHROPIC_AUTH_TOKEN"
1967
+ ) {
1968
+ return "api_key";
1969
+ }
1970
+ if (params.secret === "CLAUDE_CODE_OAUTH_TOKEN") return "oauth";
1971
+ }
1972
+ // A caller that names a variant keeps it, so the default wording stays
1973
+ // reachable with a detail present.
1974
+ if (
1975
+ variant === undefined &&
1976
+ code === "PRH-PR-UNRESOLVED" &&
1977
+ !isBlank(params.detail)
1978
+ ) {
1979
+ return "malformed-input";
1980
+ }
1981
+ return variant;
1982
+ }
1983
+
1984
+ function pickVariant(
1985
+ entry: CatalogEntry,
1986
+ ctx: OutcomeContext,
1987
+ variant: string | undefined,
1988
+ ): CatalogVariant {
1989
+ const table: Partial<Record<string, CatalogVariant>> = entry.variants;
1990
+ return (
1991
+ table[ctx] ??
1992
+ (variant === undefined ? undefined : table[variant]) ??
1993
+ entry.variants.default
1994
+ );
1995
+ }
1996
+
1997
+ function ownerFor(rule: OwnerRule, ctx: OutcomeContext): Owner {
1998
+ return typeof rule === "string" ? rule : rule[ctx];
1999
+ }
2000
+
2001
+ function variantOf(cls: ErrorClass): string | undefined {
2002
+ switch (cls.kind) {
2003
+ case "credential":
2004
+ return cls.failureClass;
2005
+ case "route":
2006
+ return cls.reason;
2007
+ case "github":
2008
+ return githubVariant(cls);
2009
+ // The transport cause picks its own sub-class where the code shares one:
2010
+ // PRH-MODEL-UNAVAILABLE serves provider_configuration_invalid (config) and
2011
+ // model_unavailable (provider). Other codes have no such variant and fall
2012
+ // back to their default.
2013
+ case "transport":
2014
+ return cls.cause;
2015
+ default:
2016
+ return undefined;
2017
+ }
2018
+ }
2019
+
2020
+ // The GitHub sub-class names the family whose wording and fix apply. A status
2021
+ // with no family of its own returns undefined and renders the code's default.
2022
+ function githubVariant(cls: GithubClass): string | undefined {
2023
+ if (cls.status === 429 || (cls.status === 403 && cls.rateLimited === true)) {
2024
+ return "rate_limit";
2025
+ }
2026
+ if (cls.status >= 500) return "server";
2027
+ return githubCode(cls) === "PRH-UNCLASSIFIED" ? "github" : undefined;
2028
+ }
2029
+
2030
+ function classDetail(cls: ErrorClass): string | undefined {
2031
+ switch (cls.kind) {
2032
+ case "capability":
2033
+ return CAPABILITY_PHRASE[cls.issue];
2034
+ case "credential":
2035
+ return CREDENTIAL_PHRASE[cls.failureClass];
2036
+ case "transport":
2037
+ return TRANSPORT_PHRASE[cls.cause];
2038
+ case "route":
2039
+ return ROUTE_PHRASE[cls.reason];
2040
+ case "github":
2041
+ return String(cls.status);
2042
+ default:
2043
+ return undefined;
2044
+ }
2045
+ }
2046
+
2047
+ function isBlank(value: string | undefined): boolean {
2048
+ return value === undefined || value.trim() === "";
2049
+ }
2050
+
2051
+ function cleanName(value: string | undefined): string | undefined {
2052
+ return isBlank(value) ? undefined : value?.trim();
2053
+ }
2054
+
2055
+ function paramText(params: ErrorParams, key: keyof ErrorParams): string {
2056
+ const raw = params[key];
2057
+ const text = raw === undefined || raw === null ? "" : String(raw);
2058
+ return text.trim() === "" ? NEUTRAL[key] : text;
2059
+ }
2060
+
2061
+ // "annotation" keeps raw values (escaped later); "summary" flattens line breaks
2062
+ // so a value cannot break its block; "command" also keeps only shell-safe
2063
+ // characters in `detail`, because a failure's free text must not reach a command
2064
+ // the reader may paste.
2065
+ type FillMode = "annotation" | "summary" | "command";
2066
+
2067
+ // Fills {name} placeholders.
2068
+ function fill(template: string, params: ErrorParams, mode: FillMode): string {
2069
+ return template.replace(/\{(\w+)\}/g, (placeholder: string, name: string) => {
2070
+ const key = name as keyof ErrorParams;
2071
+ if (!(key in NEUTRAL)) return placeholder;
2072
+ const text = paramText(params, key);
2073
+ if (mode === "annotation") return text;
2074
+ const safe =
2075
+ mode === "command" && key === "detail" ? shellSafe(text) : text;
2076
+ return safe.replace(/\r\n|\r|\n/g, " ");
2077
+ });
2078
+ }
2079
+
2080
+ // WHY an allowlist: detail is free text from a failure, and a command the reader
2081
+ // pastes must not carry a quote, a substitution or a separator.
2082
+ function shellSafe(text: string): string {
2083
+ return text.replace(/[^A-Za-z0-9 _.:-]/g, "");
2084
+ }
2085
+
2086
+ function annotationFixOf(picked: CatalogVariant, params: ErrorParams): string {
2087
+ const raw =
2088
+ typeof picked.annotationFix === "function"
2089
+ ? picked.annotationFix(params)
2090
+ : picked.annotationFix;
2091
+ return fill(raw, params, "annotation").replace(/[:.]+$/, "");
2092
+ }
2093
+
2094
+ // The variant's fix lines; a function fix picks its list from the params.
2095
+ function fixesOf(
2096
+ picked: CatalogVariant,
2097
+ params: ErrorParams,
2098
+ ): readonly string[] {
2099
+ return typeof picked.fixes === "function"
2100
+ ? picked.fixes(params)
2101
+ : picked.fixes;
2102
+ }
2103
+
2104
+ function summaryLines(
2105
+ code: ErrorCode,
2106
+ entry: CatalogEntry,
2107
+ lead: string,
2108
+ what: string,
2109
+ picked: CatalogVariant,
2110
+ params: ErrorParams,
2111
+ link: string,
2112
+ ): string[] {
2113
+ const prose = (text: string): string => fill(text, params, "summary");
2114
+ const command = (text: string): string => fill(text, params, "command");
2115
+ return [
2116
+ `### ${entry.headline ?? code}`,
2117
+ "",
2118
+ `${lead} ${capitalized(prose(what))}`,
2119
+ "",
2120
+ `Why: ${prose(picked.why)}`,
2121
+ "",
2122
+ "Fix:",
2123
+ "",
2124
+ ...fixBlocks(fixesOf(picked, params), prose, command),
2125
+ `Docs: ${link}`,
2126
+ ];
2127
+ }
2128
+
2129
+ // Consecutive "$ " lines share one bash fence; prose lines stand alone.
2130
+ function fixBlocks(
2131
+ fixes: readonly string[],
2132
+ prose: (text: string) => string,
2133
+ command: (text: string) => string,
2134
+ ): string[] {
2135
+ const out: string[] = [];
2136
+ let inBlock = false;
2137
+ for (const line of fixes) {
2138
+ const isCommand = line.startsWith("$ ");
2139
+ if (isCommand && !inBlock) {
2140
+ out.push("```bash");
2141
+ inBlock = true;
2142
+ }
2143
+ if (!isCommand && inBlock) {
2144
+ out.push("```", "");
2145
+ inBlock = false;
2146
+ }
2147
+ out.push(isCommand ? command(line.slice(2)) : prose(line));
2148
+ if (!isCommand) out.push("");
2149
+ }
2150
+ if (inBlock) out.push("```", "");
2151
+ return out;
2152
+ }
2153
+
2154
+ // Workflow-command message escaping, copied from src/ci/trigger.ts
2155
+ // (escapeCommandData). The drift test in test/ci/outcome.test.ts compares the
2156
+ // two source texts; keep them identical.
2157
+ function escapeCommandData(text: string): string {
2158
+ return text
2159
+ .replaceAll("%", "%25")
2160
+ .replaceAll("\r", "%0D")
2161
+ .replaceAll("\n", "%0A");
2162
+ }
2163
+
2164
+ // The first line of every outcome comment the publisher posts (src/ci/publish.ts writes it).
2165
+ // Exported so the status reader and the publisher share one spelling; the trailing space
2166
+ // keeps a lookalike marker from matching.
2167
+ export const OUTCOME_MARKER_PREFIX = `${MARKER_OPEN}outcome `;
2168
+
2169
+ // The PRH-* code an outcome comment names, or null. renderError's summary opens with
2170
+ // `### <headline>`, and a headline is the bare code or the code then a colon and a sentence
2171
+ // (`PRH-CANCELLED: not reviewed`), so the code is the token at the start of that heading. The
2172
+ // token must be a catalogued code: a heading that merely looks like one reads as no code.
2173
+ export function parseOutcomeCode(body: string): ErrorCode | null {
2174
+ if (matchMarkerPrefix(body, OUTCOME_MARKER_PREFIX) === undefined) return null;
2175
+ const heading = /^### (PRH-[A-Z0-9-]+)(?=[:\s]|$)/m.exec(body);
2176
+ const code = heading?.[1];
2177
+ if (code === undefined) return null;
2178
+ return (ERROR_CODES as readonly string[]).includes(code)
2179
+ ? (code as ErrorCode)
2180
+ : null;
2181
+ }