crysk 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +610 -2
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/adjudicator-dtg2axnh.md +86 -0
  10. package/dist/admission-config.example-a9vqmmad.json +9 -0
  11. package/dist/ci-admission-camfbx2b.md +122 -0
  12. package/dist/cli.js +42292 -0
  13. package/dist/consolidate-ac0mnfyj.md +24 -0
  14. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  15. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  16. package/dist/deep-review-parity-0ec904db.md +120 -0
  17. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  18. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  19. package/dist/index.js +20190 -0
  20. package/dist/opencode-ci-7b0be64p.md +141 -0
  21. package/dist/review-refuter-j4e9gezy.md +71 -0
  22. package/dist/scout-yvp153q7.md +140 -0
  23. package/dist/summarizer-zca44nxa.md +18 -0
  24. package/dist/workflow-w1g9szna.yml +151 -0
  25. package/package.json +82 -4
  26. package/prompts/consolidate.md +24 -0
  27. package/prompts/default/PROVENANCE.md +18 -0
  28. package/prompts/default/deep-review-lifecycle.md +362 -0
  29. package/prompts/default/deep-review-logic.md +156 -0
  30. package/prompts/default/deep-review-parity.md +120 -0
  31. package/prompts/default/deep-review-reliability.md +125 -0
  32. package/prompts/default/deep-review-resilience.md +118 -0
  33. package/prompts/default/review-refuter.md +71 -0
  34. package/prompts/scout.md +140 -0
  35. package/prompts/summarizer.md +18 -0
  36. package/skills/crysk/SKILL.md +74 -0
  37. package/skills/crysk-ci-setup/SKILL.md +134 -0
  38. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  39. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  40. package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
  41. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  42. package/skills/crysk-loop/SKILL.md +496 -0
  43. package/skills/crysk-loop/adjudicator.md +86 -0
  44. package/skills/crysk-pr/SKILL.md +66 -0
  45. package/src/agent-env.ts +1084 -0
  46. package/src/asset-manifest.ts +83 -0
  47. package/src/assets.d.ts +6 -0
  48. package/src/assets.ts +183 -0
  49. package/src/brand-paths.ts +155 -0
  50. package/src/brand.ts +255 -0
  51. package/src/ci/admission-ledger.ts +350 -0
  52. package/src/ci/classify-error.ts +73 -0
  53. package/src/ci/cli-record.ts +271 -0
  54. package/src/ci/force-comment.ts +39 -0
  55. package/src/ci/gates.ts +923 -0
  56. package/src/ci/outcome.ts +2181 -0
  57. package/src/ci/override.ts +187 -0
  58. package/src/ci/publish.ts +1639 -0
  59. package/src/ci/reporter.ts +626 -0
  60. package/src/ci/review-admission.ts +901 -0
  61. package/src/ci/review-levels.ts +310 -0
  62. package/src/ci/review-policy.ts +18 -0
  63. package/src/ci/review-risk.ts +184 -0
  64. package/src/ci/setup.ts +844 -0
  65. package/src/ci/trigger.ts +1353 -0
  66. package/src/cli.ts +348 -0
  67. package/src/commands/activity.ts +67 -0
  68. package/src/commands/ci-setup-questions.ts +397 -0
  69. package/src/commands/ci-setup.ts +381 -0
  70. package/src/commands/config.ts +99 -0
  71. package/src/commands/doctor.ts +108 -0
  72. package/src/commands/init.ts +139 -0
  73. package/src/commands/mcp.ts +10 -0
  74. package/src/commands/menu.ts +129 -0
  75. package/src/commands/post.ts +302 -0
  76. package/src/commands/skills.ts +83 -0
  77. package/src/commands/status.ts +173 -0
  78. package/src/commands/triage.ts +342 -0
  79. package/src/commands/uninstall.ts +37 -0
  80. package/src/commands/upgrade.ts +214 -0
  81. package/src/commands/usage.ts +98 -0
  82. package/src/compare/compare.ts +28 -0
  83. package/src/compare/floor-test.ts +471 -0
  84. package/src/compare/martian-adapter.ts +80 -0
  85. package/src/config/config.ts +267 -0
  86. package/src/corpus/corpus.ts +1094 -0
  87. package/src/corpus/preflight.ts +1789 -0
  88. package/src/diversity/accounting.ts +90 -0
  89. package/src/diversity/adjudication.ts +145 -0
  90. package/src/diversity/admission.ts +60 -0
  91. package/src/diversity/benchmark.ts +195 -0
  92. package/src/diversity/clustering.ts +285 -0
  93. package/src/diversity/errors.ts +7 -0
  94. package/src/diversity/identity.ts +285 -0
  95. package/src/diversity/index.ts +11 -0
  96. package/src/diversity/pipeline-integration.ts +448 -0
  97. package/src/diversity/projection.ts +57 -0
  98. package/src/diversity/self-contained.ts +68 -0
  99. package/src/diversity/target-validation.ts +179 -0
  100. package/src/doctor-migration.ts +209 -0
  101. package/src/doctor.ts +723 -0
  102. package/src/errors.ts +83 -0
  103. package/src/execution/admission.ts +75 -0
  104. package/src/execution/atomic-write.ts +35 -0
  105. package/src/execution/attempt-evidence.ts +415 -0
  106. package/src/execution/bucket-id.ts +136 -0
  107. package/src/execution/concurrency-limiter.ts +175 -0
  108. package/src/execution/contracts.ts +443 -0
  109. package/src/execution/failure-classification.ts +42 -0
  110. package/src/execution/failure-policy.ts +240 -0
  111. package/src/execution/harness.ts +2548 -0
  112. package/src/execution/settlement.ts +348 -0
  113. package/src/execution/spawned-process.ts +66 -0
  114. package/src/execution/spend-limiter.ts +424 -0
  115. package/src/execution/step-artifacts.ts +55 -0
  116. package/src/execution/usage-normalized.ts +469 -0
  117. package/src/git/git.ts +396 -0
  118. package/src/git/identity.ts +64 -0
  119. package/src/git/refs.ts +140 -0
  120. package/src/home-preflight.ts +443 -0
  121. package/src/home.ts +243 -0
  122. package/src/ignore-file.ts +336 -0
  123. package/src/ignore-read.ts +118 -0
  124. package/src/index.ts +34 -0
  125. package/src/legacy-launchd.ts +29 -0
  126. package/src/mcp/mcp.ts +150 -0
  127. package/src/mcp/preflight.ts +407 -0
  128. package/src/menu-context.ts +192 -0
  129. package/src/model/catalog.ts +251 -0
  130. package/src/model/exec-snapshots.ts +390 -0
  131. package/src/model/free-discovery.ts +302 -0
  132. package/src/model/provider-capabilities.ts +814 -0
  133. package/src/model/routing.ts +600 -0
  134. package/src/pr/admission.ts +847 -0
  135. package/src/pr/ci-admission-gate.ts +665 -0
  136. package/src/pr/ci-publish.ts +76 -0
  137. package/src/pr/discovery.ts +432 -0
  138. package/src/pr/inline.ts +507 -0
  139. package/src/pr/plan.ts +366 -0
  140. package/src/pr/posting.ts +115 -0
  141. package/src/pr/pr-status.ts +787 -0
  142. package/src/pr/pr.ts +3642 -0
  143. package/src/pr/preflight.ts +1031 -0
  144. package/src/pr/publish-outcome.ts +361 -0
  145. package/src/pr/range.ts +119 -0
  146. package/src/pr/reverts-preflight.ts +606 -0
  147. package/src/pr/reverts.ts +377 -0
  148. package/src/pr/review-pr.ts +927 -0
  149. package/src/pr/status.ts +154 -0
  150. package/src/pr/target.ts +388 -0
  151. package/src/pr/teardown.ts +437 -0
  152. package/src/pr/worktree-setup.ts +60 -0
  153. package/src/production-runtime.ts +1877 -0
  154. package/src/progress.ts +487 -0
  155. package/src/rereview/adjudicate.ts +89 -0
  156. package/src/rereview/classify.ts +362 -0
  157. package/src/rereview/identity.ts +211 -0
  158. package/src/rereview/plan.ts +308 -0
  159. package/src/rereview/prepare.ts +1025 -0
  160. package/src/rereview/state.ts +767 -0
  161. package/src/rereview/verify.ts +241 -0
  162. package/src/review/boundary.ts +105 -0
  163. package/src/review/consolidate.ts +246 -0
  164. package/src/review/dedupe.ts +368 -0
  165. package/src/review/drafts.ts +448 -0
  166. package/src/review/findings-conformance.ts +120 -0
  167. package/src/review/findings.ts +714 -0
  168. package/src/review/pipeline.ts +3977 -0
  169. package/src/review/preflight.ts +3575 -0
  170. package/src/review/prompt-set.ts +177 -0
  171. package/src/review/proof-refs.ts +187 -0
  172. package/src/review/report.ts +1821 -0
  173. package/src/review/review.ts +490 -0
  174. package/src/review/root-cause.ts +120 -0
  175. package/src/review/route-preflight.ts +289 -0
  176. package/src/review/run.ts +601 -0
  177. package/src/review/scout.ts +323 -0
  178. package/src/review/size-gate.ts +595 -0
  179. package/src/review/spec.ts +235 -0
  180. package/src/review/step-runner.ts +233 -0
  181. package/src/runner-authority.ts +596 -0
  182. package/src/security/binding-policy.ts +115 -0
  183. package/src/security/credential-broker.ts +773 -0
  184. package/src/security/evidence-redaction.ts +62 -0
  185. package/src/security/execution-authority.ts +27 -0
  186. package/src/security/redact.ts +71 -0
  187. package/src/security/workspace-read-broker.ts +466 -0
  188. package/src/server/client.ts +190 -0
  189. package/src/server/preflight.ts +217 -0
  190. package/src/server/server.ts +327 -0
  191. package/src/signal-handler.ts +50 -0
  192. package/src/store/activity.ts +413 -0
  193. package/src/store/backfill-preflight.ts +49 -0
  194. package/src/store/backfill.ts +141 -0
  195. package/src/store/gc-preflight.ts +206 -0
  196. package/src/store/gc.ts +424 -0
  197. package/src/store/metrics-preflight.ts +229 -0
  198. package/src/store/metrics.ts +236 -0
  199. package/src/store/preflight.ts +748 -0
  200. package/src/store/store.ts +693 -0
  201. package/src/system-tools.ts +355 -0
  202. package/src/transport-registry.ts +1124 -0
  203. package/src/transports/claude-code-cli.ts +1348 -0
  204. package/src/transports/opencode-admission.ts +515 -0
  205. package/src/transports/opencode-client.ts +3328 -0
  206. package/src/transports/opencode-evidence.ts +557 -0
  207. package/src/transports/opencode-mcp.ts +248 -0
  208. package/src/transports/opencode-sdk.ts +2294 -0
  209. package/src/transports/opencode-server.ts +535 -0
  210. package/src/triage/adjudication.ts +113 -0
  211. package/src/triage/reply.ts +125 -0
  212. package/src/triage/triage.ts +255 -0
  213. package/src/ui/activity.ts +173 -0
  214. package/src/ui/config-edit.ts +816 -0
  215. package/src/ui/config.ts +462 -0
  216. package/src/ui/menu.ts +1325 -0
  217. package/src/ui/plan.ts +1039 -0
  218. package/src/ui/primitives.ts +300 -0
  219. package/src/ui/progress.ts +298 -0
  220. package/src/ui/result.ts +552 -0
  221. package/src/ui/review-menu.ts +312 -0
  222. package/src/ui/select.ts +528 -0
  223. package/src/ui/tree.ts +178 -0
  224. package/src/uninstaller.ts +479 -0
  225. package/src/updater.ts +836 -0
  226. package/src/usage.ts +77 -0
  227. package/src/watch/preflight.ts +1389 -0
  228. package/src/watch/watch.ts +1235 -0
  229. package/src/wizard.ts +877 -0
@@ -0,0 +1,626 @@
1
+ // CI headless mode's reporter (ROADMAP Pillar 3, GitHub Actions): the pure
2
+ // half turns a review outcome into GitHub Actions workflow-command lines and
3
+ // `$GITHUB_STEP_SUMMARY` Markdown; the impure half appends those bytes to
4
+ // the two files GitHub Actions hands the job through the environment.
5
+ //
6
+ // Purity split, mirroring src/ui/primitives.ts's one documented impure pair
7
+ // (`styleEnabled()`/`terminalWidth()`): `formatWorkflowCommand`,
8
+ // `renderStepSummary`, and `formatCiOutputs` are total functions of their
9
+ // inputs — no file I/O, no `process.env` sniffing, no `log()` call. Every
10
+ // byte they need arrives as a parameter, so all three stay offline-testable
11
+ // and re-renderable from a stored artifact. `appendStepSummary` and
12
+ // `appendCiOutputs` are the ONLY functions in this module that touch the
13
+ // filesystem, and they do nothing but append the pure functions' output to
14
+ // a caller-supplied path — the exact shape GitHub Actions expects for
15
+ // `$GITHUB_STEP_SUMMARY` and `$GITHUB_OUTPUT` (both files a step appends to
16
+ // across multiple writes in the same job, never overwrites).
17
+ //
18
+ // Reuses report.ts/review/findings.ts rather than re-deriving their contracts:
19
+ // `Finding`/`Severity`/`Tier` (review/findings.ts) for finding shape, and
20
+ // `severityEmoji`, `blobUrl`, `formatElapsed`, `PrCommentDelta` (report.ts)
21
+ // for the emoji mapping, blob-link builder, compact duration format, and
22
+ // the re-review delta's data shape — the same severity glyph and blob URL a
23
+ // reader sees on the PR comment must be the one this job summary shows.
24
+ // `deltaLine`/`usd`/`code`/`severityRank` stay PRIVATE in report.ts, so this
25
+ // module writes small local equivalents rather than exporting report.ts
26
+ // internals for a single extra caller.
27
+
28
+ // Node's fs/promises, not Bun.write: Bun.write always OVERWRITES its target,
29
+ // and both $GITHUB_STEP_SUMMARY and $GITHUB_OUTPUT are files a single job
30
+ // step may append to more than once (progress groups, then a final summary;
31
+ // multiple output keys written across several tool calls). An overwrite here
32
+ // would silently destroy an earlier step's contribution to the same file.
33
+ import { appendFile } from "node:fs/promises";
34
+ import type { CiMode } from "#pr/preflight";
35
+ import type { Finding, Severity } from "#review/findings";
36
+ import {
37
+ blobUrl,
38
+ formatElapsed,
39
+ type PrCommentDelta,
40
+ severityEmoji,
41
+ } from "#review/report";
42
+ import { log } from "#ui/primitives";
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // Workflow commands (`::group::`, `::endgroup::`, `::notice::`, `::warning::`,
46
+ // `::error::`) — https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions
47
+ // ---------------------------------------------------------------------------
48
+
49
+ export type WorkflowCommandName =
50
+ | "group"
51
+ | "endgroup"
52
+ | "notice"
53
+ | "warning"
54
+ | "error";
55
+
56
+ export interface WorkflowCommandOptions {
57
+ file?: string;
58
+ line?: number;
59
+ endLine?: number;
60
+ col?: number;
61
+ endColumn?: number;
62
+ title?: string;
63
+ }
64
+
65
+ // GitHub's documented data-escaping table for a command's message body.
66
+ function escapeData(value: string): string {
67
+ return value
68
+ .replaceAll("%", "%25")
69
+ .replaceAll("\r", "%0D")
70
+ .replaceAll("\n", "%0A");
71
+ }
72
+
73
+ // The property-value table additionally escapes `:` and `,` — those are the
74
+ // two characters the `key=value,key=value` property list itself uses as
75
+ // delimiters, so a raw one in a value (a Windows path's drive colon, a
76
+ // title with a comma) would silently split into the wrong property.
77
+ function escapeProperty(value: string): string {
78
+ return value
79
+ .replaceAll("%", "%25")
80
+ .replaceAll("\r", "%0D")
81
+ .replaceAll("\n", "%0A")
82
+ .replaceAll(":", "%3A")
83
+ .replaceAll(",", "%2C");
84
+ }
85
+
86
+ // Fixed emission order so the same options object always renders the same
87
+ // property string — a test asserting an exact command line would otherwise
88
+ // be at the mercy of `Object.entries`' insertion order at each call site.
89
+ const PROPERTY_ORDER = [
90
+ "file",
91
+ "line",
92
+ "endLine",
93
+ "col",
94
+ "endColumn",
95
+ "title",
96
+ ] as const satisfies readonly (keyof WorkflowCommandOptions)[];
97
+
98
+ // Pure emitter for one GitHub Actions workflow-command line. `group` carries
99
+ // its title as the message (GitHub's own convention — `::group::<title>`
100
+ // has no property list); `endgroup` takes neither message nor properties.
101
+ export function formatWorkflowCommand(
102
+ command: WorkflowCommandName,
103
+ message = "",
104
+ options?: WorkflowCommandOptions,
105
+ ): string {
106
+ if (command === "endgroup") return "::endgroup::";
107
+ if (command === "group") return `::group::${escapeData(message)}`;
108
+ const props = PROPERTY_ORDER.filter(
109
+ (key) => options?.[key] !== undefined,
110
+ ).map((key) => `${key}=${escapeProperty(String(options?.[key]))}`);
111
+ const head =
112
+ props.length > 0 ? `::${command} ${props.join(",")}::` : `::${command}::`;
113
+ return `${head}${escapeData(message)}`;
114
+ }
115
+
116
+ // ---------------------------------------------------------------------------
117
+ // $GITHUB_STEP_SUMMARY — the job summary Markdown (spec 2.1).
118
+ // ---------------------------------------------------------------------------
119
+
120
+ // The three CiSummaryData members stay UNEXPORTED: `CiSummaryData` itself is
121
+ // the whole public contract a caller needs — a discriminated-union literal
122
+ // (`{ kind: "reviewed", ... }`) type-checks against it directly, exactly as
123
+ // every renderStepSummary test below constructs one. Exporting the members
124
+ // individually before a real caller needs to name one on its own would be
125
+ // an export for a hypothetical consumer (project rule 2) — Phase 3 either
126
+ // keeps using the union the same way or promotes exactly the member it
127
+ // needs, once it exists.
128
+ interface CiReviewSummary {
129
+ kind: "reviewed";
130
+ prNumber: number;
131
+ headSha: string;
132
+ findings: readonly Finding[];
133
+ costUsdEst: number;
134
+ wallMs: number;
135
+ model: string;
136
+ // Cosmetic and optional, same contract as renderPrComment's repoWebUrl
137
+ // (report.ts): absent renders plain code spans instead of blob links.
138
+ repoWebUrl?: string;
139
+ delta?: PrCommentDelta;
140
+ }
141
+
142
+ interface CiSkipSizeSummary {
143
+ kind: "skipped-size";
144
+ prNumber: number;
145
+ changedLines: number;
146
+ changedFiles: number;
147
+ maxChangedLines: number;
148
+ maxChangedFiles: number;
149
+ }
150
+
151
+ interface CiSkipBudgetSummary {
152
+ kind: "skipped-budget";
153
+ prNumber: number;
154
+ estimatedCostUsd: number;
155
+ budgetUsd: number;
156
+ }
157
+
158
+ interface CiSkipCoverageSummary {
159
+ kind: "skipped-coverage";
160
+ prNumber: number;
161
+ reason: string;
162
+ detail: string;
163
+ priorScore: number;
164
+ minScore: number;
165
+ reviewCount: number;
166
+ maxAttempts: number;
167
+ decision?: "skip";
168
+ admissionReason?: string;
169
+ currentHead?: string;
170
+ reviewedHead?: string | null;
171
+ riskClass?: string;
172
+ riskReason?: string;
173
+ remainingBudget?: number;
174
+ policyMode?: string;
175
+ policyHash?: string;
176
+ }
177
+
178
+ interface CiManualRequiredSummary {
179
+ kind: "manual-required";
180
+ prNumber: number;
181
+ reason: string;
182
+ detail: string;
183
+ priorScore: number;
184
+ reviewCount: number;
185
+ maxAttempts: number;
186
+ decision?: "manual-required";
187
+ admissionReason?: string;
188
+ currentHead?: string;
189
+ reviewedHead?: string | null;
190
+ riskClass?: string;
191
+ riskReason?: string;
192
+ remainingBudget?: number;
193
+ policyMode?: string;
194
+ policyHash?: string;
195
+ }
196
+
197
+ export type CiSummaryData =
198
+ | CiReviewSummary
199
+ | CiSkipSizeSummary
200
+ | CiSkipBudgetSummary
201
+ | CiSkipCoverageSummary
202
+ | CiManualRequiredSummary;
203
+
204
+ // Footer attributing pr-hero as an AI code review assistant (spec 2.1), shared
205
+ // by all five variants. Advisory keeps the "not a merge gate" register the PR
206
+ // comment's own footer has (renderPrComment, report.ts). Gate says the report
207
+ // backs the commit status that is the required check (S4), because a gate
208
+ // that disclaims being one would contradict its own red status.
209
+ const ADVISORY_FOOTER =
210
+ "<sub>Crysk — AI code review assistant. Assistant report, not a merge gate.</sub>";
211
+ const GATE_FOOTER =
212
+ "<sub>Crysk — AI code review assistant. Assistant report backing the crysk commit status, the required check in gate mode.</sub>";
213
+
214
+ function footerFor(ciMode: CiMode): string {
215
+ return ciMode === "gate" ? GATE_FOOTER : ADVISORY_FOOTER;
216
+ }
217
+
218
+ function severityRank(severity: Severity): number {
219
+ switch (severity) {
220
+ case "BLOCKER":
221
+ return 0;
222
+ case "CRITICAL":
223
+ return 1;
224
+ case "WARNING":
225
+ return 2;
226
+ case "SUGGESTION":
227
+ return 3;
228
+ }
229
+ }
230
+
231
+ function oneLine(text: string): string {
232
+ return text.replace(/\s+/g, " ").trim();
233
+ }
234
+
235
+ // Grouped by file (spec 2.1: "grouped by file and severity tier"), sorted
236
+ // so the summary is deterministic regardless of hunter fan-out order: path
237
+ // ascending, then severity rank, then line. Map preserves insertion order,
238
+ // and every finding for a path is inserted contiguously because the source
239
+ // array is pre-sorted by path first — so iterating the map yields paths in
240
+ // alphabetical order without a second sort pass.
241
+ function groupFindingsByPath(
242
+ findings: readonly Finding[],
243
+ ): Map<string, Finding[]> {
244
+ const sorted = [...findings].sort((a, b) => {
245
+ if (a.path !== b.path) return a.path < b.path ? -1 : 1;
246
+ const rankDiff = severityRank(a.severity) - severityRank(b.severity);
247
+ if (rankDiff !== 0) return rankDiff;
248
+ return a.line - b.line;
249
+ });
250
+ const groups = new Map<string, Finding[]>();
251
+ for (const finding of sorted) {
252
+ const existing = groups.get(finding.path);
253
+ if (existing) existing.push(finding);
254
+ else groups.set(finding.path, [finding]);
255
+ }
256
+ return groups;
257
+ }
258
+
259
+ function findingLine(
260
+ finding: Finding,
261
+ headSha: string,
262
+ webUrl: string | undefined,
263
+ ): string {
264
+ const loc = `${finding.path}:${finding.line}`;
265
+ const linked =
266
+ webUrl === undefined
267
+ ? `\`${loc}\``
268
+ : `[\`${loc}\`](${blobUrl(webUrl, headSha, finding.path, `L${finding.line}`)})`;
269
+ return (
270
+ `- ${severityEmoji(finding.severity)} ${finding.severity} · ` +
271
+ `${finding.tier} — ${linked} — ${oneLine(finding.claim)}`
272
+ );
273
+ }
274
+
275
+ // Local equivalent of report.ts's private `deltaLine` — same PrCommentDelta
276
+ // shape and wording, kept in sync by convention since that helper is not
277
+ // exported for a single extra caller (see module header).
278
+ function formatDeltaLine(delta: PrCommentDelta): string {
279
+ const since =
280
+ delta.previousHeadSha === undefined
281
+ ? "Δ"
282
+ : `Δ since \`${delta.previousHeadSha.slice(0, 8)}\``;
283
+ if (delta.rereview !== undefined) {
284
+ const r = delta.rereview;
285
+ const parts: string[] = [];
286
+ if (r.verifiedGone > 0) parts.push(`${r.verifiedGone} resolved (verified)`);
287
+ parts.push(`${r.unconfirmed} unconfirmed`);
288
+ parts.push(`${r.carried} carried`);
289
+ parts.push(`${r.deferred} deferred`);
290
+ parts.push(`${r.new} new`);
291
+ return `${since}: ${parts.join(" · ")}`;
292
+ }
293
+ return `${since}: ${delta.resolved} resolved · ${delta.new} new · ${delta.persist} persist`;
294
+ }
295
+
296
+ function usd(amount: number): string {
297
+ return `$${amount.toFixed(2)}`;
298
+ }
299
+
300
+ // A size limit <= 0 means that knob is off (review/size-gate.ts). Printed as
301
+ // a number it reads "limit 0", a limit every diff exceeds, and a subscription
302
+ // route now turns a knob off by default (resolveCiSizeLimits), so the other
303
+ // knob tripping would show it.
304
+ export function sizeLimitText(limit: number): string {
305
+ return limit > 0 ? `limit ${limit}` : "no limit";
306
+ }
307
+
308
+ function skipSizeLines(data: CiSkipSizeSummary): string[] {
309
+ return [
310
+ `### ⚠️ Crysk Review Skipped — PR #${data.prNumber}`,
311
+ "",
312
+ "**Reason:** the diff exceeds the configured size gate limits.",
313
+ "",
314
+ "| Metric | Value |",
315
+ "| --- | --- |",
316
+ `| Changed lines | ${data.changedLines} (${sizeLimitText(data.maxChangedLines)}) |`,
317
+ `| Changed files | ${data.changedFiles} (${sizeLimitText(data.maxChangedFiles)}) |`,
318
+ "",
319
+ "Crysk did not run to avoid reviewing an unbounded diff. Split the " +
320
+ "PR or raise `max-changed-lines` / `max-changed-files`.",
321
+ ];
322
+ }
323
+
324
+ function skipBudgetLines(data: CiSkipBudgetSummary): string[] {
325
+ return [
326
+ `### ⚠️ Crysk Review Skipped — PR #${data.prNumber}`,
327
+ "",
328
+ "**Reason:** the estimated cost exceeds the configured budget ceiling.",
329
+ "",
330
+ "| Metric | Value |",
331
+ "| --- | --- |",
332
+ `| Estimated cost | ${usd(data.estimatedCostUsd)} (budget ${usd(data.budgetUsd)}) |`,
333
+ "",
334
+ "Crysk did not run to stay within the configured `--budget-usd` " +
335
+ "ceiling.",
336
+ ];
337
+ }
338
+
339
+ function admissionMetricRows(
340
+ data: CiSkipCoverageSummary | CiManualRequiredSummary,
341
+ ): string[] {
342
+ const rows: string[] = [];
343
+ if (data.decision !== undefined) {
344
+ rows.push(`| Decision | ${data.decision} |`);
345
+ }
346
+ if (data.admissionReason !== undefined) {
347
+ rows.push(`| Admission reason | ${data.admissionReason} |`);
348
+ }
349
+ if (data.currentHead !== undefined) {
350
+ rows.push(`| Current head | \`${data.currentHead.slice(0, 8)}\` |`);
351
+ }
352
+ if (data.reviewedHead !== undefined) {
353
+ rows.push(
354
+ `| Reviewed head | ${
355
+ data.reviewedHead === null
356
+ ? "none"
357
+ : `\`${data.reviewedHead.slice(0, 8)}\``
358
+ } |`,
359
+ );
360
+ }
361
+ if (data.riskClass !== undefined) {
362
+ rows.push(`| Risk class | ${data.riskClass} |`);
363
+ }
364
+ if (data.riskReason !== undefined && data.riskReason.length > 0) {
365
+ rows.push(`| Risk detail | ${data.riskReason} |`);
366
+ }
367
+ if (data.remainingBudget !== undefined) {
368
+ rows.push(`| Remaining budget | ${data.remainingBudget} |`);
369
+ }
370
+ if (data.policyMode !== undefined) {
371
+ rows.push(`| Policy mode | ${data.policyMode} |`);
372
+ }
373
+ if (data.policyHash !== undefined) {
374
+ rows.push(`| Policy hash | \`${data.policyHash.slice(0, 8)}\` |`);
375
+ }
376
+ return rows;
377
+ }
378
+
379
+ function skipCoverageLines(data: CiSkipCoverageSummary): string[] {
380
+ // A stop is a maintainer's decision, not a score (same wording rule as the
381
+ // PR comment, gates.ts buildCoverageSkipComment).
382
+ const stopped = data.admissionReason === "stopped";
383
+ return [
384
+ `### ⚠️ Crysk Review Skipped — PR #${data.prNumber}`,
385
+ "",
386
+ stopped
387
+ ? "**Reason:** a maintainer stopped automatic reviews on this pull request."
388
+ : "**Reason:** this push does not justify another review run.",
389
+ "",
390
+ "| Metric | Value |",
391
+ "| --- | --- |",
392
+ `| Skip reason | ${data.reason} |`,
393
+ ...(stopped
394
+ ? []
395
+ : [`| Prior score | ${data.priorScore} (minimum ${data.minScore}) |`]),
396
+ `| Attempts used | ${data.reviewCount}/${data.maxAttempts} |`,
397
+ ...admissionMetricRows(data),
398
+ "",
399
+ data.detail,
400
+ ];
401
+ }
402
+
403
+ function manualRequiredLines(data: CiManualRequiredSummary): string[] {
404
+ return [
405
+ `### 🛑 Crysk Review — Manual Override Required — PR #${data.prNumber}`,
406
+ "",
407
+ "**Reason:** automatic review did not run on this push.",
408
+ "",
409
+ "| Metric | Value |",
410
+ "| --- | --- |",
411
+ `| Block reason | ${data.reason} |`,
412
+ `| Prior score | ${data.priorScore} |`,
413
+ `| Attempts used | ${data.reviewCount}/${data.maxAttempts} |`,
414
+ ...admissionMetricRows(data),
415
+ "",
416
+ data.detail,
417
+ ];
418
+ }
419
+
420
+ function reviewedLines(data: CiReviewSummary): string[] {
421
+ const blocking = data.findings.filter((f) => f.tier === "blocking");
422
+ const advisory = data.findings.filter((f) => f.tier === "advisory");
423
+ const out = [
424
+ `### 🔍 Crysk Review — PR #${data.prNumber}`,
425
+ "",
426
+ "| Metric | Value |",
427
+ "| --- | --- |",
428
+ `| Findings | ${data.findings.length} (${blocking.length} blocking · ` +
429
+ `${advisory.length} advisory) |`,
430
+ `| Estimated cost | ${usd(data.costUsdEst)} |`,
431
+ `| Duration | ${formatElapsed(data.wallMs)} |`,
432
+ `| Model | ${data.model} |`,
433
+ "",
434
+ ];
435
+ if (data.findings.length === 0) {
436
+ out.push("✅ No findings detected.");
437
+ } else {
438
+ out.push("#### Findings", "");
439
+ for (const [filePath, group] of groupFindingsByPath(data.findings)) {
440
+ out.push(`**\`${filePath}\`**`);
441
+ for (const finding of group) {
442
+ out.push(findingLine(finding, data.headSha, data.repoWebUrl));
443
+ }
444
+ out.push("");
445
+ }
446
+ }
447
+ if (data.delta !== undefined) {
448
+ out.push(formatDeltaLine(data.delta));
449
+ out.push("");
450
+ }
451
+ return out;
452
+ }
453
+
454
+ // Formatted Markdown for `$GITHUB_STEP_SUMMARY` (spec 2.1). Pure — the
455
+ // caller supplies every byte, so the summary is re-renderable from a stored
456
+ // findings.json months later, same contract as
457
+ // renderReport/renderPrComment (report.ts).
458
+ // `ciMode` picks the footer only. Omitted means advisory: the footer every
459
+ // caller has today, until a caller passes the mode its status was set under.
460
+ export function renderStepSummary(
461
+ data: CiSummaryData,
462
+ ciMode: CiMode = "advisory",
463
+ ): string {
464
+ const body =
465
+ data.kind === "skipped-size"
466
+ ? skipSizeLines(data)
467
+ : data.kind === "skipped-budget"
468
+ ? skipBudgetLines(data)
469
+ : data.kind === "skipped-coverage"
470
+ ? skipCoverageLines(data)
471
+ : data.kind === "manual-required"
472
+ ? manualRequiredLines(data)
473
+ : reviewedLines(data);
474
+ const out = [...body, "---", "", footerFor(ciMode)];
475
+ return `${out.join("\n").trimEnd()}\n`;
476
+ }
477
+
478
+ // ---------------------------------------------------------------------------
479
+ // $GITHUB_OUTPUT — the action's structured outputs (spec 1.1).
480
+ // ---------------------------------------------------------------------------
481
+
482
+ export interface CiOutputs {
483
+ status: string;
484
+ findings_count: number;
485
+ blocking_count: number;
486
+ advisory_count: number;
487
+ // Spec 1.1: "cost-usd-est: ... (float string, e.g. `"2.45"`)" — formatted
488
+ // to 2 decimals here so every consumer of $GITHUB_OUTPUT reads the same
489
+ // fixed-precision string the action.yml output contract promises.
490
+ cost_usd_est: number;
491
+ run_dir: string;
492
+ }
493
+
494
+ // Pure `key=value` line formatter for `$GITHUB_OUTPUT`. One name per line,
495
+ // GitHub Actions' own format for scalar outputs (no multiline heredoc
496
+ // delimiter needed — every value here is a single-line scalar).
497
+ export function formatCiOutputs(outputs: CiOutputs): string {
498
+ const lines = [
499
+ `status=${outputs.status}`,
500
+ `findings_count=${outputs.findings_count}`,
501
+ `blocking_count=${outputs.blocking_count}`,
502
+ `advisory_count=${outputs.advisory_count}`,
503
+ `cost_usd_est=${outputs.cost_usd_est.toFixed(2)}`,
504
+ `run_dir=${outputs.run_dir}`,
505
+ ];
506
+ return `${lines.join("\n")}\n`;
507
+ }
508
+
509
+ // ---------------------------------------------------------------------------
510
+ // Impure edge — the ONLY functions in this module that touch the filesystem.
511
+ // ---------------------------------------------------------------------------
512
+
513
+ // Appends `markdown` to the file `$GITHUB_STEP_SUMMARY` points at, adding
514
+ // exactly one trailing newline when the caller's Markdown does not already
515
+ // end with one — GitHub renders the file as-is, and two summaries glued
516
+ // together without a newline between them would merge into one line.
517
+ export async function appendStepSummary(
518
+ summaryFilePath: string,
519
+ markdown: string,
520
+ ): Promise<void> {
521
+ const text = markdown.endsWith("\n") ? markdown : `${markdown}\n`;
522
+ await appendFile(summaryFilePath, text);
523
+ }
524
+
525
+ // Appends `formatCiOutputs(outputs)` to the file `$GITHUB_OUTPUT` points at.
526
+ export async function appendCiOutputs(
527
+ outputFilePath: string,
528
+ outputs: CiOutputs,
529
+ ): Promise<void> {
530
+ await appendFile(outputFilePath, formatCiOutputs(outputs));
531
+ }
532
+
533
+ // ---------------------------------------------------------------------------
534
+ // CI headless shell composition (ROADMAP Pillar 3) — the `::group::` wrapper
535
+ // built on `formatWorkflowCommand` above, and the fatal-error reporter built
536
+ // on `appendCiOutputs` above. Extracted from cli.ts (cli-decomp S2,
537
+ // Cluster B): neither touches the filesystem directly (`appendCiOutputs`
538
+ // remains the only function here that does), so the module header's purity
539
+ // split still holds for its own two functions — these two compose them.
540
+ // ---------------------------------------------------------------------------
541
+
542
+ // Spec 2.1's `::group::` / `::endgroup::` pairing, owned by ONE function so
543
+ // the arm and the close cannot drift apart. An unclosed group is not
544
+ // cosmetic: GitHub folds every line logged after it into a collapsed section,
545
+ // so a crash mid-review hides its own `::error::` annotation from the reader
546
+ // who most needs it. Putting the arm at the call site and the close in some
547
+ // later `finally` leaves a window — whatever runs in between — where a throw
548
+ // escapes with the group still open; here there is no in-between.
549
+ //
550
+ // `emit` is a parameter rather than this module's `log`: a guarantee nothing
551
+ // can observe is a guarantee nobody can test, and the failure path is exactly
552
+ // the one that has to be proven.
553
+ export async function withCiWorkflowGroup<T>(
554
+ isCi: boolean,
555
+ name: string,
556
+ emit: (line: string) => void,
557
+ body: () => Promise<T>,
558
+ ): Promise<T> {
559
+ if (!isCi) return await body();
560
+ emit(formatWorkflowCommand("group", name));
561
+ try {
562
+ return await body();
563
+ } finally {
564
+ emit(formatWorkflowCommand("endgroup"));
565
+ }
566
+ }
567
+
568
+ // Spec 1.1's `status` output enum names `error` alongside `reviewed` /
569
+ // `skipped-size` / `skipped-budget`, but before this function nothing ever
570
+ // wrote it: main()'s own catch only handles CliError/CliUsageError (exit 1,
571
+ // no $GITHUB_OUTPUT write); every OTHER thrown error — a genuine fatal
572
+ // failure, e.g. bad credentials deep inside reviewPr() — was simply
573
+ // rethrown, crashing the process with no output at all. A workflow branching
574
+ // on `steps.x.outputs.status == 'error'` could then never fire.
575
+ //
576
+ // $GITHUB_OUTPUT existing at all is itself the CI signal here: GitHub sets it
577
+ // unconditionally for every job step, before any of this repo's own flags
578
+ // are parsed, so this needs no separate isCiEnvironment() computation — and
579
+ // it fails closed for a genuinely local crash (outputPath undefined), which
580
+ // runCli()'s caller rethrows so the developer still sees a full stack trace
581
+ // instead of a swallowed one-line message.
582
+ export async function reportFatalCiError(
583
+ error: unknown,
584
+ outputPath: string | undefined,
585
+ ): Promise<void> {
586
+ const message = error instanceof Error ? error.message : String(error);
587
+ if (outputPath !== undefined && outputPath.length > 0) {
588
+ // Best-effort: an unwritable $GITHUB_OUTPUT must not mask the original
589
+ // fatal error or suppress the ::error:: annotation below.
590
+ await appendCiOutputs(outputPath, {
591
+ status: "error",
592
+ findings_count: 0,
593
+ blocking_count: 0,
594
+ advisory_count: 0,
595
+ cost_usd_est: 0,
596
+ run_dir: "",
597
+ }).catch(() => {});
598
+ }
599
+ log(formatWorkflowCommand("error", message));
600
+ }
601
+
602
+ // main()'s two internal catches RETURN rather than throw, so runCli()'s catch
603
+ // — the only thing that has ever written `status=error` — never saw them. Both
604
+ // are failures docs/github-actions.md names as reasons the job goes red: a
605
+ // malformed argument (parseArgs, exit 2) and a CliError/CliUsageError from a
606
+ // command body (exit 1) — which is precisely what a missing or expired
607
+ // GITHUB_TOKEN produces, since pr/pr.ts raises CliError for `gh not found on
608
+ // PATH` and for a failed `gh pr view`. A consumer branching on
609
+ // `outputs.status == 'error'` therefore never saw it fire for the two most
610
+ // common failures; it saw `status` unset, indistinguishable from a step whose
611
+ // outputs were never read.
612
+ //
613
+ // $GITHUB_OUTPUT's mere presence is the CI signal here, exactly as it is for
614
+ // reportFatalCiError: GitHub sets it for every job step before any of this
615
+ // repo's own flags are parsed. Guarding the CALL rather than only the write is
616
+ // deliberate — reportFatalCiError also emits an `::error::` annotation, and
617
+ // printing workflow-command syntax on a developer's terminal after a plain
618
+ // typo is noise, not diagnostics. Exit codes are untouched; only the write is
619
+ // new.
620
+ export async function reportFatalCiErrorIfInJobStep(
621
+ error: unknown,
622
+ ): Promise<void> {
623
+ const outputPath = process.env.GITHUB_OUTPUT;
624
+ if (outputPath === undefined || outputPath.length === 0) return;
625
+ await reportFatalCiError(error, outputPath);
626
+ }