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,923 @@
1
+ // Bounded unattended spend (ROADMAP Pillar 3, GitHub Actions CI): the two
2
+ // gates that must clear BEFORE a CI run spawns a single agent, and the pure
3
+ // CI-mode skip payloads those gates produce when they don't.
4
+ //
5
+ // Phase 3 additions (this module's scope now covers the whole CI-mode
6
+ // policy layer, not just the two spend gates): `planCiSizeSkip`/
7
+ // `planCiBudgetSkip` are the ONE call reviewPr's shell makes per gate —
8
+ // comment + marker + step-summary markdown + $GITHUB_OUTPUT, all from the
9
+ // same numbers, so the shell has no decision left to make beyond "post it /
10
+ // write it". `budgetDisabledWarningMessage` covers spec 3.1's disabled-
11
+ // ceiling `::warning::` requirement. `ciExitCode` pins the assistant-posture
12
+ // exit-code contract (spec 2.1): findings, even blocking ones, never fail
13
+ // the job — only a fatal session failure or a genuine posting drop (design
14
+ // D6) does.
15
+ //
16
+ // This module does NOT reimplement the size gate — that gate (deterministic
17
+ // line/file counting, exclusion globs, the whole cost-predictability
18
+ // rationale) already exists in size-gate.ts and is already wired into local
19
+ // review, PR review and the watcher via `sizeGateDisposition`. What CI mode
20
+ // needs on top is different: outside CI, an over-limit diff can PROMPT an
21
+ // interactive operator or fall back to `--yes`/non-TTY `skip`; inside CI
22
+ // there is nobody to prompt AND the run must still exit 0 with a courteous
23
+ // PR notice (assistant posture — see proposal.md's Invariants). So this
24
+ // module adds exactly that CI-mode handling on top of an already-computed
25
+ // `SizeGateVerdict`, plus the budget gate's own threshold check (there is no
26
+ // pre-existing budget gate to reuse).
27
+ //
28
+ // Purity (project rule 1): every function here is a total function of its
29
+ // arguments. No file I/O, no `process.env` sniffing, no `log()`, no network,
30
+ // no clock. Posting the comment and writing `$GITHUB_STEP_SUMMARY` /
31
+ // `$GITHUB_OUTPUT` are impure edges that belong to the CI headless shell
32
+ // (Phase 3, src/pr/pr.ts / src/cli.ts) — this module only builds the bytes.
33
+ //
34
+ // Reuse: `CiSummaryData` (ci/reporter.ts) is the exported contract for the
35
+ // step-summary payload. Its `skipped-size`/`skipped-budget` members stay
36
+ // UNEXPORTED there by design (see that module's header) — this file names
37
+ // them with `Extract<CiSummaryData, { kind: "..." }>` against the exported
38
+ // union rather than asking ci/reporter.ts to promote either member. Nothing
39
+ // here needed a member exported on its own: an object literal typed against
40
+ // the union already type-checks structurally (renderStepSummary's own tests
41
+ // construct `CiSummaryData` values in the exact same way), and `Extract`
42
+ // gives this module named, narrowed types for its own signatures without
43
+ // touching Phase 1's frozen module or its "promote on real need" comment.
44
+ // The two skip functions below build their `CiSummaryData` value through the
45
+ // SAME code path that also builds the PR comment, so the comment and the
46
+ // step summary can never independently drift on the numbers they report.
47
+ //
48
+ // PR comment marker: design.md's draft proposed a colon-style tag
49
+ // (`<!-- pr-hero:skip-size -->`). The convention actually shipped in this
50
+ // codebase is hyphenated and namespaced under `pr-hero-<noun>`
51
+ // (`PR_COMMENT_MARKER_PREFIX = "<!-- pr-hero-report "`,
52
+ // `PR_FINDING_MARKER_PREFIX = "<!-- pr-hero-finding "`,
53
+ // `PR_STATE_MARKER_PREFIX = "<!-- pr-hero-state "`,
54
+ // `TRIAGE_MARKER_PREFIX = "<!-- pr-hero-triage "` — pr/preflight.ts,
55
+ // rereview/state.ts, triage/triage.ts). This module follows the shipped
56
+ // convention, not the draft: `<!-- pr-hero-skip-size -->` /
57
+ // `<!-- pr-hero-skip-budget -->`. Deliberately WITHOUT a `head=` field —
58
+ // unlike `prCommentMarker`, the two `CiSummaryData` skip members this phase
59
+ // builds from (already landed in Phase 1) carry no `headSha` at all, and a
60
+ // gate skip has no code to anchor a head declaration to. Wiring these
61
+ // markers into the idempotent find-or-create flow (`findMarkedCommentId`)
62
+ // is Phase 3's job, once a real poster exists to consume them.
63
+
64
+ import type { CiMode } from "#pr/preflight";
65
+ import type { Finding, FindingsDocument } from "#review/findings";
66
+ import type { PrCommentDelta } from "#review/report";
67
+ import type { SizeGateVerdict } from "#review/size-gate";
68
+ import { MARKER_OPEN } from "../brand";
69
+ import { CliUsageError } from "../errors";
70
+ import { envBillsMetered } from "../execution/usage-normalized";
71
+ import { ciForceReviewHintLine } from "./force-comment";
72
+ import {
73
+ type CiOutputs,
74
+ type CiSummaryData,
75
+ renderStepSummary,
76
+ } from "./reporter";
77
+ import {
78
+ type CiReviewAdmissionVerdict,
79
+ type CiReviewSkipReason,
80
+ ciAdmissionRemainingBudget,
81
+ ciReviewManualRequiredDetail,
82
+ ciReviewSkipDetail,
83
+ } from "./review-admission";
84
+ import type { CiReviewPolicyMode } from "./review-policy";
85
+ import type { DeltaRiskAssessment } from "./review-risk";
86
+
87
+ function usd(amount: number): string {
88
+ return `$${amount.toFixed(2)}`;
89
+ }
90
+
91
+ // ---------------------------------------------------------------------------
92
+ // Budget gate — spec.md 3.1: "If estimated cost exceeds --budget-usd ...".
93
+ // The one comparison this module owns outright (no pre-existing gate to
94
+ // reuse, unlike size).
95
+ // ---------------------------------------------------------------------------
96
+
97
+ export interface BudgetGateVerdict {
98
+ allowed: boolean;
99
+ // Present only when `allowed` is false — mirrors SizeGateVerdict's own
100
+ // discriminated shape (size-gate.ts) in spirit, kept optional-on-a-flat-
101
+ // object here per the task's own stated signature rather than a second
102
+ // discriminated union for a single string field.
103
+ reason?: string;
104
+ }
105
+
106
+ // Inclusive boundary: a cost exactly AT the ceiling is allowed, matching
107
+ // size-gate.ts's own `>` (not `>=`) comparison against its limits.
108
+ //
109
+ // A non-positive ceiling DISABLES the gate. That is not this module's
110
+ // invention — size-gate.ts:20 already settled it for the sibling knobs
111
+ // ("<= 0 disables the limit. Both knobs, independently."), and all three
112
+ // ship side by side in one action.yml feeding one preflight, so `budget-usd:
113
+ // 0` has to mean what `max-changed-lines: 0` means. The external convention
114
+ // does cut the other way (a $0 spend cap elsewhere often means "spend
115
+ // nothing"), which is why it is written down here rather than assumed.
116
+ //
117
+ // What settles it is that the failure modes are not symmetric. Read as "no
118
+ // ceiling" when the operator meant "spend nothing", being wrong costs one
119
+ // visible review, still bounded by the size gate running independently. Read
120
+ // as "always skip" when the operator meant "no ceiling", being wrong makes
121
+ // pr-hero go dark on every PR while each run still exits 0 green — the same
122
+ // shape as a lint gate that checks nothing and passes, which this repo has
123
+ // already paid for once (docs/research/scout-design.md:344). A disable is only safe
124
+ // when it is loud, so the CI shell warns on a disabled ceiling.
125
+ export function evaluateBudgetGate(
126
+ estimatedCostUsd: number,
127
+ budgetUsd: number,
128
+ ): BudgetGateVerdict {
129
+ if (budgetUsd <= 0) return { allowed: true };
130
+ if (estimatedCostUsd <= budgetUsd) return { allowed: true };
131
+ return {
132
+ allowed: false,
133
+ reason:
134
+ `estimated cost ${usd(estimatedCostUsd)} exceeds the ` +
135
+ `${usd(budgetUsd)} budget ceiling`,
136
+ };
137
+ }
138
+
139
+ // ---------------------------------------------------------------------------
140
+ // CI skip payloads — one PR comment + one step-summary payload, built from
141
+ // the SAME numbers so the two surfaces can't disagree.
142
+ // ---------------------------------------------------------------------------
143
+
144
+ export interface CiGateSkip {
145
+ // Markdown for the PR comment. Posting it (or not, per `--post`) is the
146
+ // caller's job.
147
+ comment: string;
148
+ // Feeds directly into ci/reporter.ts's `renderStepSummary`.
149
+ summary: CiSummaryData;
150
+ }
151
+
152
+ // Exported (Phase 3): both are legitimate consumers of these exact bytes —
153
+ // test/pr/preflight.test.ts's marker-prefix-disjointness registry (proving
154
+ // neither collides with PR_COMMENT/PR_FINDING/PR_STATE/TRIAGE, the pattern
155
+ // that test already established) and pr/pr.ts's repostMarkedPrComment, which
156
+ // keys on the marker so a second CI run on the same still-oversized PR (every
157
+ // `synchronize` push) posts a fresh notice at the bottom and deletes the old
158
+ // one: never stacked, and never a silent in-place edit. Both are
159
+ // self-closing, field-less tags (unlike the four `<!-- pr-hero-<noun> ` +
160
+ // trailing-space prefixes above): a skip decision has no code to anchor a
161
+ // `head=` declaration to, and no fields to encode — see the module header.
162
+ export const SKIP_SIZE_COMMENT_MARKER = `${MARKER_OPEN}skip-size -->`;
163
+ export const SKIP_BUDGET_COMMENT_MARKER = `${MARKER_OPEN}skip-budget -->`;
164
+ export const SKIP_COVERAGE_COMMENT_MARKER = `${MARKER_OPEN}skip-coverage -->`;
165
+ export const MANUAL_REQUIRED_COMMENT_MARKER = `${MARKER_OPEN}manual-required -->`;
166
+
167
+ // Same register as ci/reporter.ts's `skipSizeLines`/`skipBudgetLines` and
168
+ // project rule 4 (assistant posture): a gate skip is a courteous notice
169
+ // about SPEND, never a verdict on the diff's quality. "Split the PR" reads
170
+ // as a practical option, not a correction.
171
+ type SkipSizeSummary = Extract<CiSummaryData, { kind: "skipped-size" }>;
172
+ type SkipBudgetSummary = Extract<CiSummaryData, { kind: "skipped-budget" }>;
173
+ type SkipCoverageSummary = Extract<CiSummaryData, { kind: "skipped-coverage" }>;
174
+ type ManualRequiredSummary = Extract<
175
+ CiSummaryData,
176
+ { kind: "manual-required" }
177
+ >;
178
+
179
+ // Same reason as reporter.ts's sizeLimitText: a knob that is off (<= 0) must
180
+ // not print as "0 files". Both knobs on keeps the original wording.
181
+ function sizeLimitsText(maxLines: number, maxFiles: number): string {
182
+ if (maxLines > 0 && maxFiles > 0) {
183
+ return `max ${maxLines} lines / ${maxFiles} files`;
184
+ }
185
+ const lines = maxLines > 0 ? `max ${maxLines} lines` : "no line limit";
186
+ const files = maxFiles > 0 ? `max ${maxFiles} files` : "no file limit";
187
+ return `${lines} / ${files}`;
188
+ }
189
+
190
+ function buildSizeSkipComment(data: SkipSizeSummary): string {
191
+ const lines = [
192
+ SKIP_SIZE_COMMENT_MARKER,
193
+ "## Crysk review skipped",
194
+ "",
195
+ `⚠️ This diff changes ${data.changedLines} line(s) across ` +
196
+ `${data.changedFiles} file(s), exceeding the configured size gate ` +
197
+ `(${sizeLimitsText(data.maxChangedLines, data.maxChangedFiles)}).`,
198
+ "",
199
+ "Crysk did not run to avoid reviewing an unbounded diff. Split the " +
200
+ "PR or raise `max-changed-lines` / `max-changed-files` to change the " +
201
+ "limit for later pushes.",
202
+ "",
203
+ ciForceReviewHintLine(data.prNumber),
204
+ ];
205
+ return `${lines.join("\n")}\n`;
206
+ }
207
+
208
+ function buildBudgetSkipComment(data: SkipBudgetSummary): string {
209
+ const lines = [
210
+ SKIP_BUDGET_COMMENT_MARKER,
211
+ "## Crysk review skipped",
212
+ "",
213
+ `⚠️ The estimated review cost (${usd(data.estimatedCostUsd)}) exceeds ` +
214
+ `the configured CI budget ceiling (${usd(data.budgetUsd)}).`,
215
+ "",
216
+ "Crysk did not run to stay within the configured `--budget-usd` " +
217
+ "ceiling.",
218
+ "",
219
+ ciForceReviewHintLine(data.prNumber),
220
+ ];
221
+ return `${lines.join("\n")}\n`;
222
+ }
223
+
224
+ export interface CiSizeGateSkipInput {
225
+ // Whether this run is in CI headless mode (Phase 3's `isCiEnvironment()`
226
+ // / `--ci`). Outside CI, the existing `sizeGateDisposition` prompt/skip
227
+ // flow (size-gate.ts) already handles an over-limit diff — this function
228
+ // is a no-op there, on purpose, so the two paths cannot both fire.
229
+ isCi: boolean;
230
+ // The already-computed verdict (size-gate.ts's `evaluateSizeGate` /
231
+ // `evaluateSizeGateAggregate`). This module never counts lines or files
232
+ // itself.
233
+ verdict: SizeGateVerdict;
234
+ prNumber: number;
235
+ // The configured ceilings, reported alongside whichever one the verdict
236
+ // actually tripped — a verdict only carries the single `limit` that
237
+ // failed (size-gate.ts), but the summary/comment show both metrics.
238
+ maxChangedLines: number;
239
+ maxChangedFiles: number;
240
+ }
241
+
242
+ // `null` means "nothing to publish": either this isn't a CI run, or the
243
+ // gate passed. Callers branch on `=== null`, never on truthiness of a
244
+ // partially-built object.
245
+ export function ciSizeGateSkip(input: CiSizeGateSkipInput): CiGateSkip | null {
246
+ if (!input.isCi || input.verdict.ok) return null;
247
+ const summary: SkipSizeSummary = {
248
+ kind: "skipped-size",
249
+ prNumber: input.prNumber,
250
+ changedLines: input.verdict.effectiveLines,
251
+ changedFiles: input.verdict.effectiveFiles,
252
+ maxChangedLines: input.maxChangedLines,
253
+ maxChangedFiles: input.maxChangedFiles,
254
+ };
255
+ return { comment: buildSizeSkipComment(summary), summary };
256
+ }
257
+
258
+ export interface CiBudgetGateSkipInput {
259
+ isCi: boolean;
260
+ estimatedCostUsd: number;
261
+ budgetUsd: number;
262
+ prNumber: number;
263
+ }
264
+
265
+ export function ciBudgetGateSkip(
266
+ input: CiBudgetGateSkipInput,
267
+ ): CiGateSkip | null {
268
+ const verdict = evaluateBudgetGate(input.estimatedCostUsd, input.budgetUsd);
269
+ if (!input.isCi || verdict.allowed) return null;
270
+ const summary: SkipBudgetSummary = {
271
+ kind: "skipped-budget",
272
+ prNumber: input.prNumber,
273
+ estimatedCostUsd: input.estimatedCostUsd,
274
+ budgetUsd: input.budgetUsd,
275
+ };
276
+ return { comment: buildBudgetSkipComment(summary), summary };
277
+ }
278
+
279
+ // ---------------------------------------------------------------------------
280
+ // Disabled-ceiling warning — spec 3.1: "Because a silent disable is
281
+ // indistinguishable from a passing gate, the CI shell MUST emit a
282
+ // `::warning::` workflow command noting that the budget ceiling is
283
+ // disabled." Only for an EXPLICIT <= 0 — `undefined` (the flag was never
284
+ // given) means no ceiling was ever configured, so there is nothing to warn
285
+ // about disabling. The shell wraps this message with
286
+ // `formatWorkflowCommand("warning", ...)` (ci/reporter.ts); this module only
287
+ // decides whether to and builds the text, never the annotation syntax.
288
+ // ---------------------------------------------------------------------------
289
+
290
+ export function budgetDisabledWarningMessage(
291
+ budgetUsd: number | undefined,
292
+ ): string | null {
293
+ if (budgetUsd === undefined || budgetUsd > 0) return null;
294
+ return (
295
+ "budget-usd ceiling is disabled (<= 0 was configured); estimated cost " +
296
+ "is unconstrained for this CI run. The size gate is resolved " +
297
+ "separately."
298
+ );
299
+ }
300
+
301
+ // ---------------------------------------------------------------------------
302
+ // Route-aware ceiling resolution (issue #156). The budget gate compares
303
+ // `estimate.high` — a TOKEN-derived figure — against a real-dollar ceiling.
304
+ // On a Claude subscription route the real cash cost of a run is $0.00, so the
305
+ // shipped $10 default refused to do work over an overrun that cannot happen,
306
+ // and a skipped review is indistinguishable from a clean one to anyone
307
+ // reading the checks (this module's own doctrine, ~110-115; ci/setup.ts:50-63).
308
+ // So: no ceiling by default on a subscription route, the default ceiling on a
309
+ // metered one, and an explicit operator value honoured verbatim on either.
310
+ // ---------------------------------------------------------------------------
311
+
312
+ export type CiBillingMode = "subscription" | "metered";
313
+
314
+ // A non-empty ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN means metered.
315
+ // Everything else, including an OAuth token, means subscription.
316
+ //
317
+ // 2026-09-02, #177: the RULE now lives in `envBillsMetered`
318
+ // (execution/usage-normalized.ts) and this function only narrows it into
319
+ // `CiBillingMode`. It moved because a SECOND caller appeared — the Claude CLI
320
+ // transport, which stamps the billing mode on every usage record it emits —
321
+ // and two copies were two chances for the ceiling and the records to disagree
322
+ // about whether one run bills. They already had: this gate called an API-key
323
+ // route metered while the transport filed that user's real spend as notional
324
+ // ("at list price, not charged"), so budget enforcement, which is cash-only,
325
+ // saw a $0 ceiling.
326
+ //
327
+ // ANTHROPIC_AUTH_TOKEN joined the signal in the same move. It was never
328
+ // excluded by a decision — the doctrine below never mentions it — and
329
+ // `ENV_PASSTHROUGH` (harness.ts) projects it into the child immediately beside
330
+ // ANTHROPIC_API_KEY as the same per-token credential class, so the rule stated
331
+ // two paragraphs down ("the mere PRESENCE of a key keeps the ceiling") already
332
+ // covered it. Nil-delta for the shipped action: action.yml binds only
333
+ // ANTHROPIC_API_KEY and CLAUDE_CODE_OAUTH_TOKEN, so no generated workflow can
334
+ // newly acquire a ceiling from it.
335
+ //
336
+ // Which credential bills when BOTH CLAUDE_CODE_OAUTH_TOKEN and ANTHROPIC_API_KEY are
337
+ // present was settled by observation after this rule was written: CLI 2.1.312 prints
338
+ // "claude.ai connectors are disabled because ANTHROPIC_API_KEY or another auth source is
339
+ // set and takes precedence over your claude.ai login", and on this repo's CI with both
340
+ // secrets bound every request used the API key (see credentialOf in
341
+ // transports/claude-code-cli.ts). The rule below still does not depend on that answer,
342
+ // and the gap it describes was real when it was written:
343
+ // action.yml:111-112 binds both into the child env unconditionally,
344
+ // test/harness/env-projection.test.ts:48-56 deliberately asserts both survive
345
+ // the projection with no precedence between them, and `defaultClaudeAuthProbe`
346
+ // (model/provider-capabilities.ts:402-405) ORs them into a single boolean. Whichever
347
+ // one the Claude CLI itself prefers wins, and that fact is recorded nowhere in
348
+ // this codebase.
349
+ //
350
+ // This rule does not need that answer, because the two errors are not
351
+ // symmetric. Guess "unlimited" wrongly and a real invoice arrives that nobody
352
+ // authorized. Guess "ceiling" wrongly and one review is skipped, which the
353
+ // operator clears with a single line of YAML (`budget-usd: 0`). So the mere
354
+ // PRESENCE of a key keeps the ceiling: we cannot rule out that it bills.
355
+ // README.md:38-45 already states the user-facing half of the same rule —
356
+ // sourcing ANTHROPIC_API_KEY into the shell "is what moves a run from quota to
357
+ // invoice".
358
+ //
359
+ // Trimming is load-bearing. 2026-09-02, #177 corrects the overstatement this
360
+ // paragraph used to carry ("without the trim, no route would ever resolve as
361
+ // a subscription in Actions"): action.yml:111 binds the input UNCONDITIONALLY
362
+ // and GitHub renders an unset input as the empty string, so every
363
+ // subscription-route CI run carries `ANTHROPIC_API_KEY=""` — and `""` is
364
+ // already falsy, so that case never needed the trim. What the trim catches is
365
+ // a WHITESPACE-ONLY value, which is truthy and would otherwise impose a
366
+ // ceiling on a subscription route. `test/ci/gates.test.ts` asserts both cases
367
+ // separately, and only the whitespace ones flip when the trim is removed.
368
+ //
369
+ // This is deliberately NOT `model/provider-capabilities.ts`'s
370
+ // `CLAUDE_CAPABILITY_STATICS.billingMode`, and the two must not be "unified"
371
+ // later — but the REASON changed under it, so do not quote the old one.
372
+ //
373
+ // Until #197 the reason was an ADMISSION hazard: metered →
374
+ // `pricingApplicability: "required"` → `tokenPricingAvailable`, which nothing
375
+ // could answer for a claude-code route (`pricingReady` was false on both the
376
+ // CLI transport and the backend-wide producer, and the bundled table was keyed
377
+ // per model) → `pricing_table_missing`, blocking. #197 flipped that flag to
378
+ // `true` on the strength of the CLI's own `total_cost_usd`, so a metered
379
+ // claude-code route is no longer refused for lack of pricing and the hazard is
380
+ // gone.
381
+ //
382
+ // The separation stands on ownership instead: how a route bills follows from
383
+ // which credential it runs on, which is `credentialKindForRoute`'s single
384
+ // decision (#161, landed). This one answers a narrower question — "should CI
385
+ // impose a spend ceiling?" — and reaches nothing but the ceiling.
386
+ //
387
+ // `envBillsMetered` carries the matching ADMISSION WIRING paragraph, and it
388
+ // is worth reading precisely because #161 changed its shape: this predicate
389
+ // now has a SANCTIONED second caller (`credentialKindForRoute`), named
390
+ // rather than forbidden, because admission and usage filing must answer from
391
+ // the same function or they can disagree about one attempt. What stays
392
+ // forbidden is a THIRD caller deriving from env directly instead of going
393
+ // through that one decision — this CI gate is not that caller, and never
394
+ // should be.
395
+ //
396
+ // Optional `openCodeAuthPresent` is the OpenCode half of the same ceiling
397
+ // question — "could this run invoice?" — ORed beside the Anthropic env
398
+ // predicate, never folded into it. `envBillsMetered` stamps Claude CLI
399
+ // usage and must stay Anthropic-env-only. Omit the option (or leave it
400
+ // undefined/false) and this function stays env-only. Presence of the 0600
401
+ // auth.json is enough: we cannot rule out an invoice, same conservative
402
+ // doctrine as Anthropic keys. The instance is the file, not a parsed
403
+ // provider name.
404
+ export function deriveCiBillingMode(
405
+ env: Record<string, string | undefined>,
406
+ opts?: { openCodeAuthPresent?: boolean },
407
+ ): CiBillingMode {
408
+ return envBillsMetered(env) || opts?.openCodeAuthPresent === true
409
+ ? "metered"
410
+ : "subscription";
411
+ }
412
+
413
+ export const CI_DEFAULT_METERED_BUDGET_USD = 10;
414
+
415
+ export interface CiBudgetCeiling {
416
+ // `undefined` means NO ceiling — the gate does not run at all. Distinct from
417
+ // a `0` ceiling, which reaches `evaluateBudgetGate` and is allowed there by
418
+ // the `<= 0` convention; the two arrive by different routes and the shell
419
+ // announces them with different messages.
420
+ budgetUsd: number | undefined;
421
+ source: "operator" | "default-metered" | "unlimited-subscription";
422
+ }
423
+
424
+ // Total over the four cases. `source` exists so the caller can tell the two
425
+ // no-ceiling outcomes apart without re-deriving why.
426
+ //
427
+ // An explicitly configured value is honoured verbatim on ANY route — that is
428
+ // how an operator imposes a ceiling on a subscription (`budget-usd: 5`) or
429
+ // removes one on a metered route (`budget-usd: 0`, which still reaches
430
+ // `budgetDisabledWarningMessage`). The `configured !== undefined` test is what
431
+ // keeps 0 and negatives on the operator branch: falling back to a truthiness
432
+ // check would swallow the explicit disable and silently reimpose the $10 the
433
+ // operator just removed.
434
+ export function resolveCiBudgetCeiling(input: {
435
+ configured: number | undefined;
436
+ billingMode: CiBillingMode;
437
+ }): CiBudgetCeiling {
438
+ if (input.configured !== undefined) {
439
+ return { budgetUsd: input.configured, source: "operator" };
440
+ }
441
+ if (input.billingMode === "metered") {
442
+ return {
443
+ budgetUsd: CI_DEFAULT_METERED_BUDGET_USD,
444
+ source: "default-metered",
445
+ };
446
+ }
447
+ return { budgetUsd: undefined, source: "unlimited-subscription" };
448
+ }
449
+
450
+ // The loudness half. `unlimited-subscription` produces no ceiling and would
451
+ // otherwise be silent, which is the exact shape this module already refuses
452
+ // for the `<= 0` case: a disable is only safe when it is loud.
453
+ //
454
+ // Kept SEPARATE from `budgetDisabledWarningMessage`, and separate in register
455
+ // too — a NOTE, not a warning. The operator chose nothing wrong here; they
456
+ // configured nothing and the policy resolved. Merging the two would tell
457
+ // someone who never set `budget-usd` that they disabled something.
458
+ export function budgetUnlimitedNoticeMessage(
459
+ ceiling: CiBudgetCeiling,
460
+ ): string | null {
461
+ if (ceiling.source !== "unlimited-subscription") return null;
462
+ return (
463
+ "no budget-usd ceiling was applied: this route has no per-token invoice " +
464
+ "credential (a Claude subscription or a free route), so a run draws on " +
465
+ "quota rather than a per-token invoice and the estimated cost is not a " +
466
+ "dollar figure to gate on. The size gate resolves from the route separately. " +
467
+ "Set `budget-usd: <n>` to impose a ceiling anyway."
468
+ );
469
+ }
470
+
471
+ // ---------------------------------------------------------------------------
472
+ // Route-aware size limits — the size gate's half of the #156 policy above.
473
+ // The size gate is a COST and predictability gate (review/size-gate.ts's own
474
+ // header), and on a subscription route a run's cash cost is $0. Skipping the
475
+ // largest PRs there saved nothing and left the riskiest changes unreviewed:
476
+ // on musive, 20 PRs in two months got no review at all. So, per knob: an
477
+ // explicit flag wins; a value in the repo config is left for sizeGateConfig
478
+ // to apply; otherwise a subscription route gets no limit (0) and a metered
479
+ // route keeps the limits the action used to hard-code.
480
+ // ---------------------------------------------------------------------------
481
+
482
+ // The action's former `max-changed-files` default. Kept for metered routes so
483
+ // unsetting the action input changes nothing for anyone who pays per token.
484
+ // Lines need no constant: the engine default (DEFAULT_SIZE_GATE, 4000) already
485
+ // equals the action's former `max-changed-lines` default.
486
+ export const CI_DEFAULT_METERED_MAX_CHANGED_FILES = 50;
487
+
488
+ export interface CiSizeLimits {
489
+ // `undefined` means "not decided here": sizeGateConfig then applies the
490
+ // repo config value, or the engine default.
491
+ maxChangedLines: number | undefined;
492
+ maxChangedFiles: number | undefined;
493
+ // The knobs THIS policy turned off. Non-empty only on a subscription route,
494
+ // and only for knobs neither the flags nor the repo config set. It feeds the
495
+ // notice below, because a gate that silently stops running is a defect in
496
+ // this module's doctrine.
497
+ defaultedOff: Array<"lines" | "files">;
498
+ }
499
+
500
+ export function resolveCiSizeLimits(input: {
501
+ flags: { maxChangedLines?: number; maxChangedFiles?: number };
502
+ config:
503
+ | { max_changed_lines?: number; max_changed_files?: number }
504
+ | undefined;
505
+ billingMode: CiBillingMode;
506
+ }): CiSizeLimits {
507
+ const defaultedOff: Array<"lines" | "files"> = [];
508
+ const knob = (
509
+ flag: number | undefined,
510
+ configured: number | undefined,
511
+ meteredDefault: number | undefined,
512
+ name: "lines" | "files",
513
+ ): number | undefined => {
514
+ if (flag !== undefined) return flag;
515
+ if (configured !== undefined) return undefined;
516
+ if (input.billingMode === "metered") return meteredDefault;
517
+ defaultedOff.push(name);
518
+ return 0;
519
+ };
520
+ const maxChangedLines = knob(
521
+ input.flags.maxChangedLines,
522
+ input.config?.max_changed_lines,
523
+ undefined,
524
+ "lines",
525
+ );
526
+ const maxChangedFiles = knob(
527
+ input.flags.maxChangedFiles,
528
+ input.config?.max_changed_files,
529
+ CI_DEFAULT_METERED_MAX_CHANGED_FILES,
530
+ "files",
531
+ );
532
+ return { maxChangedLines, maxChangedFiles, defaultedOff };
533
+ }
534
+
535
+ // A NOTE, like budgetUnlimitedNoticeMessage: nobody chose anything wrong, but
536
+ // a gate that did not run is still announced.
537
+ export function sizeGateUnlimitedNoticeMessage(
538
+ limits: CiSizeLimits,
539
+ ): string | null {
540
+ if (limits.defaultedOff.length === 0) return null;
541
+ const what = limits.defaultedOff
542
+ .map((k) => (k === "lines" ? "changed-lines" : "changed-files"))
543
+ .join(" or ");
544
+ return (
545
+ `crysk size gate: no ${what} limit on a Claude subscription route — ` +
546
+ "a run draws on quota, not a per-token invoice, so large PRs are " +
547
+ "reviewed instead of skipped. Set `max-changed-lines` / " +
548
+ "`max-changed-files` to impose a limit."
549
+ );
550
+ }
551
+
552
+ // ---------------------------------------------------------------------------
553
+ // CI skip plan — the ONE call reviewPr's shell makes per gate. Composes
554
+ // ciSizeGateSkip/ciBudgetGateSkip's {comment, summary} with renderStepSummary
555
+ // (ci/reporter.ts) and the $GITHUB_OUTPUT contract into everything the shell
556
+ // needs to publish, so the shell's own job is pure mechanical glue: post
557
+ // `comment` under `markerPrefix` if `--post`, append `summaryMarkdown` if
558
+ // step-summary is on, append `outputs` if $GITHUB_OUTPUT is set, return 0.
559
+ // ---------------------------------------------------------------------------
560
+
561
+ export interface CiGateSkipPlan {
562
+ comment: string;
563
+ // Fed to pr/pr.ts's postPrComment as its `markerPrefix` — idempotent per gate
564
+ // kind, so a repeat CI run on the same still-failing PR updates the
565
+ // existing skip comment instead of stacking a new one on every push.
566
+ markerPrefix: string;
567
+ summaryMarkdown: string;
568
+ outputs: CiOutputs;
569
+ }
570
+
571
+ // Spec 1.1's $GITHUB_OUTPUT contract for a skip: no review ran, so every
572
+ // finding count is 0 and there is no run dir. `estimatedCostUsd` is 0 for a
573
+ // size skip (the gate fires before any cost estimate exists) and the
574
+ // estimate that tripped the ceiling for a budget skip — the same number the
575
+ // comment and summary already show (this module's own "same numbers"
576
+ // doctrine, see the module header).
577
+ export function ciGateSkipOutputs(
578
+ status:
579
+ | "skipped-size"
580
+ | "skipped-budget"
581
+ | "skipped-coverage"
582
+ | "manual-required",
583
+ estimatedCostUsd: number,
584
+ ): CiOutputs {
585
+ return {
586
+ status,
587
+ findings_count: 0,
588
+ blocking_count: 0,
589
+ advisory_count: 0,
590
+ cost_usd_est: estimatedCostUsd,
591
+ run_dir: "",
592
+ };
593
+ }
594
+
595
+ export function planCiSizeSkip(
596
+ input: CiSizeGateSkipInput & { ciMode: CiMode },
597
+ ): CiGateSkipPlan | null {
598
+ const skip = ciSizeGateSkip(input);
599
+ if (skip === null) return null;
600
+ return {
601
+ comment: skip.comment,
602
+ markerPrefix: SKIP_SIZE_COMMENT_MARKER,
603
+ summaryMarkdown: renderStepSummary(skip.summary, input.ciMode),
604
+ outputs: ciGateSkipOutputs("skipped-size", 0),
605
+ };
606
+ }
607
+
608
+ export function planCiBudgetSkip(
609
+ input: CiBudgetGateSkipInput & { force: boolean; ciMode: CiMode },
610
+ ): CiGateSkipPlan | null {
611
+ // CI `--force` is the `/crysk review` comment. It answers "run this one
612
+ // anyway" for every CI skip, including the spend ceiling. Outside that
613
+ // explicit comment the ceiling still holds. Local `--force` never reaches
614
+ // here: the caller only invokes this plan when `isCi` is set.
615
+ if (input.force) return null;
616
+ const skip = ciBudgetGateSkip(input);
617
+ if (skip === null) return null;
618
+ return {
619
+ comment: skip.comment,
620
+ markerPrefix: SKIP_BUDGET_COMMENT_MARKER,
621
+ summaryMarkdown: renderStepSummary(skip.summary, input.ciMode),
622
+ outputs: ciGateSkipOutputs("skipped-budget", input.estimatedCostUsd),
623
+ };
624
+ }
625
+
626
+ const COVERAGE_REASON_LABEL: Record<
627
+ Extract<CiReviewAdmissionVerdict, { action: "skip" }>["reason"],
628
+ string
629
+ > = {
630
+ "same-head": "already reviewed at this commit",
631
+ "once-per-pr": "once_per_pr policy allows one automatic review",
632
+ "below-threshold": "prior findings below the re-review score floor",
633
+ "low-risk-delta": "delta touches only low-risk paths",
634
+ stopped: "automatic reviews stopped by a maintainer",
635
+ };
636
+
637
+ function buildCoverageSkipComment(
638
+ data: SkipCoverageSummary,
639
+ reason: CiReviewSkipReason,
640
+ ): string {
641
+ // A stop is a maintainer's decision, not a score: the score line would
642
+ // blame the push for a skip it did not cause.
643
+ const stopped = reason === "stopped";
644
+ const lines = [
645
+ SKIP_COVERAGE_COMMENT_MARKER,
646
+ "## Crysk review skipped",
647
+ "",
648
+ stopped
649
+ ? "⏸️ A maintainer stopped automatic reviews on this pull request."
650
+ : "⚠️ This push did not justify another review run.",
651
+ "",
652
+ `**${data.detail}**`,
653
+ "",
654
+ stopped
655
+ ? `Attempts on this PR: ${data.reviewCount}/${data.maxAttempts}.`
656
+ : `Prior score: ${data.priorScore} (re-review needs ≥ ${data.minScore}). ` +
657
+ `Attempts on this PR: ${data.reviewCount}/${data.maxAttempts}.`,
658
+ "",
659
+ "The existing review comment still describes the last head Crysk " +
660
+ "reviewed.",
661
+ "",
662
+ ciForceReviewHintLine(data.prNumber),
663
+ ];
664
+ return `${lines.join("\n")}\n`;
665
+ }
666
+
667
+ function buildManualRequiredComment(data: ManualRequiredSummary): string {
668
+ const lines = [
669
+ MANUAL_REQUIRED_COMMENT_MARKER,
670
+ "## Crysk review requires manual override",
671
+ "",
672
+ "🛑 Automatic review did not run on this push.",
673
+ "",
674
+ `**${data.detail}**`,
675
+ "",
676
+ `Attempts on this PR: ${data.reviewCount}/${data.maxAttempts}.`,
677
+ "",
678
+ "The existing review comment still describes the last head Crysk " +
679
+ "reviewed.",
680
+ "",
681
+ ciForceReviewHintLine(data.prNumber),
682
+ ];
683
+ return `${lines.join("\n")}\n`;
684
+ }
685
+
686
+ export interface AdmissionContext {
687
+ currentHead: string;
688
+ reviewedHead: string | null;
689
+ policyMode: CiReviewPolicyMode;
690
+ policyHash: string;
691
+ deltaRisk?: DeltaRiskAssessment | null;
692
+ }
693
+
694
+ function skipAdmissionSummaryFields(
695
+ verdict: Extract<CiReviewAdmissionVerdict, { action: "skip" }>,
696
+ context?: AdmissionContext,
697
+ ): Partial<SkipCoverageSummary> {
698
+ if (context === undefined) return {};
699
+ return {
700
+ decision: "skip",
701
+ admissionReason: verdict.reason,
702
+ currentHead: context.currentHead,
703
+ reviewedHead: context.reviewedHead,
704
+ riskClass: context.deltaRisk?.class,
705
+ riskReason: context.deltaRisk?.reason,
706
+ remainingBudget: ciAdmissionRemainingBudget(
707
+ verdict.reviewCount,
708
+ verdict.maxAttempts,
709
+ ),
710
+ policyMode: context.policyMode,
711
+ policyHash: context.policyHash,
712
+ };
713
+ }
714
+
715
+ function manualAdmissionSummaryFields(
716
+ verdict: Extract<CiReviewAdmissionVerdict, { action: "manual-required" }>,
717
+ context?: AdmissionContext,
718
+ ): Partial<ManualRequiredSummary> {
719
+ if (context === undefined) return {};
720
+ return {
721
+ decision: "manual-required",
722
+ admissionReason: verdict.reason,
723
+ currentHead: context.currentHead,
724
+ reviewedHead: context.reviewedHead,
725
+ riskClass: context.deltaRisk?.class,
726
+ riskReason: context.deltaRisk?.reason,
727
+ remainingBudget: ciAdmissionRemainingBudget(
728
+ verdict.reviewCount,
729
+ verdict.maxAttempts,
730
+ ),
731
+ policyMode: context.policyMode,
732
+ policyHash: context.policyHash,
733
+ };
734
+ }
735
+
736
+ export function planCiReviewSkip(input: {
737
+ prNumber: number;
738
+ verdict: Extract<CiReviewAdmissionVerdict, { action: "skip" }>;
739
+ admission?: AdmissionContext;
740
+ ciMode: CiMode;
741
+ }): CiGateSkipPlan {
742
+ const detail = ciReviewSkipDetail(input.verdict);
743
+ const summary: SkipCoverageSummary = {
744
+ kind: "skipped-coverage",
745
+ prNumber: input.prNumber,
746
+ reason: COVERAGE_REASON_LABEL[input.verdict.reason],
747
+ detail,
748
+ priorScore: input.verdict.prior.score,
749
+ minScore: input.verdict.minScore,
750
+ reviewCount: input.verdict.reviewCount,
751
+ maxAttempts: input.verdict.maxAttempts,
752
+ ...skipAdmissionSummaryFields(input.verdict, input.admission),
753
+ };
754
+ return {
755
+ comment: buildCoverageSkipComment(summary, input.verdict.reason),
756
+ markerPrefix: SKIP_COVERAGE_COMMENT_MARKER,
757
+ summaryMarkdown: renderStepSummary(summary, input.ciMode),
758
+ outputs: ciGateSkipOutputs("skipped-coverage", 0),
759
+ };
760
+ }
761
+
762
+ export function planCiReviewManualRequired(input: {
763
+ prNumber: number;
764
+ verdict: Extract<CiReviewAdmissionVerdict, { action: "manual-required" }>;
765
+ admission?: AdmissionContext;
766
+ ciMode: CiMode;
767
+ }): CiGateSkipPlan {
768
+ const detail = ciReviewManualRequiredDetail(input.verdict);
769
+ const summary: ManualRequiredSummary = {
770
+ kind: "manual-required",
771
+ prNumber: input.prNumber,
772
+ reason:
773
+ input.verdict.reason === "max-attempts-exhausted"
774
+ ? "automatic attempt budget exhausted"
775
+ : "manual_only policy",
776
+ detail,
777
+ priorScore: input.verdict.prior.score,
778
+ reviewCount: input.verdict.reviewCount,
779
+ maxAttempts: input.verdict.maxAttempts,
780
+ ...manualAdmissionSummaryFields(input.verdict, input.admission),
781
+ };
782
+ return {
783
+ comment: buildManualRequiredComment(summary),
784
+ markerPrefix: MANUAL_REQUIRED_COMMENT_MARKER,
785
+ summaryMarkdown: renderStepSummary(summary, input.ciMode),
786
+ outputs: ciGateSkipOutputs("manual-required", 0),
787
+ };
788
+ }
789
+
790
+ // ---------------------------------------------------------------------------
791
+ // Assistant posture — spec 2.1: "The CLI MUST NOT exit with a non-zero code
792
+ // merely because findings (even `blocking` ones) were discovered ... exit
793
+ // non-zero ONLY on fatal execution failures." `blockingCount` is accepted
794
+ // and deliberately NEVER read: its only job is to let a test construct a
795
+ // high-blocking-count input and assert the result is still 0, so a future
796
+ // change that wires it into this function's logic (the exact regression
797
+ // this rule guards against) fails that test rather than shipping silently.
798
+ // ---------------------------------------------------------------------------
799
+
800
+ export function ciExitCode(input: {
801
+ sessionFailed: boolean;
802
+ droppedFindingIds: number;
803
+ blockingCount: number;
804
+ }): 0 | 1 {
805
+ if (input.sessionFailed) return 1;
806
+ if (input.droppedFindingIds > 0) return 1;
807
+ return 0;
808
+ }
809
+
810
+ // ---------------------------------------------------------------------------
811
+ // CI headless shell's "reviewed" (non-skip) outcome (ROADMAP Pillar 3,
812
+ // GitHub Actions) — the summary + outputs, and the pure "should I write"
813
+ // gates the shell checks before touching $GITHUB_STEP_SUMMARY/$GITHUB_OUTPUT.
814
+ // planCiReviewSkip/planCiReviewManualRequired above cover the two admission
815
+ // outcomes the same way; planCiReview is their sibling for a review that
816
+ // actually ran. Extracted from cli.ts (cli-decomp S2, Cluster B) — this
817
+ // module's own purity rule holds unchanged, every function below is a total
818
+ // function of its arguments.
819
+ // ---------------------------------------------------------------------------
820
+
821
+ // Spec 2.1's "reviewed" step-summary + spec 1.1's $GITHUB_OUTPUT contract,
822
+ // from the SAME findings array — so the two can never disagree on counts.
823
+ // `delta`/`repoWebUrl` are optional pass-throughs (posted.delta when a run
824
+ // posted; undefined renders plain code spans / omits the delta line).
825
+ export function planCiReview(input: {
826
+ prNumber: number;
827
+ headSha: string;
828
+ findings: readonly Finding[];
829
+ costUsdEst: number;
830
+ wallMs: number;
831
+ model: string;
832
+ repoWebUrl?: string;
833
+ delta?: PrCommentDelta;
834
+ runDir: string;
835
+ ciMode: CiMode;
836
+ }): { summaryMarkdown: string; outputs: CiOutputs } {
837
+ const blockingCount = input.findings.filter(
838
+ (f) => f.tier === "blocking",
839
+ ).length;
840
+ const summary: CiSummaryData = {
841
+ kind: "reviewed",
842
+ prNumber: input.prNumber,
843
+ headSha: input.headSha,
844
+ findings: input.findings,
845
+ costUsdEst: input.costUsdEst,
846
+ wallMs: input.wallMs,
847
+ model: input.model,
848
+ ...(input.repoWebUrl === undefined ? {} : { repoWebUrl: input.repoWebUrl }),
849
+ ...(input.delta === undefined ? {} : { delta: input.delta }),
850
+ };
851
+ return {
852
+ summaryMarkdown: renderStepSummary(summary, input.ciMode),
853
+ outputs: {
854
+ status: "reviewed",
855
+ findings_count: input.findings.length,
856
+ blocking_count: blockingCount,
857
+ advisory_count: input.findings.length - blockingCount,
858
+ cost_usd_est: input.costUsdEst,
859
+ run_dir: input.runDir,
860
+ },
861
+ };
862
+ }
863
+
864
+ // Design D6, applied to the CI headless channel: a failed session publishes
865
+ // NOTHING. `sessionFailed` means every hunter died, which leaves the merged
866
+ // document with zero findings — so the "reviewed" payload built from it would
867
+ // claim `status=reviewed` + a "No findings detected" step summary for a review
868
+ // that never ran. The job exits non-zero either way, but a human reads the job
869
+ // summary, not the exit code, and postInlineIfEligible already suppresses PR
870
+ // posting on exactly this condition; the CI channel must not be the one place
871
+ // a crashed run still asserts a clean tree.
872
+ export function shouldPublishCiReview(
873
+ isCi: boolean,
874
+ sessionFailed: boolean,
875
+ ): boolean {
876
+ return isCi && !sessionFailed;
877
+ }
878
+
879
+ // Spec 1.1: "Output parameter writing when $GITHUB_OUTPUT is provided" —
880
+ // the outputs are core to the Action's own contract (declared unconditionally
881
+ // in action.yml), so nothing beyond CI mode + a real path gates them.
882
+ export function shouldWriteCiOutputs(
883
+ isCi: boolean,
884
+ outputPath: string | undefined,
885
+ ): boolean {
886
+ return isCi && outputPath !== undefined && outputPath.length > 0;
887
+ }
888
+
889
+ // Spec 2.1: step-summary writing is additionally gated on the tri-state
890
+ // `--step-summary`/`--no-step-summary` flag (`stepSummary`), unset meaning
891
+ // the shell's own default of on — mirroring `summary`/`scout`'s own
892
+ // unset-means-default convention (preflight.ts's CliOptions).
893
+ export function shouldWriteStepSummary(
894
+ isCi: boolean,
895
+ stepSummaryFlag: boolean | undefined,
896
+ summaryPath: string | undefined,
897
+ ): boolean {
898
+ return (
899
+ isCi &&
900
+ (stepSummaryFlag ?? true) &&
901
+ summaryPath !== undefined &&
902
+ summaryPath.length > 0
903
+ );
904
+ }
905
+
906
+ // Pure on purpose (design Threat Matrix, "Git repository selection" row,
907
+ // deferred from PR2's verification): --from names a directory on disk, and
908
+ // nothing stops it from pointing at a DIFFERENT PR's run than --pr names.
909
+ // findings.json's own `pr` field is the one thing that cannot lie about
910
+ // which review it came from — checked here, before any fetch or post,
911
+ // rather than trusting the operator to keep --pr and --from in sync by hand.
912
+ export function assertRunMatchesPr(
913
+ doc: FindingsDocument,
914
+ pr: number,
915
+ runDir: string,
916
+ ): void {
917
+ if (doc.pr !== pr) {
918
+ throw new CliUsageError(
919
+ `${runDir} is a run of PR #${doc.pr}, not PR #${pr} — point --from ` +
920
+ "at a run directory for the PR you are posting to",
921
+ );
922
+ }
923
+ }