crysk 0.0.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +609 -3
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/adjudicator-dtg2axnh.md +86 -0
  10. package/dist/admission-config.example-a9vqmmad.json +9 -0
  11. package/dist/ci-admission-camfbx2b.md +122 -0
  12. package/dist/cli.js +42292 -0
  13. package/dist/consolidate-ac0mnfyj.md +24 -0
  14. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  15. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  16. package/dist/deep-review-parity-0ec904db.md +120 -0
  17. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  18. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  19. package/dist/index.js +20190 -0
  20. package/dist/opencode-ci-7b0be64p.md +141 -0
  21. package/dist/review-refuter-j4e9gezy.md +71 -0
  22. package/dist/scout-yvp153q7.md +140 -0
  23. package/dist/summarizer-zca44nxa.md +18 -0
  24. package/dist/workflow-w1g9szna.yml +151 -0
  25. package/package.json +81 -4
  26. package/prompts/consolidate.md +24 -0
  27. package/prompts/default/PROVENANCE.md +18 -0
  28. package/prompts/default/deep-review-lifecycle.md +362 -0
  29. package/prompts/default/deep-review-logic.md +156 -0
  30. package/prompts/default/deep-review-parity.md +120 -0
  31. package/prompts/default/deep-review-reliability.md +125 -0
  32. package/prompts/default/deep-review-resilience.md +118 -0
  33. package/prompts/default/review-refuter.md +71 -0
  34. package/prompts/scout.md +140 -0
  35. package/prompts/summarizer.md +18 -0
  36. package/skills/crysk/SKILL.md +74 -0
  37. package/skills/crysk-ci-setup/SKILL.md +134 -0
  38. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  39. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  40. package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
  41. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  42. package/skills/crysk-loop/SKILL.md +496 -0
  43. package/skills/crysk-loop/adjudicator.md +86 -0
  44. package/skills/crysk-pr/SKILL.md +66 -0
  45. package/src/agent-env.ts +1084 -0
  46. package/src/asset-manifest.ts +83 -0
  47. package/src/assets.d.ts +6 -0
  48. package/src/assets.ts +183 -0
  49. package/src/brand-paths.ts +155 -0
  50. package/src/brand.ts +255 -0
  51. package/src/ci/admission-ledger.ts +350 -0
  52. package/src/ci/classify-error.ts +73 -0
  53. package/src/ci/cli-record.ts +271 -0
  54. package/src/ci/force-comment.ts +39 -0
  55. package/src/ci/gates.ts +923 -0
  56. package/src/ci/outcome.ts +2181 -0
  57. package/src/ci/override.ts +187 -0
  58. package/src/ci/publish.ts +1639 -0
  59. package/src/ci/reporter.ts +626 -0
  60. package/src/ci/review-admission.ts +901 -0
  61. package/src/ci/review-levels.ts +310 -0
  62. package/src/ci/review-policy.ts +18 -0
  63. package/src/ci/review-risk.ts +184 -0
  64. package/src/ci/setup.ts +844 -0
  65. package/src/ci/trigger.ts +1353 -0
  66. package/src/cli.ts +348 -0
  67. package/src/commands/activity.ts +67 -0
  68. package/src/commands/ci-setup-questions.ts +397 -0
  69. package/src/commands/ci-setup.ts +381 -0
  70. package/src/commands/config.ts +99 -0
  71. package/src/commands/doctor.ts +108 -0
  72. package/src/commands/init.ts +139 -0
  73. package/src/commands/mcp.ts +10 -0
  74. package/src/commands/menu.ts +129 -0
  75. package/src/commands/post.ts +302 -0
  76. package/src/commands/skills.ts +83 -0
  77. package/src/commands/status.ts +173 -0
  78. package/src/commands/triage.ts +342 -0
  79. package/src/commands/uninstall.ts +37 -0
  80. package/src/commands/upgrade.ts +214 -0
  81. package/src/commands/usage.ts +98 -0
  82. package/src/compare/compare.ts +28 -0
  83. package/src/compare/floor-test.ts +471 -0
  84. package/src/compare/martian-adapter.ts +80 -0
  85. package/src/config/config.ts +267 -0
  86. package/src/corpus/corpus.ts +1094 -0
  87. package/src/corpus/preflight.ts +1789 -0
  88. package/src/diversity/accounting.ts +90 -0
  89. package/src/diversity/adjudication.ts +145 -0
  90. package/src/diversity/admission.ts +60 -0
  91. package/src/diversity/benchmark.ts +195 -0
  92. package/src/diversity/clustering.ts +285 -0
  93. package/src/diversity/errors.ts +7 -0
  94. package/src/diversity/identity.ts +285 -0
  95. package/src/diversity/index.ts +11 -0
  96. package/src/diversity/pipeline-integration.ts +448 -0
  97. package/src/diversity/projection.ts +57 -0
  98. package/src/diversity/self-contained.ts +68 -0
  99. package/src/diversity/target-validation.ts +179 -0
  100. package/src/doctor-migration.ts +209 -0
  101. package/src/doctor.ts +723 -0
  102. package/src/errors.ts +83 -0
  103. package/src/execution/admission.ts +75 -0
  104. package/src/execution/atomic-write.ts +35 -0
  105. package/src/execution/attempt-evidence.ts +415 -0
  106. package/src/execution/bucket-id.ts +136 -0
  107. package/src/execution/concurrency-limiter.ts +175 -0
  108. package/src/execution/contracts.ts +443 -0
  109. package/src/execution/failure-classification.ts +42 -0
  110. package/src/execution/failure-policy.ts +240 -0
  111. package/src/execution/harness.ts +2548 -0
  112. package/src/execution/settlement.ts +348 -0
  113. package/src/execution/spawned-process.ts +66 -0
  114. package/src/execution/spend-limiter.ts +424 -0
  115. package/src/execution/step-artifacts.ts +55 -0
  116. package/src/execution/usage-normalized.ts +469 -0
  117. package/src/git/git.ts +396 -0
  118. package/src/git/identity.ts +64 -0
  119. package/src/git/refs.ts +140 -0
  120. package/src/home-preflight.ts +443 -0
  121. package/src/home.ts +243 -0
  122. package/src/ignore-file.ts +336 -0
  123. package/src/ignore-read.ts +118 -0
  124. package/src/index.ts +34 -0
  125. package/src/legacy-launchd.ts +29 -0
  126. package/src/mcp/mcp.ts +150 -0
  127. package/src/mcp/preflight.ts +407 -0
  128. package/src/menu-context.ts +192 -0
  129. package/src/model/catalog.ts +251 -0
  130. package/src/model/exec-snapshots.ts +390 -0
  131. package/src/model/free-discovery.ts +302 -0
  132. package/src/model/provider-capabilities.ts +814 -0
  133. package/src/model/routing.ts +600 -0
  134. package/src/pr/admission.ts +847 -0
  135. package/src/pr/ci-admission-gate.ts +665 -0
  136. package/src/pr/ci-publish.ts +76 -0
  137. package/src/pr/discovery.ts +432 -0
  138. package/src/pr/inline.ts +507 -0
  139. package/src/pr/plan.ts +366 -0
  140. package/src/pr/posting.ts +115 -0
  141. package/src/pr/pr-status.ts +787 -0
  142. package/src/pr/pr.ts +3642 -0
  143. package/src/pr/preflight.ts +1031 -0
  144. package/src/pr/publish-outcome.ts +361 -0
  145. package/src/pr/range.ts +119 -0
  146. package/src/pr/reverts-preflight.ts +606 -0
  147. package/src/pr/reverts.ts +377 -0
  148. package/src/pr/review-pr.ts +927 -0
  149. package/src/pr/status.ts +154 -0
  150. package/src/pr/target.ts +388 -0
  151. package/src/pr/teardown.ts +437 -0
  152. package/src/pr/worktree-setup.ts +60 -0
  153. package/src/production-runtime.ts +1877 -0
  154. package/src/progress.ts +487 -0
  155. package/src/rereview/adjudicate.ts +89 -0
  156. package/src/rereview/classify.ts +362 -0
  157. package/src/rereview/identity.ts +211 -0
  158. package/src/rereview/plan.ts +308 -0
  159. package/src/rereview/prepare.ts +1025 -0
  160. package/src/rereview/state.ts +767 -0
  161. package/src/rereview/verify.ts +241 -0
  162. package/src/review/boundary.ts +105 -0
  163. package/src/review/consolidate.ts +246 -0
  164. package/src/review/dedupe.ts +368 -0
  165. package/src/review/drafts.ts +448 -0
  166. package/src/review/findings-conformance.ts +120 -0
  167. package/src/review/findings.ts +714 -0
  168. package/src/review/pipeline.ts +3977 -0
  169. package/src/review/preflight.ts +3575 -0
  170. package/src/review/prompt-set.ts +177 -0
  171. package/src/review/proof-refs.ts +187 -0
  172. package/src/review/report.ts +1821 -0
  173. package/src/review/review.ts +490 -0
  174. package/src/review/root-cause.ts +120 -0
  175. package/src/review/route-preflight.ts +289 -0
  176. package/src/review/run.ts +601 -0
  177. package/src/review/scout.ts +323 -0
  178. package/src/review/size-gate.ts +595 -0
  179. package/src/review/spec.ts +235 -0
  180. package/src/review/step-runner.ts +233 -0
  181. package/src/runner-authority.ts +596 -0
  182. package/src/security/binding-policy.ts +115 -0
  183. package/src/security/credential-broker.ts +773 -0
  184. package/src/security/evidence-redaction.ts +62 -0
  185. package/src/security/execution-authority.ts +27 -0
  186. package/src/security/redact.ts +71 -0
  187. package/src/security/workspace-read-broker.ts +466 -0
  188. package/src/server/client.ts +190 -0
  189. package/src/server/preflight.ts +217 -0
  190. package/src/server/server.ts +327 -0
  191. package/src/signal-handler.ts +50 -0
  192. package/src/store/activity.ts +413 -0
  193. package/src/store/backfill-preflight.ts +49 -0
  194. package/src/store/backfill.ts +141 -0
  195. package/src/store/gc-preflight.ts +206 -0
  196. package/src/store/gc.ts +424 -0
  197. package/src/store/metrics-preflight.ts +229 -0
  198. package/src/store/metrics.ts +236 -0
  199. package/src/store/preflight.ts +748 -0
  200. package/src/store/store.ts +693 -0
  201. package/src/system-tools.ts +355 -0
  202. package/src/transport-registry.ts +1124 -0
  203. package/src/transports/claude-code-cli.ts +1348 -0
  204. package/src/transports/opencode-admission.ts +515 -0
  205. package/src/transports/opencode-client.ts +3328 -0
  206. package/src/transports/opencode-evidence.ts +557 -0
  207. package/src/transports/opencode-mcp.ts +248 -0
  208. package/src/transports/opencode-sdk.ts +2294 -0
  209. package/src/transports/opencode-server.ts +535 -0
  210. package/src/triage/adjudication.ts +113 -0
  211. package/src/triage/reply.ts +125 -0
  212. package/src/triage/triage.ts +255 -0
  213. package/src/ui/activity.ts +173 -0
  214. package/src/ui/config-edit.ts +816 -0
  215. package/src/ui/config.ts +462 -0
  216. package/src/ui/menu.ts +1325 -0
  217. package/src/ui/plan.ts +1039 -0
  218. package/src/ui/primitives.ts +300 -0
  219. package/src/ui/progress.ts +298 -0
  220. package/src/ui/result.ts +552 -0
  221. package/src/ui/review-menu.ts +312 -0
  222. package/src/ui/select.ts +528 -0
  223. package/src/ui/tree.ts +178 -0
  224. package/src/uninstaller.ts +479 -0
  225. package/src/updater.ts +836 -0
  226. package/src/usage.ts +77 -0
  227. package/src/watch/preflight.ts +1389 -0
  228. package/src/watch/watch.ts +1235 -0
  229. package/src/wizard.ts +877 -0
@@ -0,0 +1,552 @@
1
+ // The end-of-run result block, as LINES. Third member of the terminal
2
+ // surface's pure half (ui/primitives.ts formats, ui/select.ts asks, this one reports):
3
+ // same contract as both — everything is a total function of its inputs, the
4
+ // style flag and the width arrive as PARAMETERS, and the I/O shell in cli.ts
5
+ // owns the printing and every exit code.
6
+ //
7
+ // WHY it exists at all: this block was written TWICE, once at the end of
8
+ // local mode and once at the end of PR mode, with different label padding and
9
+ // a `posted:` line that duplicated one already printed during the run. Two
10
+ // copies of the last thing an operator reads is two chances to drift, and
11
+ // neither copy could be tested because both were a run of `log()` calls
12
+ // inside a 400-line async shell. The mode-specific parts (worktree hint, links,
13
+ // extra artifacts) are optional inputs, not a second renderer.
14
+ //
15
+ // WHY it prints the FINDINGS: after five minutes and $4 the terminal used to
16
+ // report counts and file paths and never once said what was found — the
17
+ // payload was the one thing you had to leave the terminal to read. Everything
18
+ // below the header exists to end that.
19
+
20
+ import type { Finding, FindingsDocument } from "#review/findings";
21
+ import {
22
+ blobUrl,
23
+ coverageSentence,
24
+ formatElapsed,
25
+ movedHeadSentence,
26
+ } from "#review/report";
27
+ import type { UnresolvedSpend } from "../execution/spend-limiter";
28
+ import { freeRouteEstimateText } from "./plan";
29
+ import {
30
+ cyan,
31
+ dim,
32
+ green,
33
+ red,
34
+ row,
35
+ severityLabel,
36
+ shortPath,
37
+ terminalWidth,
38
+ truncate,
39
+ wrapText,
40
+ yellow,
41
+ } from "./primitives";
42
+ import { FREE_STEPS_NOTE, type FreeBillingMode } from "./select";
43
+
44
+ interface ResultWorktree {
45
+ gitDirOwner: string;
46
+ worktreePath: string;
47
+ }
48
+
49
+ // D1-08 PR5b (D8): the run's unresolved spend reservations, surfaced here so
50
+ // the fencing gap (design decision D7: breaker state does not survive a
51
+ // process restart) is visible in the terminal a human actually reads, not
52
+ // only in pipeline.json. A plain alias over `UnresolvedSpend[]` — the
53
+ // pipeline-level shape already carries everything this block prints.
54
+ export type ResultUnresolved = readonly UnresolvedSpend[];
55
+
56
+ // What it takes to turn a finding into something clickable. Absent when the
57
+ // repo has no usable github remote, which is the honest degradation: the block
58
+ // falls back to today's plain `path:line` and never prints a guessed url.
59
+ //
60
+ // WHY a URL and not an interactive findings browser (the thing this replaced):
61
+ // a url survives in scrollback and can be opened whenever the reader gets to
62
+ // it, while an interactive view forces a decision in the moment and dies with
63
+ // the process. The cheaper surface is also the more durable one.
64
+ export interface ResultLinks {
65
+ // Canonical repo web url, no trailing slash: `https://github.com/owner/repo`.
66
+ webUrl: string;
67
+ // The sha the review actually read. Blob links are pinned to it, never to a
68
+ // branch name — a branch link drifts and starts pointing at other people's
69
+ // code under our claim.
70
+ headSha: string;
71
+ // PR mode only. Its presence is what earns the PR's own url a line, and it
72
+ // is also the pull number every comment fragment hangs off.
73
+ pr?: number;
74
+ // findingId -> the url of the comment this finding was POSTED as, when it
75
+ // was. Preferred over a blob link because it lands the reader in the
76
+ // conversation where they will reply, not in a read-only file view.
77
+ commentUrls?: ReadonlyMap<string, string>;
78
+ }
79
+
80
+ export interface ResultInput {
81
+ // The document, not a pre-chewed tally: every count in the header is
82
+ // derived here, from the same bytes that were just written to disk, so the
83
+ // terminal and findings.json cannot disagree about what the run found.
84
+ doc: FindingsDocument;
85
+ // CASH, and only cash — the figure the header's `$X.XX` reports and the one
86
+ // budget enforcement is allowed to read (§8: "Budget enforcement uses cash
87
+ // only"). On a Claude subscription or a free route this is a truthful $0.00.
88
+ costUsd: number;
89
+ // #173 (§8: "Artifacts and reports show cash and notional totals
90
+ // separately"). The list-basis figure a subscription run was NOT charged,
91
+ // kept strictly apart from `costUsd` and rendered with its own label — the
92
+ // design's "research comparisons may use notional only when clearly
93
+ // labelled" is a rendering obligation, not just a storage one.
94
+ //
95
+ // Optional, and absent means NO ROW rather than a `$0.00` one: a runner that
96
+ // reports no normalized usage has no list figure to show, and printing one
97
+ // it never produced is the fabrication the whole usage slice exists to
98
+ // prevent.
99
+ notionalUsd?: number;
100
+ // W3-FOOTER: the route's billing, derived by freeBillingMode from the same
101
+ // free-step count the plan card prints. Absent means no free share, and the
102
+ // footer keeps its subscription wording byte for byte.
103
+ billing?: FreeBillingMode;
104
+ wallMs: number;
105
+ estimate: { low: number; high: number };
106
+ // One directory plus the basenames written inside it. The full paths still
107
+ // go to pipeline.json — three absolute paths sharing a 60-char prefix cost
108
+ // three lines and carry one bit each (the shortPath rule, applied to the
109
+ // place that motivated it).
110
+ runDir: string;
111
+ artifacts: string[];
112
+ // PR mode only: the worktree is kept and reused BY DECISION, so the block
113
+ // hands over the exact removal command. `worktree remove`, never `rm -rf` —
114
+ // a live codegraph daemon holds .codegraph/daemon.sock.
115
+ worktree?: ResultWorktree;
116
+ links?: ResultLinks;
117
+ // PR mode only, and only on a CONFIRMED mismatch (GitHub #39): the PR's
118
+ // head as GitHub reported it immediately before posting, when it is not
119
+ // the head this run reviewed. Optional, matching this interface's own
120
+ // style for mode-specific inputs (`links`, `worktree`) —
121
+ // unlike renderPrComment's required parameter, there is exactly ONE
122
+ // production call site for this block and its test pins it, so an
123
+ // omission cannot hide in a second caller.
124
+ movedHeadSha?: string;
125
+ sessionFailed: boolean;
126
+ // D1-08 PR5b (D8): present and non-empty exactly when at least one spend
127
+ // reservation ended `unresolved_remote` this run. Its presence is what
128
+ // marks the header's `$X.XX` figure as a FLOOR rather than a total (the
129
+ // known cost is real; the unresolved bucket's true cost is not) and what
130
+ // earns the run a footer row naming the fenced bucket(s).
131
+ unresolved?: ResultUnresolved;
132
+ styles: boolean;
133
+ width?: number;
134
+ }
135
+
136
+ const MIN_WIDTH = 40;
137
+ const MAX_WIDTH = 96;
138
+ // Body indents: the marker column, then the prose column under it.
139
+ const MARKER_INDENT = " ";
140
+ const PROSE_INDENT = " ";
141
+ // Wide enough for the longest footer label ("estimate", "worktree") plus a gap.
142
+ const FOOTER_LABEL_WIDTH = 12;
143
+
144
+ // Deliberately NOT ui/primitives.ts's box(): box truncates every body line to fit its
145
+ // border, and the one thing this block must never truncate away is a claim.
146
+ // So the card is a RULE — the top edge only — and the body below it is plain
147
+ // indented text that wraps. Shape: `╭─ left ───── right ─╮`.
148
+ // `spentDropped` is not cosmetic bookkeeping: when the terminal is too narrow
149
+ // for both halves the counts win and the spend comes OFF the rule, so the
150
+ // caller has to put it back as its own row. Reported rather than assumed,
151
+ // because "the money is never dropped" is only true if somebody relocates it.
152
+ function headerRule(
153
+ left: string,
154
+ right: string,
155
+ width: number,
156
+ styles: boolean,
157
+ ): { line: string; spentDropped: boolean } {
158
+ // 8 = "╭─ " + " " around the fill + " ─╮".
159
+ const fill = width - left.length - right.length - 8;
160
+ if (fill < 1) {
161
+ const shown = truncate(left, Math.max(width - 6, 1));
162
+ return {
163
+ line:
164
+ dim("╭─ ", styles) +
165
+ shown +
166
+ dim(` ${"─".repeat(Math.max(width - 5 - shown.length, 1))}╮`, styles),
167
+ spentDropped: true,
168
+ };
169
+ }
170
+ return {
171
+ line:
172
+ dim("╭─ ", styles) +
173
+ left +
174
+ dim(` ${"─".repeat(fill)} `, styles) +
175
+ right +
176
+ dim(" ─╮", styles),
177
+ spentDropped: false,
178
+ };
179
+ }
180
+
181
+ // A POSITIVE type test for the same reason report.ts's findingLocationLine
182
+ // carries one: `=== undefined ||` let a null symbol through to `.length` and
183
+ // threw. This was the EARLIER of the two crash sites in PR #50's defect — the
184
+ // terminal block an operator reads at the end of every run, reached before
185
+ // posting is ever attempted.
186
+ function locationOf(f: Finding): string {
187
+ return typeof f.symbol === "string" && f.symbol.length > 0
188
+ ? `${f.path}:${f.line} · ${f.symbol}`
189
+ : `${f.path}:${f.line}`;
190
+ }
191
+
192
+ // The tier as a marker, because the tier is what decides whether a human must
193
+ // act (the rule severityLabel's colour half already encodes). Returned WITH
194
+ // its trailing space: ⛔ is one code unit but renders TWO columns wide, so the
195
+ // padding cannot be computed from `.length` and is baked in here instead —
196
+ // otherwise the severity column of a blocking and an advisory finding sit one
197
+ // column apart on screen while looking identical in a string comparison.
198
+ function tierMarker(f: Finding): string {
199
+ return f.tier === "blocking" ? "⛔ " : "· ";
200
+ }
201
+
202
+ // Where a reader should go to act on this finding, in priority order:
203
+ // 1. its own posted comment, when the run posted one — that is the thread
204
+ // the reply belongs in, so it beats a read-only file view outright;
205
+ // 2. the blob at the reviewed head sha, via report.ts's shared blobUrl.
206
+ // `undefined` when there are no links at all, which is the plain-location
207
+ // fallback, never a fabricated url.
208
+ function findingUrl(
209
+ f: Finding,
210
+ links: ResultLinks | undefined,
211
+ ): string | undefined {
212
+ if (links === undefined) return undefined;
213
+ const posted = links.commentUrls?.get(f.id);
214
+ if (posted !== undefined) return posted;
215
+ return blobUrl(links.webUrl, links.headSha, f.path, `L${f.line}`);
216
+ }
217
+
218
+ // One finding: marker + severity + location, the claim wrapped underneath, the
219
+ // refuter's verdict as the provenance line, and — last, because it is the
220
+ // ACTION rather than the evidence — a clickable url. NOTHING is truncated — a
221
+ // claim is the payload, and a payload you have to open a file to read is the
222
+ // defect this whole work unit fixes.
223
+ //
224
+ // The url gets a whole line to itself and is passed through neither wrapText
225
+ // nor truncate: a folded url is not clickable and a truncated one is a lie
226
+ // about where the finding lives, so an overlong line is the correct trade
227
+ // (exactly the reasoning wrapText's own comment gives for never splitting a
228
+ // long word, and the worktree-removal command below).
229
+ //
230
+ // Built with padding computed from the UNSTYLED severity and painted per
231
+ // segment: an escape sequence inside a measured string is counted as visible
232
+ // width, which is the same trap markerRowLines documents in cli.ts.
233
+ function findingLines(
234
+ f: Finding,
235
+ indent: string,
236
+ width: number,
237
+ styles: boolean,
238
+ links: ResultLinks | undefined,
239
+ ): string[] {
240
+ const pad = " ".repeat(Math.max(10 - f.severity.length, 1));
241
+ const prose = indent + PROSE_INDENT.slice(0, 3);
242
+ const proseWidth = Math.max(width - prose.length, 20);
243
+ const url = findingUrl(f, links);
244
+ return [
245
+ `${indent}${tierMarker(f)}` +
246
+ `${severityLabel(f.severity, f.tier, styles)}${pad}` +
247
+ cyan(locationOf(f), styles),
248
+ ...wrapText(f.claim, proseWidth).map((line) => prose + line),
249
+ prose +
250
+ dim(
251
+ `↳ refuter ${f.refuter_verdict} · ${f.hops_used} hop(s) · ` +
252
+ `${f.hunter} · ${f.evidence_class}`,
253
+ styles,
254
+ ),
255
+ ...(url === undefined
256
+ ? []
257
+ : [prose + dim("↗ ", styles) + cyan(url, styles)]),
258
+ ];
259
+ }
260
+
261
+ // Findings in document order, except that findings sharing a root cause are
262
+ // pulled together under their cluster id. That grouping is real signal the old
263
+ // block flattened into a bare "K distinct root cause(s)": three findings on
264
+ // one defect and three separate defects are the same number there.
265
+ //
266
+ // MEASUREMENT ONLY, exactly as review/root-cause.ts insists: this reorders lines on a
267
+ // terminal. Nothing here touches findings[], and findings.json is already on
268
+ // disk by the time this runs.
269
+ function findingsSection(
270
+ doc: FindingsDocument,
271
+ width: number,
272
+ styles: boolean,
273
+ links: ResultLinks | undefined,
274
+ ): string[] {
275
+ if (doc.findings.length === 0) return [];
276
+ const byId = new Map(doc.findings.map((f) => [f.id, f]));
277
+ // Only clusters with two or more findings STILL PRESENT earn a header: a
278
+ // refuted sibling leaves a cluster of one, and "shared root cause" over a
279
+ // single finding is noise.
280
+ const groups = new Map<string, Finding[]>();
281
+ for (const cluster of doc.debug.root_causes?.clusters ?? []) {
282
+ const members = cluster.finding_ids
283
+ .map((id) => byId.get(id))
284
+ .filter((f): f is Finding => f !== undefined);
285
+ if (members.length > 1) groups.set(cluster.id, members);
286
+ }
287
+ const clusterOf = new Map<string, string>();
288
+ for (const [id, members] of groups) {
289
+ for (const member of members) clusterOf.set(member.id, id);
290
+ }
291
+ const lines: string[] = [];
292
+ const emitted = new Set<string>();
293
+ for (const finding of doc.findings) {
294
+ if (emitted.has(finding.id)) continue;
295
+ const cluster = clusterOf.get(finding.id);
296
+ const members = cluster === undefined ? undefined : groups.get(cluster);
297
+ if (cluster === undefined || members === undefined) {
298
+ lines.push(
299
+ "",
300
+ ...findingLines(finding, MARKER_INDENT, width, styles, links),
301
+ );
302
+ emitted.add(finding.id);
303
+ continue;
304
+ }
305
+ lines.push(
306
+ "",
307
+ MARKER_INDENT +
308
+ dim(`${cluster} · ${members.length} findings, one root cause`, styles),
309
+ );
310
+ for (const member of members) {
311
+ lines.push(
312
+ ...findingLines(member, `${MARKER_INDENT} `, width, styles, links),
313
+ );
314
+ emitted.add(member.id);
315
+ }
316
+ }
317
+ return lines;
318
+ }
319
+
320
+ // The terminal half of GitHub #39, and the summary comment's twin — same
321
+ // sentence, same order relative to the incompleteness notice, different
322
+ // paint. It sits ABOVE incompleteLines for the reason spelled out in
323
+ // renderPrComment: this one says WHICH CODE everything below describes, the
324
+ // #42 one says how much of it was looked at, and reading them the other way
325
+ // round is reading them wrong.
326
+ //
327
+ // NOT suppressed on `sessionFailed`, unlike incompleteLines: a dead session
328
+ // posts nothing, so the moved head can only reach here from a run that
329
+ // really did post — and if a caller ever does hand it in on a failed
330
+ // session, "the PR moved" is still true and still worth the two lines.
331
+ function movedHeadLines(
332
+ reviewedSha: string,
333
+ currentSha: string,
334
+ width: number,
335
+ styles: boolean,
336
+ ): string[] {
337
+ const headWidth = Math.max(width - MARKER_INDENT.length, 20);
338
+ const proseWidth = Math.max(width - PROSE_INDENT.length, 20);
339
+ return [
340
+ "",
341
+ ...wrapText(
342
+ "the PR head moved while this review ran — the comments are pinned " +
343
+ "to the commit that was reviewed",
344
+ headWidth,
345
+ ).map((line) => MARKER_INDENT + yellow(line, styles)),
346
+ // Wrapped, never truncated, for findingLines' reason: a 40-char sha cut
347
+ // in half is worse than no sha at all.
348
+ ...wrapText(
349
+ movedHeadSentence(reviewedSha, currentSha, (text) => text),
350
+ proseWidth,
351
+ ).map((line) => PROSE_INDENT + dim(line, styles)),
352
+ ];
353
+ }
354
+
355
+ // The terminal half of GitHub #42, and the same argument as the summary
356
+ // comment's: `partial · ` in the header rule says the run was incomplete in
357
+ // two words, but two words next to five counts is a footnote wearing a
358
+ // header's clothes, and the green all-clear below it read as a clean bill
359
+ // anyway. So a partial run gets a line of its own that NAMES what was lost,
360
+ // and the green line is withdrawn (see renderResult).
361
+ //
362
+ // Suppressed when `sessionFailed`: a dead session prints "every hunter failed
363
+ // — this run reviewed nothing." last, which is the whole message there, and
364
+ // listing the same corpses one paragraph earlier only softens it.
365
+ function incompleteLines(
366
+ doc: FindingsDocument,
367
+ width: number,
368
+ styles: boolean,
369
+ ): string[] {
370
+ // Wrapped, never truncated, for findingLines' reason: the one thing this
371
+ // block must not do is drop the half of a sentence that says what is
372
+ // missing.
373
+ const headWidth = Math.max(width - MARKER_INDENT.length, 20);
374
+ const proseWidth = Math.max(width - PROSE_INDENT.length, 20);
375
+ return [
376
+ "",
377
+ ...wrapText(
378
+ "incomplete review — at least one agent did not finish, so the " +
379
+ "counts above are a floor, not a verdict",
380
+ headWidth,
381
+ ).map((line) => MARKER_INDENT + yellow(line, styles)),
382
+ ...wrapText(
383
+ coverageSentence(doc, (key) => key),
384
+ proseWidth,
385
+ ).map((line) => PROSE_INDENT + dim(line, styles)),
386
+ ];
387
+ }
388
+
389
+ export function renderResult(input: ResultInput): string[] {
390
+ const width = Math.max(
391
+ Math.min(input.width ?? terminalWidth(), MAX_WIDTH),
392
+ MIN_WIDTH,
393
+ );
394
+ const styles = input.styles;
395
+ const doc = input.doc;
396
+ const blocking = doc.findings.filter((f) => f.tier === "blocking").length;
397
+ const advisory = doc.findings.length - blocking;
398
+ const refuted = doc.debug.refuted.length;
399
+ // `partial` in the header, never in a footnote: a run where a hunter died
400
+ // found less than a complete one would have, and every count above is read
401
+ // in that light or misread.
402
+ const status = doc.run_status === "partial" ? "partial · " : "";
403
+ const left =
404
+ `${status}${blocking} blocking · ${advisory} advisory · ` +
405
+ `${refuted} refuted`;
406
+ // D8: a bucket fenced by an unresolved_remote reservation means the real
407
+ // cost of that bucket's attempt is UNKNOWN — printing a bare `$X.XX` there
408
+ // is the exact "$0 on parse failure" collapse this slice exists to kill,
409
+ // just relocated to the terminal's header line. `≥` marks it a floor.
410
+ const hasUnresolved = (input.unresolved?.length ?? 0) > 0;
411
+ const costLabel = `${hasUnresolved ? "≥" : ""}$${input.costUsd.toFixed(2)}`;
412
+ const right = `${costLabel} · ${formatElapsed(input.wallMs)}`;
413
+ const header = headerRule(left, right, width, styles);
414
+ // The PR's own url, directly under the rule rather than down in the artifact
415
+ // footer, for two reasons. It is the WHERE of everything above and below it,
416
+ // so it belongs with the counts it describes; and the footer is built out of
417
+ // row(), which wraps its value to the value column — the one thing a url
418
+ // must never do. Local mode has no PR and gets no such line.
419
+ const prUrl =
420
+ input.links?.pr === undefined
421
+ ? undefined
422
+ : `${input.links.webUrl}/pull/${input.links.pr}`;
423
+ // GitHub #42: an incomplete run says so above its own payload, naming the
424
+ // agents that were lost, so nothing below is read as full coverage.
425
+ const incomplete = doc.run_status === "partial" && !input.sessionFailed;
426
+ const lines = [
427
+ "",
428
+ header.line,
429
+ ...(prUrl === undefined
430
+ ? []
431
+ : [MARKER_INDENT + dim("↗ ", styles) + cyan(prUrl, styles)]),
432
+ // GitHub #39, above the #42 block on purpose — see movedHeadLines.
433
+ ...(input.movedHeadSha === undefined
434
+ ? []
435
+ : movedHeadLines(doc.head_sha, input.movedHeadSha, width, styles)),
436
+ ...(incomplete ? incompleteLines(doc, width, styles) : []),
437
+ ...findingsSection(doc, width, styles, input.links),
438
+ ];
439
+ // A green all-clear is only allowed when the review actually RAN. A dead
440
+ // session also reaches here with `findings: []`, and "no findings" over a
441
+ // review that never happened is the same lie the posting
442
+ // guard exists to prevent (cli.ts steps 13/14) — the red line below is the
443
+ // whole message in that case.
444
+ //
445
+ // `partial` joined that exclusion for GitHub #42: a run where some agents
446
+ // died and the survivors found nothing is not a clean bill either, and
447
+ // green is the strongest clean-bill signal this block has. The yellow
448
+ // notice above already carries the count and the names, so the branch is
449
+ // simply withdrawn rather than restated.
450
+ if (doc.findings.length === 0 && !input.sessionFailed && !incomplete) {
451
+ lines.push(
452
+ "",
453
+ MARKER_INDENT +
454
+ green("no findings survived to this point", styles) +
455
+ (refuted === 0 ? "" : dim(` — ${refuted} refuted and dropped`, styles)),
456
+ );
457
+ }
458
+ // The footer goes through row(), so a run dir plus four basenames wraps to
459
+ // the value column instead of running off the terminal. Values are handed to
460
+ // it UNPAINTED for the reason row() documents: it measures the value to
461
+ // place the wrap, and an escape sequence inside one is counted as width.
462
+ const footer = { styles, width, indent: 2, labelWidth: FOOTER_LABEL_WIDTH };
463
+ lines.push(
464
+ "",
465
+ ...row(
466
+ "run dir",
467
+ shortPath(input.runDir) +
468
+ (input.artifacts.length === 0
469
+ ? ""
470
+ : ` · ${input.artifacts.join(" · ")}`),
471
+ footer,
472
+ ),
473
+ // The band is kept because it is the only thing that makes an overrun
474
+ // visible: both recorded cost incidents were under-estimates, and rule 6
475
+ // says every live run lands in a ledger.
476
+ ...row(
477
+ "estimate",
478
+ input.billing === "free"
479
+ ? freeRouteEstimateText(input.estimate)
480
+ : input.billing === "mixed"
481
+ ? `$${input.estimate.low.toFixed(2)}–$${input.estimate.high.toFixed(2)} ${FREE_STEPS_NOTE}`
482
+ : `$${input.estimate.low.toFixed(2)}–$${input.estimate.high.toFixed(2)}`,
483
+ footer,
484
+ ),
485
+ );
486
+ // #173: the second half of the §8 cash/notional split, and the reason the
487
+ // header's `$0.00` on a subscription run is informative rather than broken.
488
+ // Its own row, its own label, and wording that names the basis — a bare
489
+ // second dollar figure beside the first is exactly the mixing §8 forbids.
490
+ if (input.notionalUsd !== undefined) {
491
+ lines.push(
492
+ ...row(
493
+ "notional",
494
+ input.billing === "free"
495
+ ? `$${input.notionalUsd.toFixed(2)} at list price — not charged on a free route; ` +
496
+ "budget limits read the cash figure above"
497
+ : `$${input.notionalUsd.toFixed(2)} at list price — not charged on a ` +
498
+ "subscription; budget limits read the cash figure above",
499
+ footer,
500
+ ),
501
+ );
502
+ }
503
+ // D8: naming the fenced bucket(s) HERE, not only in pipeline.json, is the
504
+ // whole point of this row — see the module-level ResultUnresolved comment.
505
+ if (hasUnresolved) {
506
+ const buckets = [
507
+ ...new Set((input.unresolved ?? []).map((u) => u.bucketId)),
508
+ ];
509
+ lines.push(
510
+ ...row(
511
+ "unresolved",
512
+ `${input.unresolved?.length} spend reservation(s) unresolved in ` +
513
+ `bucket(s) ${buckets.join(", ")} — cost above is a floor; see ` +
514
+ "pipeline.json",
515
+ footer,
516
+ ),
517
+ );
518
+ }
519
+ // The relocation headerRule reported: on a terminal too narrow for the rule
520
+ // to carry both halves, what this run actually cost gets its own row instead
521
+ // of disappearing with the rule's right-hand segment.
522
+ if (header.spentDropped) {
523
+ lines.push(...row("spent", right, footer));
524
+ }
525
+ if (input.worktree) {
526
+ lines.push(
527
+ ...row(
528
+ "worktree",
529
+ "kept for finding-verification; remove it with",
530
+ footer,
531
+ ),
532
+ // The command on its OWN line and never wrapped: it exists to be copied,
533
+ // and a command broken across two indented lines is not copyable.
534
+ PROSE_INDENT +
535
+ dim(
536
+ `git -C ${input.worktree.gitDirOwner} worktree remove --force ` +
537
+ input.worktree.worktreePath,
538
+ styles,
539
+ ),
540
+ );
541
+ }
542
+ // The line that outranks every count above it. The exit code is the SHELL's
543
+ // (return 1 in local mode, postingExitCode in PR mode) — this only says so.
544
+ if (input.sessionFailed) {
545
+ lines.push(
546
+ "",
547
+ MARKER_INDENT +
548
+ red("every hunter failed — this run reviewed nothing.", styles),
549
+ );
550
+ }
551
+ return lines;
552
+ }