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,1821 @@
1
+ // The human-facing half of local mode (ROADMAP B0): a pure renderer that
2
+ // turns a findings document into the markdown a developer actually reads, and
3
+ // a pure cost estimator that runs BEFORE the money is spent.
4
+ //
5
+ // Pure on purpose — no I/O, no git, no clock. The CLI owns every side effect,
6
+ // so the report can be re-rendered from an artifact on disk months later and
7
+ // come out byte-identical (the lab already replays old findings.json files;
8
+ // a renderer that reached for `new Date()` would make that a lie).
9
+
10
+ import { listPaths } from "#git/refs";
11
+ import type { ResolvedModelRoute, ResolvedStepRoute } from "#model/routing";
12
+ import {
13
+ type CiMode,
14
+ findingMarker,
15
+ PR_FINDING_MARKER_PREFIX,
16
+ PR_REREVIEW_CLOSED_MARKER_PREFIX,
17
+ prCommentMarker,
18
+ } from "#pr/preflight";
19
+ import {
20
+ type RecoveredSeverity,
21
+ SEVERITY_UNRECOVERABLE,
22
+ } from "#rereview/classify";
23
+ import type {
24
+ Finding,
25
+ FindingsDocument,
26
+ RefuterVerdict,
27
+ RunStatus,
28
+ Severity,
29
+ Tier,
30
+ } from "#review/findings";
31
+ import {
32
+ clusterByRootCause,
33
+ extractAnchor,
34
+ type RootCauseSummary,
35
+ rootCauseIdByFinding,
36
+ } from "#review/root-cause";
37
+ import {
38
+ BIN_NAME,
39
+ findMarker,
40
+ LEGACY_BIN_NAME,
41
+ matchMarkerPrefix,
42
+ } from "../brand";
43
+
44
+ export interface DiffStat {
45
+ files: number;
46
+ insertions: number;
47
+ deletions: number;
48
+ }
49
+
50
+ export interface CostEstimate {
51
+ low: number;
52
+ high: number;
53
+ // Plain-language statement of how coarse this is, meant to be printed next
54
+ // to the numbers so nobody reads the band as a quote.
55
+ basis: string;
56
+ }
57
+
58
+ // Per-hunter marginal cost, fitted to the measured runs (see BAND below).
59
+ // Deliberately three transparent coefficients instead of a regression: with
60
+ // this few calibration points anything fancier is false precision.
61
+ //
62
+ // The base is the load-bearing coefficient, recalibrated 2026-08-11 from
63
+ // 0.5 to 1.2: a hunter's floor is reading the TREE and the prompt
64
+ // machinery, nearly independent of a small diff. The proof was two PR-mode
65
+ // runs of the same 7-file / +21 −8 tree billing $4.74 and $3.92 against a
66
+ // $1.19–$2.39 band — both ~2x above the top, the exact under-estimate
67
+ // failure this band exists to prevent.
68
+ const USD_PER_AGENT_BASE = 1.2;
69
+ const USD_PER_CHANGED_LINE = 0.00021;
70
+ const USD_PER_FILE = 0.008;
71
+
72
+ // Skewed on purpose. Every recorded overrun was an UNDER-estimate, never
73
+ // over, so the upper arm is the wider one: a band that is too generous costs
74
+ // a second of hesitation, a band that is too tight costs real money.
75
+ const BAND_LOW = 0.65;
76
+ const BAND_HIGH = 1.4;
77
+
78
+ // WHY this function exists at all: the ROADMAP logs two cost overruns in a
79
+ // row — "~$21" against an actual bill, and "~$34" against an actual $48.30 —
80
+ // and both had the same cause. The estimate was carried over from the
81
+ // PREVIOUS arm instead of being computed from the tree about to be reviewed.
82
+ // So this estimates from the diff, and only from the diff.
83
+ //
84
+ // Calibration points, all measured on real runs of the current engine:
85
+ // - PR 1682's tree (7 files / +21 −8, 3 hunters + refuter) billed $4.74
86
+ // and $3.92 across two runs — the per-agent floor evidence;
87
+ // - a 45-file / +2775 −1237 tree with 5 hunters + refuter billed ~$14.78,
88
+ // and the same tree was recorded at ~$11/run elsewhere in the campaign;
89
+ // - the first B0 local run (5 files / +484, 4 hunters + refuter), $3.68.
90
+ // A legacy "~$2.61 small tree" point from before PR mode existed was
91
+ // RETIRED by the 1682 evidence: two same-engine runs of a comparable tree
92
+ // both landed far above it, and a calibration point the instrument itself
93
+ // contradicts is decoration. The ~$11 vs ~$14.78 spread on ONE tree is the
94
+ // whole argument for returning a band: the same diff, the same agents, a
95
+ // 34% swing. A point estimate here would be a fiction with a decimal point.
96
+ //
97
+ // The refuter is not a separate term: its cost rides in the coefficients,
98
+ // because every calibration run had the refuter leg included and a
99
+ // refuter's size tracks how much the hunters found, which tracks diff size.
100
+ export function estimateCost(
101
+ diffStat: DiffStat,
102
+ hunterCount: number,
103
+ summarizerEnabled = false,
104
+ // ROADMAP-DOORDASH M5. Defaulted OFF so every existing caller keeps its
105
+ // band byte-identical, and so a caller that forgets it under-quotes
106
+ // nothing it did not already under-quote.
107
+ scoutEnabled = false,
108
+ // Item 7 O-5a. Default 0 so every existing caller keeps its band
109
+ // byte-identical. Priced as its own term (not folded into `agents`) so a
110
+ // 40-finding re-review of a 2-file delta is not billed as 40 hunters.
111
+ verificationSteps = 0,
112
+ // The post-refuter consolidation pass. LAST and defaulted OFF so every
113
+ // existing call shape compiles and keeps its band; the product paths pass
114
+ // true. One seat, the scout's rule: a claims-only sonnet call costs far
115
+ // less than a hunter, and over-quoting is the cheap direction to be wrong.
116
+ consolidateEnabled = false,
117
+ ): CostEstimate {
118
+ const files = Math.max(0, diffStat.files);
119
+ const lines =
120
+ Math.max(0, diffStat.insertions) + Math.max(0, diffStat.deletions);
121
+ // A validated ReviewSpec always carries at least one hunter, so a zero here
122
+ // means a caller asked hypothetically. Clamping keeps the band from
123
+ // collapsing to $0–$0, which would read as "this is free".
124
+ // The scout takes a full agent seat, the summarizer's precedent, and that
125
+ // deliberately OVER-quotes: it is diff-only, one attempt, and reads no tree,
126
+ // so its true cost is a fraction of a hunter's. Two reasons it gets the seat
127
+ // anyway. First, this band's own rule — every recorded overrun was an
128
+ // UNDER-estimate, so the generous direction is the cheap one to be wrong in.
129
+ // Second, the scout has NO calibration point of its own: M4 billed $37.00
130
+ // across six prompt versions, two probe defects and a reverted experiment,
131
+ // which is a milestone total and not a per-spawn cost. M6 records cost per
132
+ // arm; that is the number this coefficient gets recalibrated from, and until
133
+ // it exists an invented per-scout coefficient would be false precision.
134
+ const hunterSeats = Math.max(
135
+ 0,
136
+ hunterCount +
137
+ (summarizerEnabled ? 1 : 0) +
138
+ (scoutEnabled ? 1 : 0) +
139
+ (consolidateEnabled ? 1 : 0),
140
+ );
141
+ const steps = Math.max(0, verificationSteps);
142
+ // A zero-hunter, zero-verify call still needs a band (the hypothetical
143
+ // floor). A skip-discovery re-review with N verify steps must NOT inherit
144
+ // that floor — that would bill a phantom hunter on top of verification.
145
+ const agents = hunterSeats === 0 && steps === 0 ? 1 : hunterSeats;
146
+ // Verification is its OWN term (item 7 O-5a), not folded into `agents`:
147
+ // a verify step reads one prior finding, not the whole tree, so multiplying
148
+ // it by changed-files would price a 40-finding re-review of a 2-file delta
149
+ // as if it were 40 hunters. The seat is the same per-agent floor — generous
150
+ // on purpose, same direction as the scout.
151
+ const mid =
152
+ agents *
153
+ (USD_PER_AGENT_BASE +
154
+ USD_PER_CHANGED_LINE * lines +
155
+ USD_PER_FILE * files) +
156
+ steps * USD_PER_AGENT_BASE;
157
+ return {
158
+ low: round2(mid * BAND_LOW),
159
+ high: round2(mid * BAND_HIGH),
160
+ basis:
161
+ "coarse band from measured runs (a 7-file / +21 −8 tree with 3 " +
162
+ "hunters + refuter, $3.92–$4.74 across two runs; a 45-file / " +
163
+ "+2775 −1237 tree with 5 hunters + refuter, ~$11–$14.78): a " +
164
+ "per-agent floor for hunters + refuter" +
165
+ `${summarizerEnabled ? " + summarizer" : ""}` +
166
+ `${scoutEnabled ? " + scout" : ""}` +
167
+ `${consolidateEnabled ? " + consolidation" : ""}` +
168
+ `${steps > 0 ? ` + ${steps} verification step(s)` : ""} ` +
169
+ "plus changed lines and files. An order-of-magnitude " +
170
+ "guide, not a quote — the same tree has billed 34% apart across runs.",
171
+ };
172
+ }
173
+
174
+ export interface ReportMeta {
175
+ repo: string;
176
+ base: string;
177
+ head: string;
178
+ // The stat of the EFFECTIVE diff — the one the hunters were handed, with
179
+ // generated content already excluded. Never the raw range's stat: a report
180
+ // that claims 5000 changed lines beside a review of 40 of them is lying
181
+ // about what was read.
182
+ diffStat: DiffStat;
183
+ // Paths the exclusion filter dropped from the reviewed diff, if any. Stated
184
+ // in the report because it is a mutation of the input, not a detail.
185
+ excludedPaths?: string[];
186
+ // CASH, and only cash — §8's "Budget enforcement uses cash only". A Claude
187
+ // subscription route reports a truthful $0.00 here.
188
+ costUsd: number;
189
+ // #173 (§8: "Artifacts and reports show cash and notional totals
190
+ // separately"). The list-basis figure the run was NOT charged. Absent means
191
+ // no segment at all, never a `$0.00` one — a runner that reported no
192
+ // normalized usage has no list figure, and printing one it never produced
193
+ // is the fabrication the usage slice exists to prevent.
194
+ notionalUsd?: number;
195
+ wallMs: number;
196
+ // S4: the mode the commit status is set under, which the closing note names.
197
+ // Absent means advisory: a local run, and any caller that never passes it,
198
+ // keeps today's wording byte-identical.
199
+ ciMode?: CiMode;
200
+ }
201
+
202
+ // What the report needs from a per-agent telemetry row. Telemetry.per_agent's
203
+ // DECLARED value type is the lab-shared minimum (tokens_total + duration_ms),
204
+ // but this engine writes the richer PerAgentUsage, which carries `status`.
205
+ // Read through a runtime check rather than widening the shared schema type:
206
+ // the report stays useful on a rich document AND on an old lab artifact that
207
+ // only ever had the two fields, and neither one throws.
208
+ interface AgentRow {
209
+ key: string;
210
+ status: string;
211
+ // Why a failed agent failed (PerAgentUsage.detail), when the run recorded it.
212
+ detail?: string;
213
+ }
214
+
215
+ function agentRows(doc: FindingsDocument): AgentRow[] {
216
+ const perAgent = doc.telemetry.per_agent;
217
+ if (!perAgent) return [];
218
+ return Object.entries(perAgent).map(([key, value]) => {
219
+ const { status, detail } = value as { status?: unknown; detail?: unknown };
220
+ return {
221
+ key,
222
+ status: typeof status === "string" ? status : "ran",
223
+ ...(typeof detail === "string" && detail.trim() !== ""
224
+ ? { detail: detail.trim() }
225
+ : {}),
226
+ };
227
+ });
228
+ }
229
+
230
+ // The coverage sentence behind every incompleteness notice (GitHub #42,
231
+ // ROADMAP-DOORDASH M1). Shared with ui/result.ts — exported for the same
232
+ // reason blobUrl below is: the public comment and the terminal must name the
233
+ // SAME agents from the SAME bytes, and two derivations of "who did not
234
+ // finish" is exactly how one surface starts under-reporting the other.
235
+ // `quote` is the only difference between them (backticks in markdown, bare
236
+ // text on a terminal), so the prose itself is written once.
237
+ //
238
+ // WHY "agents" and not "hunters", which is the word the issue uses: the
239
+ // document does not record roles. `telemetry.per_agent` is keyed by
240
+ // AgentSpec.key and carries a status, but nothing in it says which key was a
241
+ // hunter — the refuter and the summarizer sit in the same map (review/pipeline.ts
242
+ // writes `refuter` and `summary` rows there). Excluding those two keys by
243
+ // name would be a hardcoded list that (a) breaks the moment a spec renames
244
+ // the refuter and (b) would print "all hunters completed" on a run that went
245
+ // partial BECAUSE the refuter died, which is the under-disclosure this whole
246
+ // notice exists to prevent. So every agent is named, and the prose says
247
+ // agent. Over-naming costs a word; under-naming costs the guarantee.
248
+ //
249
+ // Statuses are printed VERBATIM rather than bucketed into failed/ok: an old
250
+ // lab artifact whose rows predate the `status` field reads as "ran"
251
+ // (agentRows' fallback), and bucketing that into "failed" would invent a
252
+ // failure the run never recorded.
253
+ export function coverageSentence(
254
+ doc: FindingsDocument,
255
+ quote: (key: string) => string,
256
+ ): string {
257
+ const rows = agentRows(doc);
258
+ const completed = rows.filter((r) => r.status === "ok").map((r) => r.key);
259
+ const lost = rows.filter((r) => r.status !== "ok");
260
+ // A partial run can name nobody at all, and the notice still has to be
261
+ // honest about that instead of printing an empty list: the gotchas
262
+ // early-return produces `run_status: "partial"` with an EMPTY per_agent map
263
+ // (review/pipeline.ts), a pipeline timeout abandons in-flight steps whose rows are
264
+ // never written, and a pre-v2 artifact has no per_agent at all. "Did not
265
+ // complete: (none)" on any of those would read as "everything ran".
266
+ const done =
267
+ completed.length === 0
268
+ ? "No agent is recorded as completed."
269
+ : `Completed: ${completed.map(quote).join(", ")}.`;
270
+ if (lost.length === 0) {
271
+ return `${done} The run record does not name which agents were lost.`;
272
+ }
273
+ return `${done} Did not complete: ${lostAgents(lost, quote)}.`;
274
+ }
275
+
276
+ // "refuter (failed — Anthropic API: …)": the status verbatim, then the provider's words when
277
+ // the run recorded them. `quote` wraps the detail too, so a markdown comment shows it as code
278
+ // and a mention or a link in the provider's text stays inert.
279
+ function lostAgents(
280
+ lost: readonly AgentRow[],
281
+ quote: (text: string) => string,
282
+ ): string {
283
+ return lost
284
+ .map(
285
+ (r) =>
286
+ `${quote(r.key)} (${r.status}${
287
+ r.detail === undefined ? "" : ` — ${quote(r.detail)}`
288
+ })`,
289
+ )
290
+ .join(", ");
291
+ }
292
+
293
+ // The workflow-command annotation for a review that did not finish everything: a partial run
294
+ // (the coverage sentence, which names who was lost and why), or a complete one whose
295
+ // summarizer or another non-gating step failed. Absent when every agent finished. One line:
296
+ // the message is escaped the way a workflow command needs (%, CR, LF).
297
+ export function incompleteReviewAnnotation(
298
+ doc: FindingsDocument,
299
+ ): string | undefined {
300
+ const lost = agentRows(doc).filter(
301
+ (r) => r.status === "failed" || r.status === "unsettled",
302
+ );
303
+ let message: string;
304
+ if (doc.run_status === "partial") {
305
+ message = `crysk: incomplete review. ${coverageSentence(doc, (key) => key)}`;
306
+ } else if (lost.length > 0) {
307
+ message = `crysk: the review is complete, but a step failed: ${lostAgents(lost, (text) => text)}.`;
308
+ } else {
309
+ return undefined;
310
+ }
311
+ const escaped = message
312
+ .replaceAll("%", "%25")
313
+ .replaceAll("\r", "%0D")
314
+ .replaceAll("\n", "%0A");
315
+ return `::warning title=crysk::${escaped}`;
316
+ }
317
+
318
+ // The one sentence behind every moved-head notice (GitHub #39,
319
+ // ROADMAP-DOORDASH M1), shared with ui/result.ts for coverageSentence's
320
+ // reason: the public comment and the terminal must name the SAME two shas
321
+ // from the SAME bytes, and `quote` is the only difference between them
322
+ // (backticks in markdown, bare text on a terminal).
323
+ //
324
+ // The wording is M1's own, kept recognizable on purpose — "reviewed `X`;
325
+ // head is now `Y`" is the whole reconciliation POLICY this slice owes. What
326
+ // a re-review should DO about findings computed on a stale head (re-verify,
327
+ // demote, discard) is ROADMAP item 7's design work and is deliberately NOT
328
+ // decided here; with `commit_id` pinned, GitHub anchors the comments to X
329
+ // and marks them outdated itself, so the only thing left to say is which
330
+ // commit the reader is looking at.
331
+ //
332
+ // Full 40-char shas, not the 8-char short form the headline uses: this is
333
+ // the line a reader takes to `git log` to see what landed in between, and a
334
+ // short sha is one paste-and-fail away from being useless.
335
+ export function movedHeadSentence(
336
+ reviewedSha: string,
337
+ currentSha: string,
338
+ quote: (text: string) => string,
339
+ ): string {
340
+ return (
341
+ `Reviewed ${quote(reviewedSha)}; the PR head is now ` +
342
+ `${quote(currentSha)}. Everything below describes the reviewed commit.`
343
+ );
344
+ }
345
+
346
+ type RenderableSummary = NonNullable<FindingsDocument["summary"]>;
347
+
348
+ function summaryLines(summary: RenderableSummary): string[] {
349
+ return [
350
+ "### Summary",
351
+ "",
352
+ oneLine(summary.prose),
353
+ "",
354
+ `**Confidence: ${summary.score}/5** — ${oneLine(summary.score_reason)}`,
355
+ ];
356
+ }
357
+
358
+ export function renderReport(doc: FindingsDocument, meta: ReportMeta): string {
359
+ const summary = doc.debug.root_causes ?? clusterByRootCause(doc.findings);
360
+ const out: string[] = [];
361
+ out.push(`# Review — ${meta.repo} ${meta.base}..${meta.head}`);
362
+ out.push("");
363
+ out.push(...runLines(doc, meta));
364
+ if (doc.summary !== undefined) {
365
+ out.push("");
366
+ out.push(...summaryLines(doc.summary));
367
+ }
368
+ out.push("");
369
+ out.push(...section("Blocking", doc, "blocking", summary));
370
+ out.push("");
371
+ out.push(...section("Advisory", doc, "advisory", summary));
372
+ out.push("");
373
+ out.push(...notReported(doc));
374
+ out.push("");
375
+ out.push(...closing(doc, meta.ciMode ?? "advisory"));
376
+ // Trailing newline: these strings are written straight to report.md, and a
377
+ // file without one makes every diff of a regenerated report noisy.
378
+ return `${out.join("\n").trimEnd()}\n`;
379
+ }
380
+
381
+ // The deterministic delta line (ROADMAP B6, design D5): computed by
382
+ // pr/inline.ts's matcher from the live comment stream, never from a stored
383
+ // count. `previousHeadSha` is the PRIOR summary marker's `head=` value — free
384
+ // because the marker already carries it — and is absent on the very first
385
+ // run (no prior marked comment exists yet) or against a pre-B3 markerless
386
+ // comment (no `head=` to parse). Both cases render the counts WITHOUT a
387
+ // "since <sha>" clause rather than omitting the line: spec's own "First-ever
388
+ // run" scenario requires `0 resolved · K new · 0 persist` to be visible, not
389
+ // silent, on the first post.
390
+ export interface RereviewLiveRow {
391
+ id: string;
392
+ sev: RecoveredSeverity;
393
+ status: string;
394
+ locs: readonly string[];
395
+ claim: string;
396
+ }
397
+
398
+ export interface RereviewDelta {
399
+ verifiedGone: number;
400
+ unconfirmed: number;
401
+ carried: number;
402
+ deferred: number;
403
+ new: number;
404
+ suppressed: number;
405
+ returned: number;
406
+ reTiered: number;
407
+ live?: readonly RereviewLiveRow[];
408
+ capped?: number;
409
+ case?: string;
410
+ worsened?: readonly {
411
+ priorId: string;
412
+ priorSev: RecoveredSeverity;
413
+ discoverySev: Severity;
414
+ }[];
415
+ // GitHub #166: this run's discovery found nothing to look at (case B's
416
+ // same-head re-review, or case C's restricted delta touching none of the
417
+ // PR's own files) — zero DISCOVERY hunters ran (a verifier may still have
418
+ // run — see `queuedForVerification` handling in `skippedDiscoveryMessage`,
419
+ // rereview/plan.ts). Mirrors `RereviewProvenance.discovery_skipped_empty_delta`
420
+ // (rereview/prepare.ts), which used to be computed and threaded onto the
421
+ // artifact but never READ by this renderer — the gap that let a $0/0s skip
422
+ // publish "pr-hero reviewed this PR and found nothing to report" over a
423
+ // real prior summary.
424
+ discoverySkippedEmptyDelta?: boolean;
425
+ // pr-hero review #286 finding: `discoverySkippedEmptyDelta` alone cannot
426
+ // say WHY discovery came up empty, and "no changes since the last review"
427
+ // is false for the other reason — see `RereviewProvenance.discovery_skip_reason`'s
428
+ // own WHY (rereview/prepare.ts). Absent/`"no_delta"` renders the original
429
+ // wording; `"all_excluded"` MUST name what was excluded instead.
430
+ discoverySkipReason?: "no_delta" | "all_excluded";
431
+ discoveryExcludedPaths?: readonly string[];
432
+ }
433
+
434
+ export interface PrCommentDelta {
435
+ resolved: number;
436
+ new: number;
437
+ persist: number;
438
+ previousHeadSha?: string;
439
+ // Item 7: when present, deltaLine and the clean-bill gate read THIS, not
440
+ // MatchResult.resolved (C2, R2-S6). Absent keeps first-review rendering
441
+ // byte-identical.
442
+ rereview?: RereviewDelta;
443
+ }
444
+
445
+ // `row.sev` arrives typed `string` here (this reader also serves raw
446
+ // pipeline.json data, see rereview/prepare.ts's readRereviewProvenance) —
447
+ // never widen an unrecognized string INTO a real Severity by casting.
448
+ // Anything that is not one of the 4 real values or the sentinel itself
449
+ // degrades to the sentinel: the WARNING-default this replaces is #206's own
450
+ // bug, restated for the read-back path instead of the build path.
451
+ function asRecoveredSeverity(sev: string | undefined): RecoveredSeverity {
452
+ switch (sev) {
453
+ case "BLOCKER":
454
+ case "CRITICAL":
455
+ case "WARNING":
456
+ case "SUGGESTION":
457
+ return sev;
458
+ default:
459
+ return SEVERITY_UNRECOVERABLE;
460
+ }
461
+ }
462
+
463
+ export function rereviewDeltaFromProvenance(
464
+ rereview: {
465
+ case?: string;
466
+ live: readonly {
467
+ id?: string;
468
+ sev?: string;
469
+ status: string;
470
+ locs?: readonly string[];
471
+ claim?: string;
472
+ }[];
473
+ resolved_verified?: number;
474
+ verification_capped?: number;
475
+ returned?: number;
476
+ re_tiered?: number;
477
+ worsened?: readonly {
478
+ priorId: string;
479
+ priorSev: RecoveredSeverity;
480
+ discoverySev: Severity;
481
+ }[];
482
+ // Optional, not `RereviewProvenance`'s required boolean: this structural
483
+ // type is also satisfied by hand-built test fixtures and older
484
+ // pipeline.json reads that never carried the field (schema tolerance).
485
+ discovery_skipped_empty_delta?: boolean;
486
+ // Same optionality reasoning, for the pr-hero review #286 fields — an
487
+ // artifact written before that fix has neither.
488
+ discovery_skip_reason?: "no_delta" | "all_excluded";
489
+ discovery_excluded_paths?: readonly string[];
490
+ },
491
+ newFindings: number,
492
+ ): RereviewDelta {
493
+ const count = (status: string): number =>
494
+ rereview.live.filter((row) => row.status === status).length;
495
+ return {
496
+ verifiedGone: rereview.resolved_verified ?? 0,
497
+ unconfirmed: count("unconfirmed"),
498
+ carried: count("carried"),
499
+ deferred: count("deferred"),
500
+ new: newFindings,
501
+ suppressed: count("suppressed"),
502
+ returned: rereview.returned ?? 0,
503
+ reTiered: rereview.re_tiered ?? 0,
504
+ live: rereview.live.map((row) => ({
505
+ id: row.id ?? "",
506
+ sev: asRecoveredSeverity(row.sev),
507
+ status: row.status,
508
+ locs: row.locs ?? [],
509
+ claim: row.claim ?? "",
510
+ })),
511
+ capped: rereview.verification_capped ?? 0,
512
+ ...(rereview.case === undefined ? {} : { case: rereview.case }),
513
+ ...(rereview.worsened === undefined ? {} : { worsened: rereview.worsened }),
514
+ ...(rereview.discovery_skipped_empty_delta === true
515
+ ? { discoverySkippedEmptyDelta: true }
516
+ : {}),
517
+ ...(rereview.discovery_skip_reason === undefined
518
+ ? {}
519
+ : { discoverySkipReason: rereview.discovery_skip_reason }),
520
+ ...(rereview.discovery_excluded_paths === undefined ||
521
+ rereview.discovery_excluded_paths.length === 0
522
+ ? {}
523
+ : { discoveryExcludedPaths: rereview.discovery_excluded_paths }),
524
+ };
525
+ }
526
+
527
+ // One consistent severity → emoji mapping (Juanma's PR #2 feedback), shared
528
+ // by the summary's headline/index AND every per-finding body — a reader
529
+ // who learns 🔴 means BLOCKER/CRITICAL in one place must see the SAME
530
+ // mapping everywhere, or the emoji becomes noise instead of a scan aid.
531
+ // BLOCKER and CRITICAL share one glyph on purpose: both are the severities
532
+ // that can ever reach `tier: "blocking"` (deriveTier, review/findings.ts), so this
533
+ // is the same grouping the engine's own gate already makes. Used by the
534
+ // summary HEADLINE, which still counts by hunter severity (PR #2: a
535
+ // tier-based "0 blocking" hid that both findings were genuinely CRITICAL).
536
+ export function severityEmoji(severity: Severity): string {
537
+ switch (severity) {
538
+ case "BLOCKER":
539
+ case "CRITICAL":
540
+ return "🔴";
541
+ case "WARNING":
542
+ return "🟡";
543
+ case "SUGGESTION":
544
+ return "🔵";
545
+ }
546
+ }
547
+
548
+ // GitHub #19 W0: the posted scan aid follows `tier`, not hunter severity.
549
+ // A BLOCKER/CRITICAL that deriveTier already made advisory must not scream
550
+ // 🔴 — that glyph is reserved for findings that can still block. SUGGESTION
551
+ // keeps its own 🔵 so hygiene stays distinct from a real-but-not-blocking
552
+ // WARNING (or a demoted CRITICAL). Does not change what was found; the
553
+ // hunter's severity word still sits in the header after the tier.
554
+ export function scanAidEmoji(
555
+ finding: Pick<Finding, "severity" | "tier">,
556
+ ): string {
557
+ if (finding.tier === "blocking") return "🔴";
558
+ if (finding.severity === "SUGGESTION") return "🔵";
559
+ return "🟡";
560
+ }
561
+
562
+ // Priority order for the summary's compact index (Juanma: "priority ordering
563
+ // actually works" here — inline comments themselves sort by GitHub's own
564
+ // file/line order, not ours). Lower rank sorts first.
565
+ function severityRank(severity: Severity): number {
566
+ switch (severity) {
567
+ case "BLOCKER":
568
+ return 0;
569
+ case "CRITICAL":
570
+ return 1;
571
+ case "WARNING":
572
+ return 2;
573
+ case "SUGGESTION":
574
+ return 3;
575
+ }
576
+ }
577
+
578
+ const LEAD_IN_MAX = 100;
579
+
580
+ // A short, single-line preview of a finding's claim for the summary's
581
+ // index — the claim's full text belongs on the finding's own comment, not
582
+ // duplicated here (the ROADMAP B6 "one finding, one place" decision this
583
+ // index partially reinstates — see renderPrComment's own WHY). Truncates at
584
+ // a word boundary so the ellipsis never lands mid-word.
585
+ function leadIn(claim: string): string {
586
+ const text = oneLine(claim);
587
+ if (text.length <= LEAD_IN_MAX) return text;
588
+ const truncated = text.slice(0, LEAD_IN_MAX);
589
+ const lastSpace = truncated.lastIndexOf(" ");
590
+ const cut = lastSpace > 40 ? truncated.slice(0, lastSpace) : truncated;
591
+ return `${cut}…`;
592
+ }
593
+
594
+ // What a live row prints where its claim would go when there is no claim to
595
+ // print. A prior rebuilt from a posted `<!-- pr-hero-finding -->` marker
596
+ // carries none: the marker never stored one, and `priorsFromPostedMarkers`
597
+ // (rereview/prepare.ts) sets `claim: ""` DELIBERATELY so `claimFingerprint("")`
598
+ // — the single constant every claim-less prior shares — can never act as a
599
+ // tie-break in prior→comment matching (that module's WHY at :534, :570-578
600
+ // and :736-745). That limitation is intentional and stays; what was broken is
601
+ // the RENDER. `leadIn("")` returns "", so the row printed its separator with
602
+ // nothing after it — "- `carried` 🟡 `src/wizard.ts:721` — (R002)" on PR
603
+ // #179's second review — which reads as a finding whose description is empty
604
+ // rather than one whose claim this surface simply cannot recover. Italic, so
605
+ // it cannot be mistaken for the claim itself, and it says nothing about
606
+ // status or severity: those are on the same line and are known. The reader
607
+ // keeps the location and the id, and the finding's OWN comment — the thing
608
+ // the marker was parsed out of — does carry the claim.
609
+ const CLAIM_UNAVAILABLE =
610
+ "_claim text unavailable; see this finding's own comment on the PR_";
611
+
612
+ // `leadIn` is left alone on purpose: every non-empty claim renders exactly as
613
+ // it did, byte for byte.
614
+ function liveClaimText(claim: string): string {
615
+ const text = leadIn(claim);
616
+ return text === "" ? CLAIM_UNAVAILABLE : text;
617
+ }
618
+
619
+ // The summary's one-line-per-finding index (Juanma's PR #2 feedback item 1:
620
+ // the earlier "one finding, one place" decision stripped this list entirely,
621
+ // leaving counts + delta + footer — on first contact that reads as empty).
622
+ // This partially reverses that decision, but the coherence obligation it
623
+ // reinstates is much smaller than the pre-B6 shape: a ONE-LINE index plus
624
+ // links, not a duplicated claim/evidence body, and the delta already had to
625
+ // be correct. `commentUrlByFindingId` is absent (or a finding's id is
626
+ // missing from it) before ids exist — the FIRST render of a freshly created
627
+ // summary, before any per-finding comment has been posted — in which case
628
+ // the line renders without a link; the closing PATCH (cli.ts) supplies the
629
+ // map once posting has happened.
630
+ function findingIndexLines(
631
+ findings: Finding[],
632
+ commentUrlByFindingId: ReadonlyMap<string, string> | undefined,
633
+ ): string[] {
634
+ const sorted = [...findings].sort((a, b) => {
635
+ const rankDiff = severityRank(a.severity) - severityRank(b.severity);
636
+ if (rankDiff !== 0) return rankDiff;
637
+ if (a.path !== b.path) return a.path < b.path ? -1 : 1;
638
+ return a.line - b.line;
639
+ });
640
+ return sorted.map((f) => {
641
+ const loc = code(`${f.path}:${f.line}`);
642
+ const url = commentUrlByFindingId?.get(f.id);
643
+ const locRef = url === undefined ? loc : `[${loc}](${url})`;
644
+ return `${scanAidEmoji(f)} ${locRef} — ${leadIn(f.claim)}`;
645
+ });
646
+ }
647
+
648
+ // The PR-comment renderer (ROADMAP B2): the same findings document, shaped
649
+ // for a public GitHub comment instead of a run artifact. Pure for the same
650
+ // reason renderReport is — a posted comment must be re-renderable from the
651
+ // artifact and come out identical.
652
+ //
653
+ // Deliberately SPARSER than report.md: NO cost, NO token counts, no
654
+ // telemetry of any kind — the engine's internal economics never reach a
655
+ // public comment.
656
+ //
657
+ // The first line is the pr-hero marker carrying doc.head_sha: postPrComment
658
+ // (pr/pr.ts) finds the previous comment by the marker PREFIX and updates it in
659
+ // place, so this renderer and that finder share one contract and posting
660
+ // stays idempotent — while the declared head lets the watch guard (B3) tell
661
+ // which head a posted comment covers.
662
+ //
663
+ // The summary line (not the footer) names the exact range reviewed:
664
+ // doc.base_sha IS the diff-from commit — the recorded rule in cli.ts.
665
+ //
666
+ // `repoWebUrl` (e.g. https://github.com/org/repo) turns locations into
667
+ // links pinned to doc.head_sha. It is OPTIONAL and cosmetic by contract:
668
+ // absent, the comment renders as plain code spans, byte-identical to the
669
+ // linkless shape — the renderer stays offline-testable and a posted comment
670
+ // stays re-renderable from the artifact alone.
671
+ //
672
+ // ROADMAP B6 reshape, W2 (issues #16/#17): the index stays one-liners;
673
+ // anchorable findings live on the review; un-anchorable (and 422-demoted)
674
+ // findings render their full body in this summary's Comments Outside Diff
675
+ // section, never as standalone issue comments. `delta`
676
+ // may be absent — a caller with no prior-state knowledge (or a same-run
677
+ // first post) still gets a valid comment, just without the delta line —
678
+ // but the PARAMETER itself is REQUIRED, not optional (PR2 verification
679
+ // WARN-3, same fix shape as `consumedCommentIds` on `postPrReview`,
680
+ // a3b3d3a): an optional third argument is one a PR3 wiring call can
681
+ // simply forget, and the summary would then render silently without the
682
+ // delta line spec R13 requires. `delta: PrCommentDelta | undefined`
683
+ // forces every call site to say so explicitly, so the type system — not a
684
+ // missed review comment — catches the omission.
685
+ // `outsideDiffFindings` is the same WARN-3 shape: REQUIRED, not optional.
686
+ // An optional fourth argument is one a caller can forget, and the summary
687
+ // would then silently omit the Outside Diff bucket those findings reached.
688
+ // Pass `[]` when there are none — the section is omitted only when the
689
+ // array is empty, never because a call site skipped the argument.
690
+ // `commentUrlByFindingId` stays the last, OPTIONAL parameter (ROADMAP B6
691
+ // rework, Juanma's PR #2 feedback): a finding id → its own posted
692
+ // review-comment URL, so the index above can link straight to it. Absent
693
+ // on the summary's FIRST creation (pr/pr.ts creates the summary BEFORE any
694
+ // per-finding comment exists, to fix its position in the PR timeline —
695
+ // see pr/pr.ts's postInlineFindings WHY) and present on the closing PATCH
696
+ // once posting finished. Un-anchorable findings have no review-comment
697
+ // URL; their index line stays unlinked and the bucket below has the full
698
+ // body. A caller that omits the map gets a correct, link-free index —
699
+ // never a broken or empty one — so this stays additive, unlike `delta`
700
+ // and `outsideDiffFindings` above: a missing link map degrades the
701
+ // index's usefulness, it does not make the comment lie.
702
+ //
703
+ // `movedHeadSha` (GitHub #39) is REQUIRED `string | undefined`, on `delta`'s
704
+ // side of that dividing line rather than `commentUrlByFindingId`'s, and it
705
+ // sits BEFORE the link map so the type system says so. It is the PR's head
706
+ // as GitHub reported it moments before posting, and it is set ONLY on a
707
+ // confirmed mismatch with `doc.head_sha` — the caller does the comparison
708
+ // once (pr/pr.ts's postInlineFindings) so two surfaces cannot derive two
709
+ // different answers from it, and this renderer is dumb: present means moved,
710
+ // absent means unmoved OR unverifiable. An issue-mandated element whose
711
+ // omission is SILENT is exactly the argument that made `delta` required; a
712
+ // caller that forgot this one would publish a comment about code the PR no
713
+ // longer has, with nothing on the page saying so.
714
+ export function renderPrComment(
715
+ doc: FindingsDocument,
716
+ repoWebUrl: string | undefined,
717
+ delta: PrCommentDelta | undefined,
718
+ outsideDiffFindings: readonly Finding[],
719
+ movedHeadSha: string | undefined,
720
+ commentUrlByFindingId?: ReadonlyMap<string, string>,
721
+ // S4: the footer's disclaimer follows the gate mode. Omitted means advisory,
722
+ // the wording every caller has today, until a caller passes its mode.
723
+ ciMode: CiMode = "advisory",
724
+ // S1b: Outside Diff entries at this index and after render compact (the
725
+ // linked location only). WHY an index and not a flag: the size fallback
726
+ // compacts from the last entry backwards, one entry at a time, until the
727
+ // body fits. Omitted or past the end, the section is byte-identical.
728
+ compactFrom?: number,
729
+ ): string {
730
+ // Normalize away one trailing slash so `gh repo view` output and a
731
+ // hand-typed URL build the same links.
732
+ const webUrl = repoWebUrl?.endsWith("/")
733
+ ? repoWebUrl.slice(0, -1)
734
+ : repoWebUrl;
735
+ // Counted by SEVERITY, not tier (Juanma's PR #2 feedback item 3: the old
736
+ // tier-based "0 blocking · 2 advisory" headline hid that both findings
737
+ // were actually CRITICAL, just downgraded — the exact contradiction that
738
+ // made "CRITICAL (advisory)" read as a bug on the finding body itself).
739
+ // SUGGESTION is deliberately excluded from the headline, mirroring the
740
+ // two-bucket 🔴/🟡 shape Juanma specified — a SUGGESTION still appears in
741
+ // the index below, just not double-counted in the headline.
742
+ const liveRows = delta?.rereview?.live ?? [];
743
+ const liveForHeadline = liveRows.filter((row) => row.status !== "suppressed");
744
+ const headlineSev = [
745
+ ...doc.findings.map((f) => f.severity),
746
+ ...liveForHeadline.map((row) => row.sev),
747
+ ];
748
+ const critical = headlineSev.filter(
749
+ (sev) => sev === "BLOCKER" || sev === "CRITICAL",
750
+ ).length;
751
+ const warning = headlineSev.filter((sev) => sev === "WARNING").length;
752
+ // #206: a carried prior whose real severity could not be recovered must
753
+ // never fall into `warning` by default — that IS the bug (a live BLOCKER
754
+ // rendering as "0 critical · 1 warning"). It also must not vanish from the
755
+ // headline entirely: silence here would just move the undercount from
756
+ // "wrong bucket" to "no bucket", still hiding that something needs a
757
+ // human's eyes. So it gets its own headline term instead.
758
+ const severityUnavailable = headlineSev.filter(
759
+ (sev) => sev === SEVERITY_UNRECOVERABLE,
760
+ ).length;
761
+ const headSha8 = code(doc.head_sha.slice(0, 8));
762
+ const headRef =
763
+ webUrl === undefined
764
+ ? headSha8
765
+ : `[${headSha8}](${webUrl}/commit/${doc.head_sha})`;
766
+ // The marker keeps carrying the REVIEWED head, never `movedHeadSha`
767
+ // (GitHub #39): the watch guard (B3) reads this marker to learn which head
768
+ // a posted comment covers, and writing the CURRENT head here would tell the
769
+ // watcher that the new head was reviewed — the same silent lie the pin and
770
+ // the notice below exist to kill, just relocated into the machine-readable
771
+ // half of the comment.
772
+ // Rereview-coverage fix: a PARTIAL run's marker carries the
773
+ // coverage=partial token so the NEXT `pr-hero review --pr N` can tell (via
774
+ // parsePrCommentMarker) that this run never finished and must not trust
775
+ // L===H the way a clean case B/C would. A COMPLETE run's marker stays
776
+ // byte-identical to before — the self-healing property: a forced-full
777
+ // re-run that is ITSELF partial writes coverage=partial again, so coverage
778
+ // stays forced until a run actually completes.
779
+ const out: string[] = [
780
+ prCommentMarker(doc.head_sha, doc.run_status !== "partial"),
781
+ ];
782
+ out.push("## Crysk review");
783
+ out.push("");
784
+ // GitHub #39, and it goes FIRST — above the #42 incompleteness notice and
785
+ // therefore above everything. The two notices qualify different things and
786
+ // the order follows the scope of what they qualify: this one says WHICH
787
+ // CODE the whole comment describes (the coverage sentence below included),
788
+ // #42's says how much of that code was actually looked at. A reader who
789
+ // learns on line 9 that the counts are a floor, and only on line 12 that
790
+ // they were computed against a commit the PR no longer points at, has read
791
+ // the two in the wrong order.
792
+ //
793
+ // Set only on a CONFIRMED mismatch (cli.ts re-reads the head immediately
794
+ // before posting and compares once). Unmoved and unverifiable both render
795
+ // nothing, and neither is a lie: the headline below names the reviewed sha
796
+ // outright and never claims it is current, so silence here says "nothing
797
+ // to add", not "this is the head".
798
+ if (movedHeadSha !== undefined) {
799
+ out.push(
800
+ "⚠️ **The PR moved while this review ran.** The comments are pinned to " +
801
+ "the commit that was reviewed, so GitHub will mark them outdated as " +
802
+ "the lines move; they are not a statement about the current head.",
803
+ );
804
+ out.push("");
805
+ out.push(movedHeadSentence(doc.head_sha, movedHeadSha, code));
806
+ out.push("");
807
+ }
808
+ if (delta?.rereview?.case === "D") {
809
+ out.push(
810
+ "⚠️ **Last reviewed head is not an ancestor of this head.** " +
811
+ "Reviewing the full PR range (force-push / rebase / amend).",
812
+ );
813
+ out.push("");
814
+ }
815
+ if ((delta?.rereview?.capped ?? 0) > 0) {
816
+ out.push(
817
+ `⚠️ **${delta?.rereview?.capped} prior finding(s) not verified:** ` +
818
+ "verification cap (`max_verification_steps`) bound this run (a dismissed or deferred one keeps its triage); " +
819
+ "`--yes` does not bypass it.",
820
+ );
821
+ out.push("");
822
+ }
823
+ // GitHub #42. The defect: a run where SOME agents died and the survivors
824
+ // found nothing posted "🔴 0 critical · 🟡 0 warning" followed by a ✅ clean
825
+ // bill, and the only trace of the incompleteness was the word `partial`
826
+ // inside the <sub> footer at the very bottom. A reader takes a green check
827
+ // at face value; nobody audits a footer.
828
+ //
829
+ // So the notice goes ABOVE the counts, not below them and not in the
830
+ // footer: the counts are the thing being qualified, and a qualifier a
831
+ // reader meets after the number it qualifies has already done its damage.
832
+ //
833
+ // The decision the issue left open — should such a run post at all — is
834
+ // POST (Juanma, ROADMAP-DOORDASH M1): "post, stating the incompleteness and
835
+ // naming the hunters that did not run — visible noise beats invisible
836
+ // loss". Direction of error: posting nothing hides that a review was even
837
+ // attempted, and an invisible loss is the failure this project's own rule
838
+ // ranks worst; a loud incomplete notice is merely noisy, and noise can be
839
+ // read and dismissed. The two extremes stay where they were — every agent
840
+ // dead is `sessionFailed` and never posts (cli.ts), a complete run keeps
841
+ // its ✅ untouched. This is the middle case only.
842
+ //
843
+ // Unconditional on `partial`, NOT gated on zero findings: a partial run
844
+ // that found three things is also reporting a floor, not a verdict. The
845
+ // zero-findings branch below is only where the ✅ has to be replaced.
846
+ if (doc.run_status === "partial") {
847
+ out.push(
848
+ "⚠️ **This review is incomplete.** At least one agent did not finish, " +
849
+ "so the counts below are a floor, not a verdict: whatever the " +
850
+ "missing agents would have found is missing with them.",
851
+ );
852
+ out.push("");
853
+ out.push(coverageSentence(doc, code));
854
+ out.push("");
855
+ }
856
+ out.push(
857
+ `🔴 ${critical} critical · 🟡 ${warning} warning` +
858
+ (severityUnavailable > 0
859
+ ? ` · ⚠️ ${severityUnavailable} severity unavailable`
860
+ : "") +
861
+ ` — ${headRef}, diff from ${code(doc.base_sha.slice(0, 8))}`,
862
+ );
863
+ out.push("");
864
+ if (doc.summary !== undefined) {
865
+ out.push(...summaryLines(doc.summary));
866
+ out.push("");
867
+ }
868
+ if (doc.findings.length === 0) {
869
+ // The ✅ is a statement about COVERAGE, not about the findings array: it
870
+ // claims every hunter looked and nobody found anything. On a partial run
871
+ // that claim is false, so the glyph is withdrawn and the line points back
872
+ // at the notice above rather than leaving the body to jump from a zero
873
+ // count straight to the footer (GitHub #42).
874
+ //
875
+ // Item 7 C7: zero new findings is also not a clean bill when priors
876
+ // remain live (carried / unconfirmed / deferred / suppressed) or this
877
+ // run returned / re-tiered a prior. MatchResult.resolved cannot say so.
878
+ out.push(cleanBillLine(doc.run_status, delta?.rereview));
879
+ out.push("");
880
+ } else {
881
+ out.push(...findingIndexLines(doc.findings, commentUrlByFindingId));
882
+ out.push("");
883
+ }
884
+ out.push(...liveFindingLines(delta?.rereview));
885
+ if (outsideDiffFindings.length > 0) {
886
+ out.push(
887
+ ...outsideDiffSection(
888
+ outsideDiffFindings,
889
+ doc.head_sha,
890
+ webUrl,
891
+ compactFrom,
892
+ ),
893
+ );
894
+ out.push("");
895
+ }
896
+ // Omit the "since <sha>" clause when the previous head equals the current
897
+ // one (Juanma's PR #2 feedback: "Δ since f933fda8" printed on head
898
+ // f933fda8 is noise) — a re-run on an unchanged head, not a genuinely
899
+ // absent prior state (which deltaLine already renders bare).
900
+ const normalizedDelta =
901
+ delta && delta.previousHeadSha === doc.head_sha
902
+ ? { ...delta, previousHeadSha: undefined }
903
+ : delta;
904
+ if (normalizedDelta) {
905
+ out.push(deltaLine(normalizedDelta));
906
+ out.push("");
907
+ }
908
+ out.push("---");
909
+ out.push("");
910
+ // The footer keeps the report's public register: a comment that says
911
+ // "blocking" without the not-a-merge-gate sentence would overstate the
912
+ // tool's own contract. Comment voice: no em dashes in prose — the
913
+ // disclaimer joins with a colon.
914
+ out.push(
915
+ `<sub>run ${doc.run_status} · ${engineLabel(doc)} · ${commentDisclaimer(ciMode)}</sub>`,
916
+ );
917
+ return `${out.join("\n").trimEnd()}\n`;
918
+ }
919
+
920
+ function liveFindingLines(rereview: RereviewDelta | undefined): string[] {
921
+ if (rereview === undefined) return [];
922
+ const out: string[] = [];
923
+ if (rereview.worsened !== undefined && rereview.worsened.length > 0) {
924
+ for (const hit of rereview.worsened) {
925
+ out.push(
926
+ `returned ${hit.priorId}: ${hit.priorSev} → ${hit.discoverySev}`,
927
+ );
928
+ }
929
+ out.push("");
930
+ }
931
+ const listed = (rereview.live ?? []).filter(
932
+ (row) => row.status !== "suppressed",
933
+ );
934
+ if (listed.length > 0) {
935
+ out.push("Still live:");
936
+ for (const row of listed) {
937
+ const loc = row.locs[0] ?? row.id;
938
+ // #206: never run an unrecoverable severity through severityEmoji —
939
+ // its 4-case switch has no branch for the sentinel, and reusing 🟡 by
940
+ // accident is exactly the silent downgrade this issue is about. A
941
+ // distinct glyph AND word, never one of 🔴/🟡/🔵, so the row cannot be
942
+ // mistaken for a real (if low) severity.
943
+ const badge =
944
+ row.sev === SEVERITY_UNRECOVERABLE
945
+ ? "⚠️ severity unavailable"
946
+ : severityEmoji(row.sev);
947
+ out.push(
948
+ `- \`${row.status}\` ${badge} \`${loc}\` — ${liveClaimText(row.claim)} (${row.id})`,
949
+ );
950
+ }
951
+ out.push("");
952
+ }
953
+ if (rereview.suppressed > 0) {
954
+ out.push(
955
+ `${rereview.suppressed} finding${rereview.suppressed === 1 ? "" : "s"} suppressed.`,
956
+ );
957
+ out.push("");
958
+ }
959
+ return out;
960
+ }
961
+
962
+ function rereviewIsClean(rereview: RereviewDelta | undefined): boolean {
963
+ if (rereview === undefined) return true;
964
+ return (
965
+ rereview.unconfirmed === 0 &&
966
+ rereview.carried === 0 &&
967
+ rereview.deferred === 0 &&
968
+ rereview.suppressed === 0 &&
969
+ rereview.returned === 0 &&
970
+ rereview.reTiered === 0
971
+ );
972
+ }
973
+
974
+ // Shared by both non-clean cleanBillLine branches below (the ordinary
975
+ // re-review one and the skipped-discovery one, GitHub #166) so the two
976
+ // wordings can never drift on what "live" means.
977
+ function liveBits(rereview: RereviewDelta): string[] {
978
+ const bits: string[] = [];
979
+ if (rereview.carried > 0) bits.push(`${rereview.carried} carried`);
980
+ if (rereview.unconfirmed > 0)
981
+ bits.push(`${rereview.unconfirmed} unconfirmed`);
982
+ if (rereview.deferred > 0) bits.push(`${rereview.deferred} deferred`);
983
+ if (rereview.suppressed > 0) bits.push(`${rereview.suppressed} suppressed`);
984
+ if (rereview.returned > 0) bits.push(`${rereview.returned} returned`);
985
+ if (rereview.reTiered > 0) bits.push(`${rereview.reTiered} re-tiered`);
986
+ return bits;
987
+ }
988
+
989
+ // pr-hero review #286 finding: `discoverySkippedEmptyDelta` alone cannot say
990
+ // WHY discovery is empty, and "no changes" was flatly wrong for the OTHER
991
+ // reason it can be set — a real, non-empty delta whose every file was
992
+ // excluded by the size gate / `.prheroignore` (`filterDiffByIgnoreRules`'s
993
+ // `droppedPaths`, threaded as `discoveryExcludedPaths`). This picks the
994
+ // sentence the data actually supports; it never says "nothing changed" when
995
+ // something plainly did.
996
+ function discoverySkipSentence(rereview: RereviewDelta): string {
997
+ if (rereview.discoverySkipReason === "all_excluded") {
998
+ const paths = rereview.discoveryExcludedPaths ?? [];
999
+ const named = paths.length > 0 ? ` (${listPaths([...paths])})` : "";
1000
+ return `Every changed file was excluded from review${named}, so the effective diff is empty.`;
1001
+ }
1002
+ return "No changes since the last review of this head.";
1003
+ }
1004
+
1005
+ // GitHub #166, corrected by pr-hero review #286: a re-review whose discovery
1006
+ // skipped for lack of anything new (case B's same head, or case C's
1007
+ // restricted delta touching none of the PR's own files — or, per the
1008
+ // sentence above, a real delta excluded entirely) ran ZERO DISCOVERY
1009
+ // hunters — the two branches below both describe what a review CONCLUDED,
1010
+ // and this run concluded nothing from discovery; it never looked. That is
1011
+ // still all this function may claim:
1012
+ //
1013
+ // - it must never say "hunter" unqualified, since a VERIFIER can still run
1014
+ // in the same pass (case B's `applied`/`case_b_reply` triggers, case C's
1015
+ // `touched()` — rereview/classify.ts) and did not run zero of anything;
1016
+ // - it must never claim what "the last review reported" — this run only
1017
+ // ever reads the CARRIED state (`rereview.live[]` and `verifiedGone`), not
1018
+ // the last review's own content, so every sentence stays grounded in that;
1019
+ // - `verifiedGone` (review #286's third finding) MUST gate the "nothing to
1020
+ // report" framing: `rereviewIsClean` alone ignores it, and a run whose
1021
+ // verifier resolved every prior this pass is not "nothing happened" — it
1022
+ // is a resolution, and erasing it would repeat the same class of false
1023
+ // clean bill #166 reported in the first place.
1024
+ function skippedDiscoveryCleanBillLine(rereview: RereviewDelta): string {
1025
+ const sentences: string[] = [
1026
+ discoverySkipSentence(rereview),
1027
+ "No discovery hunter ran this pass.",
1028
+ ];
1029
+ if (rereview.verifiedGone > 0) {
1030
+ sentences.push(
1031
+ `${rereview.verifiedGone} prior finding${rereview.verifiedGone === 1 ? "" : "s"} ` +
1032
+ "resolved (verified) this pass.",
1033
+ );
1034
+ }
1035
+ const bits = liveBits(rereview);
1036
+ if (bits.length > 0) {
1037
+ sentences.push(`Still live: ${bits.join(" · ")}.`);
1038
+ }
1039
+ if (sentences.length === 2) {
1040
+ sentences.push("No live findings are carried from the previous review.");
1041
+ }
1042
+ return sentences.join(" ");
1043
+ }
1044
+
1045
+ function cleanBillLine(
1046
+ runStatus: FindingsDocument["run_status"],
1047
+ rereview: RereviewDelta | undefined,
1048
+ ): string {
1049
+ if (runStatus === "partial") {
1050
+ return (
1051
+ "The agents that completed reported nothing. That is not a clean " +
1052
+ "bill: read it against the coverage above."
1053
+ );
1054
+ }
1055
+ if (rereview?.discoverySkippedEmptyDelta === true) {
1056
+ return skippedDiscoveryCleanBillLine(rereview);
1057
+ }
1058
+ if (!rereviewIsClean(rereview) && rereview !== undefined) {
1059
+ return `No new findings this delta. Live: ${liveBits(rereview).join(" · ")}.`;
1060
+ }
1061
+ return "✅ Crysk reviewed this PR and found nothing to report.";
1062
+ }
1063
+
1064
+ function deltaLine(delta: PrCommentDelta): string {
1065
+ const since =
1066
+ delta.previousHeadSha === undefined
1067
+ ? "Δ"
1068
+ : `Δ since ${code(delta.previousHeadSha.slice(0, 8))}`;
1069
+ if (delta.rereview !== undefined) {
1070
+ const r = delta.rereview;
1071
+ const parts: string[] = [];
1072
+ if (r.verifiedGone > 0) {
1073
+ parts.push(`${r.verifiedGone} resolved (verified)`);
1074
+ }
1075
+ parts.push(`${r.unconfirmed} unconfirmed`);
1076
+ parts.push(`${r.carried} carried`);
1077
+ parts.push(`${r.deferred} deferred`);
1078
+ parts.push(`${r.new} new`);
1079
+ return `${since}: ${parts.join(" · ")}`;
1080
+ }
1081
+ return `${since}: ${delta.resolved} resolved · ${delta.new} new · ${delta.persist} persist`;
1082
+ }
1083
+
1084
+ // The re-review closing comment (pr/pr.ts's postInlineFindings): a short,
1085
+ // NEW issue comment posted after the summary's closing PATCH. The summary is
1086
+ // edited in place on a re-review, and an edit is invisible on GitHub (no
1087
+ // notification, no move down the timeline), so without this a clean
1088
+ // re-review looked exactly like a run that never happened. The delta line is
1089
+ // the summary's own `deltaLine`, so the two comments cannot disagree on the
1090
+ // numbers.
1091
+ export function renderRereviewClosedComment(input: {
1092
+ headSha: string;
1093
+ delta: PrCommentDelta;
1094
+ // Findings this pass actually published (fresh review comments plus fresh
1095
+ // Outside Diff entries). NOT the delta's `new`: on a re-review that number
1096
+ // is the discovery count and includes findings that persisted onto an
1097
+ // existing comment, so a sentence built from it could say "no new" right
1098
+ // under a delta line that says "1 new".
1099
+ newPosted: number;
1100
+ // Every finding this pass reported, posted or kept.
1101
+ totalFindings: number;
1102
+ runStatus: RunStatus;
1103
+ summaryUrl: string | undefined;
1104
+ }): string {
1105
+ const sha = code(input.headSha.slice(0, 8));
1106
+ const complete = input.runStatus === "complete";
1107
+ // The heading is what the notification and the timeline preview show, so
1108
+ // a partial pass never gets the green "complete": the summary already
1109
+ // refuses a clean bill to a partial run (issue #42), and this comment must
1110
+ // not hand one back.
1111
+ const lines = [
1112
+ `${PR_REREVIEW_CLOSED_MARKER_PREFIX}head=${input.headSha} -->`,
1113
+ complete
1114
+ ? `### ✅ Crysk re-review complete — ${sha}`
1115
+ : `### ⚠️ Crysk re-review finished with partial coverage — ${sha}`,
1116
+ "",
1117
+ ];
1118
+ if (!complete) {
1119
+ lines.push(
1120
+ "⚠️ Partial coverage: some review steps failed, so this pass may have missed findings.",
1121
+ "",
1122
+ );
1123
+ }
1124
+ lines.push(deltaLine(input.delta), "");
1125
+ if (input.newPosted > 0) {
1126
+ lines.push(`${input.newPosted} new finding(s) posted in this pass.`);
1127
+ } else if (input.totalFindings > 0) {
1128
+ lines.push(
1129
+ "Nothing new was posted in this pass; findings already on the PR were kept.",
1130
+ );
1131
+ } else if (complete) {
1132
+ lines.push("No findings in this pass.");
1133
+ } else {
1134
+ lines.push("No findings reported by the steps that completed.");
1135
+ }
1136
+ lines.push(
1137
+ "",
1138
+ input.summaryUrl === undefined
1139
+ ? "The summary comment above was updated."
1140
+ : `The summary comment was updated: [view summary](${input.summaryUrl})`,
1141
+ );
1142
+ return `${lines.join("\n")}\n`;
1143
+ }
1144
+
1145
+ // Outside-diff bucket (issues #16/#17): un-anchorable and 422-demoted
1146
+ // findings live HERE, inside the one summary, never as `POST .../issues/<n>/comments`.
1147
+ // Rendered only when N>0. Full per-finding body (header, blob-linked location,
1148
+ // claim, tier explanation, evidence, prompt-to-fix) — the same shape as
1149
+ // renderIssueFindingComment minus the finding marker (that marker would make
1150
+ // fetchPostedFindingComments treat this summary as a finding comment) and
1151
+ // minus the "Posted as a standalone comment" footer (#17's smell).
1152
+ function outsideDiffSection(
1153
+ findings: readonly Finding[],
1154
+ headSha: string,
1155
+ webUrl: string | undefined,
1156
+ compactFrom: number | undefined,
1157
+ ): string[] {
1158
+ const out: string[] = [`### Comments Outside Diff (${findings.length})`, ""];
1159
+ for (const [i, finding] of findings.entries()) {
1160
+ if (i > 0) out.push("");
1161
+ // A compact entry keeps only its tier and linked location: no claim,
1162
+ // evidence, or prompt-to-fix body. WHY the tier stays: without it a reader
1163
+ // (or the sandbox's report parser) cannot tell a compacted blocking entry
1164
+ // from an advisory one.
1165
+ if (compactFrom !== undefined && i >= compactFrom) {
1166
+ out.push(
1167
+ `${scanAidEmoji(finding)} ${finding.tier} · ` +
1168
+ findingLocationLine(finding, headSha, webUrl, true),
1169
+ );
1170
+ continue;
1171
+ }
1172
+ out.push(...findingBodyLines(finding, headSha, webUrl, true));
1173
+ }
1174
+ return out;
1175
+ }
1176
+
1177
+ // Per-finding comment bodies (ROADMAP B6, reworked per Juanma's PR #2
1178
+ // feedback items 2-5). Every posted finding — anchored inline or standalone
1179
+ // — carries the pr/preflight.ts identity marker as its FIRST line, mirroring
1180
+ // prCommentMarker's own contract, so a second run can tell "already posted"
1181
+ // from "new" (pr/inline.ts's matcher) without ever touching dedupe_key or
1182
+ // root_cause_id. Deliberately as sparse as renderPrComment on economics: no
1183
+ // cost, no tokens, nothing internal.
1184
+ //
1185
+ // Shape (both renderers, `linkLocation` is the only structural difference —
1186
+ // see below):
1187
+ // <marker>
1188
+ //
1189
+ // 🔴 blocking · CRITICAL · introduced · lifecycle · refuter: corroborated
1190
+ // `path:line` — symbol()
1191
+ //
1192
+ // <claim, as a single unbroken-but-readable paragraph — item 5: "es solo
1193
+ // texto y no se entiende bien" was the old five-line wall>
1194
+ //
1195
+ // ⚖️ Downgraded to advisory — the refuter returned `downgraded-latent`
1196
+ // (only when tier disagrees with severity — item 3/4)
1197
+ //
1198
+ // <details>Evidence (N)</details>
1199
+ // <details>Prompt to fix with AI</details>
1200
+ //
1201
+ // The refuter's verdict is the header's LAST field (diagnosis 5.9): without
1202
+ // it, triage cannot tell a refuter-corroborated blocker from a warning that
1203
+ // never reached the refuter. Appended, never inserted, because the parsers
1204
+ // that read this line back (FINDING_HEADER_BADGE here, FINDING_HEADER_TIER in
1205
+ // ci/review-admission.ts) anchor on the leading fields only.
1206
+ function findingHeaderLine(finding: Finding): string {
1207
+ return (
1208
+ `${scanAidEmoji(finding)} ${finding.tier} · ${finding.severity} · ` +
1209
+ `${finding.causal_disposition} · ${finding.hunter} · ` +
1210
+ `refuter: ${refuterLabel(finding.refuter_verdict)}`
1211
+ );
1212
+ }
1213
+
1214
+ // `not_submitted` is the engine's word for "the refuter never saw this
1215
+ // finding" (every WARNING/SUGGESTION, and blockers on a truncated run). On a
1216
+ // PR comment that reads as a submission failure, so it renders as `unchecked`.
1217
+ // Every other verdict renders verbatim, matching the ledger's vocabulary.
1218
+ function refuterLabel(verdict: RefuterVerdict): string {
1219
+ return verdict === "not_submitted" ? "unchecked" : verdict;
1220
+ }
1221
+
1222
+ function findingLocationLine(
1223
+ finding: Finding,
1224
+ headSha: string,
1225
+ webUrl: string | undefined,
1226
+ linkLocation: boolean,
1227
+ ): string {
1228
+ const loc = code(`${finding.path}:${finding.line}`);
1229
+ const linked =
1230
+ linkLocation && webUrl !== undefined
1231
+ ? `[${loc}](${blobUrl(webUrl, headSha, finding.path, `L${finding.line}`)})`
1232
+ : loc;
1233
+ // A POSITIVE type test, not `=== undefined`. Defence in depth: the draft and
1234
+ // artifact validators now normalise a null symbol away, so this should be
1235
+ // unreachable — but the old `=== undefined` guard let `"symbol": null` walk
1236
+ // straight into oneLine() and the TypeError killed a POST the pipeline had
1237
+ // already billed $3.77 for (PR #50, 2026-08-23). A renderer that throws
1238
+ // loses paid work; one that renders loses a symbol. oneLine() itself is
1239
+ // deliberately left strict — hardening it would mask this class everywhere.
1240
+ // Empty strings fall to the same branch, which drops the trailing "— ".
1241
+ return typeof finding.symbol === "string" && finding.symbol.length > 0
1242
+ ? `${linked} — ${oneLine(finding.symbol)}`
1243
+ : linked;
1244
+ }
1245
+
1246
+ // Item 3/4 (Juanma's PR #2 feedback): "CRITICAL (advisory)" on screen with no
1247
+ // explanation reads as a contradiction, and `causal_disposition` was never
1248
+ // shown anywhere. This line closes both — but ONLY when severity and tier
1249
+ // actually disagree (a CRITICAL/BLOCKER landed advisory); printing it when
1250
+ // they agree would be a tautology ("CRITICAL, still CRITICAL"). Mirrors
1251
+ // deriveTier's own gate (review/findings.ts): only BLOCKER/CRITICAL can ever
1252
+ // disagree with their tier, since every other severity is advisory by
1253
+ // definition and never needs explaining.
1254
+ function tierExplanationLines(finding: Finding): string[] {
1255
+ const isBlockerClass =
1256
+ finding.severity === "BLOCKER" || finding.severity === "CRITICAL";
1257
+ if (!isBlockerClass || finding.tier !== "advisory") return [];
1258
+ // `not_submitted` never reached the refuter, so "the refuter returned" it
1259
+ // would be false, and printing the engine's word here would contradict the
1260
+ // header, which says `refuter: unchecked` (refuterLabel).
1261
+ const lines = [
1262
+ finding.refuter_verdict === "not_submitted"
1263
+ ? "⚖️ Downgraded to advisory — the refuter never checked it"
1264
+ : "⚖️ Downgraded to advisory — the refuter returned " +
1265
+ `\`${finding.refuter_verdict}\``,
1266
+ ];
1267
+ // `downgraded-latent` is the one verdict with a documented, human-legible
1268
+ // meaning worth spelling out inline (review/findings.ts's own WHY comment on the
1269
+ // type): a real defect the refuter could not currently trigger. The other
1270
+ // verdicts that can also land here (`inconclusive`, or an `insufficient`
1271
+ // evidence_class regardless of verdict) have no equally short gloss, so they
1272
+ // render with just the verdict name rather than a guessed one.
1273
+ // `not_submitted` (unrefuted-inferential, or demoted because the run was
1274
+ // truncated before the refuter leg ran) has its own line above.
1275
+ if (finding.refuter_verdict === "downgraded-latent") {
1276
+ lines.push(" (real, but no live trigger today)");
1277
+ }
1278
+ return lines;
1279
+ }
1280
+
1281
+ // Item "Prompt to fix with AI" (Juanma's PR #2 feedback): a copy-pasteable
1282
+ // prompt, not a deep link — Greptile's equivalent hands off to a hosted IDE
1283
+ // integration this project does not have, and inventing a link to a service
1284
+ // that does not exist would be worse than omitting the feature.
1285
+ function promptToFixBlock(finding: Finding): string[] {
1286
+ return [
1287
+ "",
1288
+ "<details><summary>Prompt to fix with AI</summary>",
1289
+ "",
1290
+ "```",
1291
+ `Fix this issue in ${finding.path} at line ${finding.line}:`,
1292
+ "",
1293
+ oneLine(finding.claim),
1294
+ "```",
1295
+ "",
1296
+ "</details>",
1297
+ ];
1298
+ }
1299
+
1300
+ function findingBodyLines(
1301
+ finding: Finding,
1302
+ headSha: string,
1303
+ webUrl: string | undefined,
1304
+ linkLocation: boolean,
1305
+ ): string[] {
1306
+ const out: string[] = [
1307
+ findingHeaderLine(finding),
1308
+ findingLocationLine(finding, headSha, webUrl, linkLocation),
1309
+ "",
1310
+ oneLine(finding.claim),
1311
+ ];
1312
+ const tierLines = tierExplanationLines(finding);
1313
+ if (tierLines.length > 0) {
1314
+ out.push("");
1315
+ out.push(...tierLines);
1316
+ }
1317
+ out.push(...evidenceBlock(finding, headSha, webUrl));
1318
+ out.push(...promptToFixBlock(finding));
1319
+ return out;
1320
+ }
1321
+
1322
+ const FINDING_HEADER_BADGE =
1323
+ /^\S+\s+(blocking|advisory)\s+·\s+(BLOCKER|CRITICAL|WARNING|SUGGESTION)\s+·/;
1324
+
1325
+ export interface RecoveredFindingBadge {
1326
+ sev: Severity;
1327
+ tier: Tier;
1328
+ claim: string;
1329
+ }
1330
+
1331
+ // #206's recovery path: when a re-review's `pr-hero-state` block cannot
1332
+ // supply a carried prior's `sev`/`tier`/`claim` (missing, unparseable, or —
1333
+ // the routine case — a FIRST review never writes one at all, see
1334
+ // `postInlineFindings`'s `framing === undefined` branch in src/pr/pr.ts),
1335
+ // the finding's OWN posted comment still carries the truth: `findingMarker`
1336
+ // signs only the claim's FINGERPRINT, never the claim text itself, but
1337
+ // `findingBodyLines` above writes the real header/location/claim right
1338
+ // after it. This is that renderer's exact structural inverse — it does NOT
1339
+ // re-derive the format independently, so the two cannot silently drift
1340
+ // apart (see the round-trip test in test/review/report.test.ts).
1341
+ //
1342
+ // Deliberately all-or-nothing: `findingBodyLines`' header/location/blank/
1343
+ // claim order is fixed by construction, so a body that does not match it
1344
+ // closely enough to recover the header cannot be trusted to have the claim
1345
+ // in the expected place either. A caller that gets `null` back must not
1346
+ // invent a value — see rereview/classify.ts's `SEVERITY_UNRECOVERABLE` /
1347
+ // `TIER_UNRECOVERABLE` sentinels, which exist for exactly this return.
1348
+ export function parseFindingCommentBadge(
1349
+ body: string,
1350
+ ): RecoveredFindingBadge | null {
1351
+ if (findMarker(body, PR_FINDING_MARKER_PREFIX) === undefined) return null;
1352
+ const lines = body.split("\n");
1353
+ const markerIndex = lines.findIndex(
1354
+ (line) => matchMarkerPrefix(line, PR_FINDING_MARKER_PREFIX) !== undefined,
1355
+ );
1356
+ if (markerIndex === -1) return null;
1357
+ let i = markerIndex + 1;
1358
+ while (i < lines.length && (lines[i]?.trim() ?? "") === "") i++;
1359
+ const headerLine = lines[i];
1360
+ if (headerLine === undefined) return null;
1361
+ const match = FINDING_HEADER_BADGE.exec(headerLine.trim());
1362
+ if (match?.[1] === undefined || match[2] === undefined) return null;
1363
+ const tier = match[1] as Tier;
1364
+ const sev = match[2] as Severity;
1365
+ // findingBodyLines' fixed shape from here: the location line (exactly
1366
+ // one, whatever it contains — never parsed, its content is not needed),
1367
+ // one blank line, then the claim. Order never varies; only the OPTIONAL
1368
+ // blocks after the claim (tier explanation / evidence / prompt) do.
1369
+ i++;
1370
+ if (lines[i] === undefined) return null;
1371
+ i++;
1372
+ while (i < lines.length && (lines[i]?.trim() ?? "") === "") i++;
1373
+ const claimLine = lines[i];
1374
+ if (claimLine === undefined) return null;
1375
+ const claim = claimLine.trim();
1376
+ if (claim.length === 0) return null;
1377
+ return { sev, tier, claim };
1378
+ }
1379
+
1380
+ export function renderInlineComment(
1381
+ finding: Finding,
1382
+ headSha: string,
1383
+ webUrl?: string,
1384
+ ): string {
1385
+ const out: string[] = [
1386
+ findingMarker({
1387
+ path: finding.path,
1388
+ line: finding.line,
1389
+ headSha,
1390
+ claim: finding.claim,
1391
+ }),
1392
+ "",
1393
+ // No link on the location line: GitHub already anchors this comment to
1394
+ // the diff line itself, so a self-referential link would be redundant —
1395
+ // unlike the un-anchorable twin below, which has no anchor to point at.
1396
+ ...findingBodyLines(finding, headSha, webUrl, false),
1397
+ ];
1398
+ return `${out.join("\n").trimEnd()}\n`;
1399
+ }
1400
+
1401
+ // Kept for postIssueComment (src/pr/pr.ts) and its tests: leftover W1 orphans
1402
+ // from old runs still have this body shape. New posting (W2, issues #16/#17)
1403
+ // does not call this — un-anchorable findings go into the summary Outside
1404
+ // Diff section, which reuses findingBodyLines without the marker or this
1405
+ // standalone-comment footer (#17's smell).
1406
+ export function renderIssueFindingComment(
1407
+ finding: Finding,
1408
+ headSha: string,
1409
+ webUrl?: string,
1410
+ ): string {
1411
+ const out: string[] = [
1412
+ findingMarker({
1413
+ path: finding.path,
1414
+ line: finding.line,
1415
+ headSha,
1416
+ claim: finding.claim,
1417
+ }),
1418
+ "",
1419
+ ...findingBodyLines(finding, headSha, webUrl, true),
1420
+ "",
1421
+ "<sub>Posted as a standalone comment: Crysk could not anchor this " +
1422
+ "finding to a line in the current diff.</sub>",
1423
+ ];
1424
+ return `${out.join("\n").trimEnd()}\n`;
1425
+ }
1426
+
1427
+ // Shared Evidence <details> block, extracted from the pre-B6
1428
+ // commentTierSection so both per-finding renderers stay byte-identical on
1429
+ // the blank-line discipline GitHub requires around <details> markdown.
1430
+ function evidenceBlock(
1431
+ finding: Finding,
1432
+ headSha: string,
1433
+ webUrl: string | undefined,
1434
+ ): string[] {
1435
+ if (finding.proof_refs.length === 0) return [];
1436
+ const out: string[] = [
1437
+ "",
1438
+ `<details><summary>Evidence (${finding.proof_refs.length})</summary>`,
1439
+ "",
1440
+ ];
1441
+ for (const ref of finding.proof_refs) {
1442
+ out.push(`- ${renderRef(ref, headSha, webUrl)}`);
1443
+ }
1444
+ out.push("");
1445
+ out.push("</details>");
1446
+ return out;
1447
+ }
1448
+
1449
+ // One Evidence bullet. With a web URL, the ref's leading `path:line` /
1450
+ // `path:start-end` anchor becomes a blob link and the trailing prose stays
1451
+ // plain text; a ref whose anchor does not parse falls back to the plain
1452
+ // backtick-guarded rendering — a broken link would be worse than none.
1453
+ function renderRef(
1454
+ ref: string,
1455
+ headSha: string,
1456
+ webUrl: string | undefined,
1457
+ ): string {
1458
+ if (webUrl === undefined) return code(ref);
1459
+ const parsed = parseRefAnchor(ref);
1460
+ if (parsed === null) return code(ref);
1461
+ const fragment =
1462
+ parsed.end === undefined
1463
+ ? `L${parsed.start}`
1464
+ : `L${parsed.start}-L${parsed.end}`;
1465
+ const url = blobUrl(webUrl, headSha, parsed.path, fragment);
1466
+ const link = `[${code(`${parsed.path}:${parsed.lines}`)}](${url})`;
1467
+ return parsed.prose === "" ? link : `${link} ${oneLine(parsed.prose)}`;
1468
+ }
1469
+
1470
+ // Splits one proof_ref into its leading location anchor and trailing prose,
1471
+ // REUSING extractAnchor (review/root-cause.ts) so the comment and the root-cause
1472
+ // clustering read the exact same token as "the location" — two parsers for
1473
+ // one format would drift. On top of the shared token this only checks that
1474
+ // the line part is numeric (`19` or `19-20`): extractAnchor accepts any
1475
+ // non-empty text after the colon, but only numbers make a #L fragment.
1476
+ function parseRefAnchor(ref: string): {
1477
+ path: string;
1478
+ lines: string;
1479
+ start: number;
1480
+ end?: number;
1481
+ prose: string;
1482
+ } | null {
1483
+ const anchor = extractAnchor([ref]);
1484
+ if (anchor === null) return null;
1485
+ const colon = anchor.lastIndexOf(":");
1486
+ const path = anchor.slice(0, colon);
1487
+ const lines = anchor.slice(colon + 1);
1488
+ const match = /^(\d+)(?:-(\d+))?$/.exec(lines);
1489
+ if (path.length === 0 || match?.[1] === undefined) return null;
1490
+ return {
1491
+ path,
1492
+ lines,
1493
+ start: Number(match[1]),
1494
+ end: match[2] === undefined ? undefined : Number(match[2]),
1495
+ prose: ref.trim().slice(anchor.length).trim(),
1496
+ };
1497
+ }
1498
+
1499
+ // Exported for ui/result.ts, the second surface that links a finding to its
1500
+ // source. Deliberately SHARED rather than re-derived: the markdown report and
1501
+ // the terminal block must point a reader at the same bytes, and two copies of
1502
+ // `/blob/<sha>/<path>#<fragment>` is exactly how the pinned line of one
1503
+ // surface drifts from the other.
1504
+ export function blobUrl(
1505
+ webUrl: string,
1506
+ sha: string,
1507
+ path: string,
1508
+ fragment: string,
1509
+ ): string {
1510
+ return `${webUrl}/blob/${sha}/${path}#${fragment}`;
1511
+ }
1512
+
1513
+ function runLines(doc: FindingsDocument, meta: ReportMeta): string[] {
1514
+ const { files, insertions, deletions } = meta.diffStat;
1515
+ // #173: cash first and unqualified, notional after it and never without its
1516
+ // basis spelled out — §8 allows notional in a report "only when clearly
1517
+ // labelled", and two bare dollar figures side by side is precisely the
1518
+ // mixing it forbids.
1519
+ const notional =
1520
+ meta.notionalUsd === undefined
1521
+ ? ""
1522
+ : ` (${usd(meta.notionalUsd)} at list price, not charged)`;
1523
+ const lines = [
1524
+ `${files} file${files === 1 ? "" : "s"}, +${insertions} −${deletions}` +
1525
+ ` · run ${doc.run_status} · ${usd(meta.costUsd)}${notional} · ${duration(meta.wallMs)}`,
1526
+ ];
1527
+ const excluded = meta.excludedPaths ?? [];
1528
+ if (excluded.length > 0) {
1529
+ lines.push("");
1530
+ lines.push(
1531
+ `${excluded.length} file${excluded.length === 1 ? " was" : "s were"} ` +
1532
+ `excluded from the reviewed diff: ${excluded.join(", ")}. The counts ` +
1533
+ "above, and the diff the hunters read, are after that exclusion " +
1534
+ "(`diff.raw.patch` holds the unfiltered diff).",
1535
+ );
1536
+ }
1537
+ const rows = agentRows(doc);
1538
+ if (rows.length > 0) {
1539
+ lines.push("");
1540
+ lines.push(
1541
+ `Agents: ${rows.map((r) => `${r.key} ${r.status}`).join(" · ")}`,
1542
+ );
1543
+ }
1544
+ if (!doc.parity_hunter_fired) {
1545
+ lines.push("");
1546
+ lines.push(
1547
+ "The parity hunter did not fire: no changed path matched its trigger.",
1548
+ );
1549
+ }
1550
+ return lines;
1551
+ }
1552
+
1553
+ // Grouping is the entire point of this section. ONE systemic defect reported
1554
+ // at N call sites is one thing to fix, and a flat list of N findings reads as
1555
+ // N problems — the same misreading that turns a correct review into an
1556
+ // apparent precision collapse (see the note on clusterByRootCause). So the
1557
+ // cluster is the unit of presentation here, and the finding is a site inside
1558
+ // it.
1559
+ function section(
1560
+ title: string,
1561
+ doc: FindingsDocument,
1562
+ tier: Tier,
1563
+ summary: RootCauseSummary,
1564
+ ): string[] {
1565
+ const findings = doc.findings.filter((f) => f.tier === tier);
1566
+ const byFinding = rootCauseIdByFinding(summary);
1567
+ const anchorById = new Map(summary.clusters.map((c) => [c.id, c.anchor]));
1568
+ // Clusters can straddle the tier split (two sites blocking, one advisory).
1569
+ // Group WITHIN the section: a section must never claim sites it is not
1570
+ // showing, so K counts the sites rendered right here.
1571
+ const groups: Array<{ key: string; findings: Finding[] }> = [];
1572
+ const index = new Map<string, { key: string; findings: Finding[] }>();
1573
+ for (const finding of findings) {
1574
+ // A finding the clusterer never placed is its own group, keyed by its own
1575
+ // id — an unclustered finding must never fall into a shared bucket.
1576
+ const key = byFinding.get(finding.id) ?? `finding:${finding.id}`;
1577
+ const existing = index.get(key);
1578
+ if (existing) {
1579
+ existing.findings.push(finding);
1580
+ continue;
1581
+ }
1582
+ const group = { key, findings: [finding] };
1583
+ index.set(key, group);
1584
+ groups.push(group);
1585
+ }
1586
+ const out = [
1587
+ `## ${title} (${findings.length} finding${findings.length === 1 ? "" : "s"}` +
1588
+ `, ${groups.length} root cause${groups.length === 1 ? "" : "s"})`,
1589
+ ];
1590
+ if (findings.length === 0) {
1591
+ out.push("");
1592
+ out.push(`_Nothing ${title.toLowerCase()}._`);
1593
+ return out;
1594
+ }
1595
+ for (const group of groups) {
1596
+ out.push("");
1597
+ const first = group.findings[0];
1598
+ if (!first) continue;
1599
+ if (group.findings.length === 1) {
1600
+ out.push(...renderSingleton(first));
1601
+ continue;
1602
+ }
1603
+ out.push(
1604
+ ...renderFanOut(
1605
+ group.findings,
1606
+ anchorById.get(group.key) ?? null,
1607
+ group.key,
1608
+ ),
1609
+ );
1610
+ }
1611
+ return out;
1612
+ }
1613
+
1614
+ function renderFanOut(
1615
+ findings: Finding[],
1616
+ anchor: string | null,
1617
+ clusterId: string,
1618
+ ): string[] {
1619
+ const label = anchor === null ? "(no shared anchor)" : code(anchor);
1620
+ const out = [
1621
+ `### ${clusterId} — ${label}`,
1622
+ "",
1623
+ `One defect reported at ${findings.length} sites — fix the root cause ` +
1624
+ "once and every site below goes with it.",
1625
+ "",
1626
+ ];
1627
+ for (const finding of findings) {
1628
+ out.push(
1629
+ `- ${finding.id} ${code(`${finding.path}:${finding.line}`)} — ` +
1630
+ `${oneLine(finding.claim)} (${finding.severity}, ${finding.hunter})`,
1631
+ );
1632
+ }
1633
+ return out;
1634
+ }
1635
+
1636
+ function renderSingleton(finding: Finding): string[] {
1637
+ const symbol = finding.symbol ? ` (${oneLine(finding.symbol)})` : "";
1638
+ const out = [
1639
+ `### ${finding.id} — ${code(`${finding.path}:${finding.line}`)}${symbol}`,
1640
+ "",
1641
+ oneLine(finding.claim),
1642
+ "",
1643
+ `- ${finding.severity} · evidence ${finding.evidence_class} · ` +
1644
+ `${finding.causal_disposition} · hunter ${finding.hunter} · ` +
1645
+ `refuter ${finding.refuter_verdict}`,
1646
+ ];
1647
+ if (finding.proof_refs.length === 0) {
1648
+ out.push("- Proof: none cited");
1649
+ return out;
1650
+ }
1651
+ out.push("- Proof:");
1652
+ for (const ref of finding.proof_refs) out.push(` - ${oneLine(ref)}`);
1653
+ return out;
1654
+ }
1655
+
1656
+ // The audit trail. A finding the engine dropped is invisible in findings[],
1657
+ // and an invisible drop is an unattributable miss: "no hunter saw it" and "a
1658
+ // hunter saw it and the refuter killed it" must not look the same to a human
1659
+ // reading this file.
1660
+ function notReported(doc: FindingsDocument): string[] {
1661
+ const refuted = doc.debug.refuted;
1662
+ const deduped = doc.debug.deduped ?? [];
1663
+ const out = ["## Not reported", ""];
1664
+ if (refuted.length === 0 && deduped.length === 0) {
1665
+ out.push("Nothing was refuted, and nothing was merged as a duplicate.");
1666
+ return out;
1667
+ }
1668
+ out.push(
1669
+ `${refuted.length} refuted, ${deduped.length} merged as duplicates.`,
1670
+ );
1671
+ if (refuted.length > 0) out.push("");
1672
+ for (const finding of refuted) {
1673
+ out.push(
1674
+ `- ${finding.id} ${code(`${finding.path}:${finding.line}`)} — ` +
1675
+ `${oneLine(finding.claim)} — ${finding.refuter_verdict}`,
1676
+ );
1677
+ }
1678
+ // A severe claim discarded as a duplicate used to leave nothing here but a
1679
+ // number, and issue #153 is what that cost: an authorization-bypass BLOCKER
1680
+ // was merged into a claim about a DIFFERENT defect and vanished from the
1681
+ // report, while debug.deduped[] had recorded it the whole time. A count is
1682
+ // not a trace. Advisory losers stay counted only — this exists to make a
1683
+ // lost BLOCKER visible, not to reprint every merge.
1684
+ //
1685
+ // No id: a loser keeps its hunter-assigned draft id, which names nothing a
1686
+ // reader can look up, so the location is the anchor.
1687
+ const severe = deduped.filter(
1688
+ (loser) => loser.severity === "BLOCKER" || loser.severity === "CRITICAL",
1689
+ );
1690
+ if (severe.length > 0) {
1691
+ out.push("");
1692
+ for (const loser of severe) {
1693
+ out.push(
1694
+ `- ${code(`${loser.path}:${loser.line}`)} — ` +
1695
+ `${oneLine(loser.claim)} — merged into ${loser.merged_into}`,
1696
+ );
1697
+ }
1698
+ }
1699
+ return out;
1700
+ }
1701
+
1702
+ // The engine identity as prose, shared by the report's closing note and the
1703
+ // PR comment's footer: absent engine info degrades to a name, never a lie.
1704
+ function engineLabel(doc: FindingsDocument): string {
1705
+ return doc.engine
1706
+ ? `${doc.engine.name === LEGACY_BIN_NAME ? BIN_NAME : doc.engine.name} ${doc.engine.version}`
1707
+ : "crysk (version not recorded)";
1708
+ }
1709
+
1710
+ // The report's closing note by gate mode. Advisory is today's wording, byte for
1711
+ // byte. Gate says the report backs the required status, and it does not claim
1712
+ // the merge is never blocked: under a required check it can be.
1713
+ function closing(doc: FindingsDocument, ciMode: CiMode): string[] {
1714
+ if (ciMode === "gate") {
1715
+ return [
1716
+ "---",
1717
+ "",
1718
+ `Generated by ${engineLabel(doc)}. This report backs the crysk commit status, ` +
1719
+ "the required check in gate mode: every line above is a claim to verify. " +
1720
+ "A blocking finding sets that status to failure. Whether it blocks the merge " +
1721
+ "is up to branch protection.",
1722
+ ];
1723
+ }
1724
+ return [
1725
+ "---",
1726
+ "",
1727
+ `Generated by ${engineLabel(doc)}. This is an assistant report, not a merge gate: ` +
1728
+ 'every line above is a claim to verify, and `blocking` means "a human ' +
1729
+ 'should look before this ships", never "the merge is blocked".',
1730
+ ];
1731
+ }
1732
+
1733
+ // The PR comment footer's disclaimer by gate mode, kept in the comment's own
1734
+ // voice: no em dashes, the disclaimer joins with a colon.
1735
+ function commentDisclaimer(ciMode: CiMode): string {
1736
+ return ciMode === "gate"
1737
+ ? "Assistant report backing the crysk commit status, the required check in gate mode: every line above is a claim to verify."
1738
+ : "Assistant report, not a merge gate: every line above is a claim to verify.";
1739
+ }
1740
+
1741
+ // Hunter-authored text lands inside code spans and list items. A stray
1742
+ // backtick in a path or proof_ref would break out of its span and mangle
1743
+ // every line after it, so spans are built here and never by hand.
1744
+ function code(text: string): string {
1745
+ return `\`${oneLine(text).replaceAll("`", "'")}\``;
1746
+ }
1747
+
1748
+ // Claims arrive as free prose and sometimes carry newlines; a raw newline
1749
+ // inside a list item silently ends the item.
1750
+ function oneLine(text: string): string {
1751
+ return text.replace(/\s+/g, " ").trim();
1752
+ }
1753
+
1754
+ function usd(amount: number): string {
1755
+ return `$${amount.toFixed(2)}`;
1756
+ }
1757
+
1758
+ // Elapsed time as the compact `3m12s` the CLI's live progress prefixes onto
1759
+ // every event line. Floor, never round: 59.9s read as "60s" would tick the
1760
+ // minute early. Minutes deliberately never roll into hours — a review past
1761
+ // the hour reading "61m..." is itself information.
1762
+ export function formatElapsed(ms: number): string {
1763
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
1764
+ const minutes = Math.floor(totalSeconds / 60);
1765
+ const seconds = totalSeconds % 60;
1766
+ return minutes === 0
1767
+ ? `${seconds}s`
1768
+ : `${minutes}m${String(seconds).padStart(2, "0")}s`;
1769
+ }
1770
+
1771
+ function duration(ms: number): string {
1772
+ const totalSeconds = Math.max(0, Math.round(ms / 1000));
1773
+ const minutes = Math.floor(totalSeconds / 60);
1774
+ const seconds = totalSeconds % 60;
1775
+ return minutes === 0
1776
+ ? `${seconds}s`
1777
+ : `${minutes}m ${String(seconds).padStart(2, "0")}s`;
1778
+ }
1779
+
1780
+ function round2(value: number): number {
1781
+ return Math.round(value * 100) / 100;
1782
+ }
1783
+
1784
+ export function formatModelRoute(
1785
+ route: ResolvedModelRoute,
1786
+ logicalIdentity?: string,
1787
+ ): string {
1788
+ const variant = route.modelVariant ? `#${route.modelVariant}` : "";
1789
+ const modelName = route.modelSnapshot || route.modelFamily;
1790
+ const target = `${route.provider}/${modelName}${variant}`;
1791
+ const gateway = route.gateway ?? "direct";
1792
+ const dims = `[${gateway}, ${route.backend}]`;
1793
+ if (logicalIdentity && logicalIdentity !== target) {
1794
+ return `${logicalIdentity} -> ${target} ${dims}`;
1795
+ }
1796
+ return `${target} ${dims}`;
1797
+ }
1798
+
1799
+ export function formatStepRoute(
1800
+ step: ResolvedStepRoute,
1801
+ rawLogical?: string,
1802
+ ): string {
1803
+ return formatModelRoute(step.route, rawLogical ?? step.logicalIdentity);
1804
+ }
1805
+
1806
+ // The envelope needs ONE model string. With no --model override each agent
1807
+ // carries its own frontmatter model, so report what actually ran rather than
1808
+ // inventing a single value: identical models collapse to one name, a mixed
1809
+ // set is recorded as a mix instead of as a lie.
1810
+ export function envelopeModel(
1811
+ options: { model?: string },
1812
+ agentFiles: Map<string, { model?: string }>,
1813
+ ): string {
1814
+ if (options.model) return options.model;
1815
+ const models = new Set<string>();
1816
+ for (const agent of agentFiles.values()) {
1817
+ if (agent.model) models.add(agent.model);
1818
+ }
1819
+ if (models.size === 0) return "unspecified";
1820
+ return [...models].sort().join("+");
1821
+ }