crysk 0.0.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +611 -3
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/SKILL-y8rv8msh.md +134 -0
  10. package/dist/SKILL-ygka1bs0.md +515 -0
  11. package/dist/adjudicator-dtg2axnh.md +86 -0
  12. package/dist/admission-config.example-a9vqmmad.json +9 -0
  13. package/dist/ci-admission-camfbx2b.md +122 -0
  14. package/dist/ci-admission-qk9r9taq.md +124 -0
  15. package/dist/cli.js +42501 -0
  16. package/dist/consolidate-ac0mnfyj.md +24 -0
  17. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  18. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  19. package/dist/deep-review-parity-0ec904db.md +120 -0
  20. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  21. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  22. package/dist/index.js +20190 -0
  23. package/dist/opencode-ci-7b0be64p.md +141 -0
  24. package/dist/review-refuter-j4e9gezy.md +71 -0
  25. package/dist/scout-yvp153q7.md +140 -0
  26. package/dist/summarizer-zca44nxa.md +18 -0
  27. package/dist/workflow-w1g9szna.yml +151 -0
  28. package/package.json +81 -4
  29. package/prompts/consolidate.md +24 -0
  30. package/prompts/default/PROVENANCE.md +18 -0
  31. package/prompts/default/deep-review-lifecycle.md +362 -0
  32. package/prompts/default/deep-review-logic.md +156 -0
  33. package/prompts/default/deep-review-parity.md +120 -0
  34. package/prompts/default/deep-review-reliability.md +125 -0
  35. package/prompts/default/deep-review-resilience.md +118 -0
  36. package/prompts/default/review-refuter.md +71 -0
  37. package/prompts/scout.md +140 -0
  38. package/prompts/summarizer.md +18 -0
  39. package/skills/crysk/SKILL.md +74 -0
  40. package/skills/crysk-ci-setup/SKILL.md +134 -0
  41. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  42. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  43. package/skills/crysk-ci-setup/references/ci-admission.md +124 -0
  44. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  45. package/skills/crysk-loop/SKILL.md +515 -0
  46. package/skills/crysk-loop/adjudicator.md +86 -0
  47. package/skills/crysk-pr/SKILL.md +66 -0
  48. package/src/agent-env.ts +1084 -0
  49. package/src/asset-manifest.ts +83 -0
  50. package/src/assets.d.ts +6 -0
  51. package/src/assets.ts +183 -0
  52. package/src/brand-paths.ts +155 -0
  53. package/src/brand.ts +255 -0
  54. package/src/ci/admission-ledger.ts +350 -0
  55. package/src/ci/classify-error.ts +73 -0
  56. package/src/ci/cli-record.ts +271 -0
  57. package/src/ci/force-comment.ts +39 -0
  58. package/src/ci/gates.ts +945 -0
  59. package/src/ci/outcome.ts +2181 -0
  60. package/src/ci/override.ts +187 -0
  61. package/src/ci/publish.ts +1639 -0
  62. package/src/ci/reporter.ts +626 -0
  63. package/src/ci/review-admission.ts +910 -0
  64. package/src/ci/review-levels.ts +310 -0
  65. package/src/ci/review-policy.ts +18 -0
  66. package/src/ci/review-risk.ts +184 -0
  67. package/src/ci/setup.ts +844 -0
  68. package/src/ci/trigger.ts +1353 -0
  69. package/src/cli.ts +348 -0
  70. package/src/commands/activity.ts +67 -0
  71. package/src/commands/ci-setup-questions.ts +397 -0
  72. package/src/commands/ci-setup.ts +381 -0
  73. package/src/commands/config.ts +99 -0
  74. package/src/commands/doctor.ts +108 -0
  75. package/src/commands/init.ts +139 -0
  76. package/src/commands/mcp.ts +10 -0
  77. package/src/commands/menu.ts +129 -0
  78. package/src/commands/post.ts +302 -0
  79. package/src/commands/skills.ts +83 -0
  80. package/src/commands/status.ts +173 -0
  81. package/src/commands/triage.ts +342 -0
  82. package/src/commands/uninstall.ts +37 -0
  83. package/src/commands/upgrade.ts +214 -0
  84. package/src/commands/usage.ts +98 -0
  85. package/src/compare/compare.ts +28 -0
  86. package/src/compare/floor-test.ts +471 -0
  87. package/src/compare/martian-adapter.ts +80 -0
  88. package/src/config/config.ts +267 -0
  89. package/src/corpus/corpus.ts +1094 -0
  90. package/src/corpus/preflight.ts +1789 -0
  91. package/src/diversity/accounting.ts +90 -0
  92. package/src/diversity/adjudication.ts +145 -0
  93. package/src/diversity/admission.ts +60 -0
  94. package/src/diversity/benchmark.ts +195 -0
  95. package/src/diversity/clustering.ts +285 -0
  96. package/src/diversity/errors.ts +7 -0
  97. package/src/diversity/identity.ts +285 -0
  98. package/src/diversity/index.ts +11 -0
  99. package/src/diversity/pipeline-integration.ts +448 -0
  100. package/src/diversity/projection.ts +57 -0
  101. package/src/diversity/self-contained.ts +68 -0
  102. package/src/diversity/target-validation.ts +179 -0
  103. package/src/doctor-migration.ts +209 -0
  104. package/src/doctor.ts +723 -0
  105. package/src/errors.ts +83 -0
  106. package/src/execution/admission.ts +75 -0
  107. package/src/execution/atomic-write.ts +35 -0
  108. package/src/execution/attempt-evidence.ts +415 -0
  109. package/src/execution/bucket-id.ts +136 -0
  110. package/src/execution/concurrency-limiter.ts +175 -0
  111. package/src/execution/contracts.ts +443 -0
  112. package/src/execution/failure-classification.ts +42 -0
  113. package/src/execution/failure-policy.ts +240 -0
  114. package/src/execution/harness.ts +2548 -0
  115. package/src/execution/settlement.ts +348 -0
  116. package/src/execution/spawned-process.ts +66 -0
  117. package/src/execution/spend-limiter.ts +424 -0
  118. package/src/execution/step-artifacts.ts +55 -0
  119. package/src/execution/usage-normalized.ts +469 -0
  120. package/src/git/git.ts +396 -0
  121. package/src/git/identity.ts +64 -0
  122. package/src/git/refs.ts +140 -0
  123. package/src/home-preflight.ts +443 -0
  124. package/src/home.ts +243 -0
  125. package/src/ignore-file.ts +336 -0
  126. package/src/ignore-read.ts +118 -0
  127. package/src/index.ts +34 -0
  128. package/src/legacy-launchd.ts +29 -0
  129. package/src/mcp/mcp.ts +150 -0
  130. package/src/mcp/preflight.ts +407 -0
  131. package/src/menu-context.ts +192 -0
  132. package/src/model/catalog.ts +251 -0
  133. package/src/model/exec-snapshots.ts +390 -0
  134. package/src/model/free-discovery.ts +302 -0
  135. package/src/model/provider-capabilities.ts +814 -0
  136. package/src/model/routing.ts +600 -0
  137. package/src/pr/admission.ts +984 -0
  138. package/src/pr/answered-findings.ts +169 -0
  139. package/src/pr/ci-admission-gate.ts +743 -0
  140. package/src/pr/ci-publish.ts +76 -0
  141. package/src/pr/discovery.ts +432 -0
  142. package/src/pr/inline.ts +507 -0
  143. package/src/pr/plan.ts +366 -0
  144. package/src/pr/posting.ts +115 -0
  145. package/src/pr/pr-status.ts +845 -0
  146. package/src/pr/pr.ts +3642 -0
  147. package/src/pr/preflight.ts +1031 -0
  148. package/src/pr/publish-outcome.ts +361 -0
  149. package/src/pr/range.ts +119 -0
  150. package/src/pr/reverts-preflight.ts +606 -0
  151. package/src/pr/reverts.ts +377 -0
  152. package/src/pr/review-pr.ts +927 -0
  153. package/src/pr/status.ts +154 -0
  154. package/src/pr/target.ts +388 -0
  155. package/src/pr/teardown.ts +437 -0
  156. package/src/pr/worktree-setup.ts +60 -0
  157. package/src/production-runtime.ts +1877 -0
  158. package/src/progress.ts +487 -0
  159. package/src/rereview/adjudicate.ts +89 -0
  160. package/src/rereview/classify.ts +362 -0
  161. package/src/rereview/identity.ts +211 -0
  162. package/src/rereview/plan.ts +308 -0
  163. package/src/rereview/prepare.ts +1025 -0
  164. package/src/rereview/state.ts +767 -0
  165. package/src/rereview/verify.ts +241 -0
  166. package/src/review/boundary.ts +105 -0
  167. package/src/review/consolidate.ts +246 -0
  168. package/src/review/dedupe.ts +368 -0
  169. package/src/review/drafts.ts +448 -0
  170. package/src/review/findings-conformance.ts +120 -0
  171. package/src/review/findings.ts +714 -0
  172. package/src/review/pipeline.ts +3977 -0
  173. package/src/review/preflight.ts +3575 -0
  174. package/src/review/prompt-set.ts +177 -0
  175. package/src/review/proof-refs.ts +187 -0
  176. package/src/review/report.ts +1821 -0
  177. package/src/review/review.ts +490 -0
  178. package/src/review/root-cause.ts +120 -0
  179. package/src/review/route-preflight.ts +289 -0
  180. package/src/review/run.ts +601 -0
  181. package/src/review/scout.ts +323 -0
  182. package/src/review/size-gate.ts +595 -0
  183. package/src/review/spec.ts +235 -0
  184. package/src/review/step-runner.ts +233 -0
  185. package/src/runner-authority.ts +596 -0
  186. package/src/security/binding-policy.ts +115 -0
  187. package/src/security/credential-broker.ts +773 -0
  188. package/src/security/evidence-redaction.ts +62 -0
  189. package/src/security/execution-authority.ts +27 -0
  190. package/src/security/redact.ts +71 -0
  191. package/src/security/workspace-read-broker.ts +466 -0
  192. package/src/server/client.ts +190 -0
  193. package/src/server/preflight.ts +217 -0
  194. package/src/server/server.ts +327 -0
  195. package/src/signal-handler.ts +50 -0
  196. package/src/store/activity.ts +413 -0
  197. package/src/store/backfill-preflight.ts +49 -0
  198. package/src/store/backfill.ts +141 -0
  199. package/src/store/gc-preflight.ts +206 -0
  200. package/src/store/gc.ts +424 -0
  201. package/src/store/metrics-preflight.ts +229 -0
  202. package/src/store/metrics.ts +236 -0
  203. package/src/store/preflight.ts +748 -0
  204. package/src/store/store.ts +693 -0
  205. package/src/system-tools.ts +355 -0
  206. package/src/transport-registry.ts +1124 -0
  207. package/src/transports/claude-code-cli.ts +1348 -0
  208. package/src/transports/opencode-admission.ts +515 -0
  209. package/src/transports/opencode-client.ts +3328 -0
  210. package/src/transports/opencode-evidence.ts +557 -0
  211. package/src/transports/opencode-mcp.ts +248 -0
  212. package/src/transports/opencode-sdk.ts +2294 -0
  213. package/src/transports/opencode-server.ts +535 -0
  214. package/src/triage/adjudication.ts +113 -0
  215. package/src/triage/reply.ts +125 -0
  216. package/src/triage/triage.ts +255 -0
  217. package/src/ui/activity.ts +173 -0
  218. package/src/ui/config-edit.ts +816 -0
  219. package/src/ui/config.ts +462 -0
  220. package/src/ui/menu.ts +1325 -0
  221. package/src/ui/plan.ts +1039 -0
  222. package/src/ui/primitives.ts +300 -0
  223. package/src/ui/progress.ts +298 -0
  224. package/src/ui/result.ts +552 -0
  225. package/src/ui/review-menu.ts +312 -0
  226. package/src/ui/select.ts +528 -0
  227. package/src/ui/tree.ts +178 -0
  228. package/src/uninstaller.ts +479 -0
  229. package/src/updater.ts +836 -0
  230. package/src/usage.ts +77 -0
  231. package/src/watch/preflight.ts +1389 -0
  232. package/src/watch/watch.ts +1235 -0
  233. package/src/wizard.ts +877 -0
@@ -0,0 +1,984 @@
1
+ // CI admission ledger state and skip publishing helpers.
2
+ // Extracted from cli.ts (cli-decomp S5).
3
+
4
+ import {
5
+ type AdmissionAttemptStatus,
6
+ type AdmissionRecord,
7
+ reserveAdmissionAttempt,
8
+ settleAdmissionAttempt,
9
+ } from "#ci/admission-ledger";
10
+ import { classifyCliError } from "#ci/classify-error";
11
+ import { writeCliRecord } from "#ci/cli-record";
12
+ import {
13
+ type CiGateSkipPlan,
14
+ shouldWriteCiOutputs,
15
+ shouldWriteStepSummary,
16
+ } from "#ci/gates";
17
+ import type { CliRecord } from "#ci/outcome";
18
+ import { isOverrideStatus, newestStatusInContext } from "#ci/override";
19
+ import {
20
+ appendCiOutputs,
21
+ appendStepSummary,
22
+ formatWorkflowCommand,
23
+ } from "#ci/reporter";
24
+ import { type CiReviewPolicy, ciReviewSkipLabel } from "#ci/review-admission";
25
+ import type { AnsweredFindings } from "#pr/answered-findings";
26
+ import {
27
+ fetchCommitStatuses,
28
+ fetchCommitStatusList,
29
+ fetchPrCommitShas,
30
+ ghRepoWebUrl,
31
+ repostMarkedPrComment,
32
+ upsertAdmissionCheckRun,
33
+ } from "#pr/pr";
34
+ import {
35
+ blockingCommitStatusRequest,
36
+ type CiMode,
37
+ COMMIT_STATUS_CONTEXT,
38
+ type CommitStatusFact,
39
+ clipStatusDescription,
40
+ commitStatusRequest,
41
+ partialReviewAgainDescription,
42
+ partialReviewDescription,
43
+ prHtmlUrl,
44
+ skipCommitStatusRequest,
45
+ } from "#pr/preflight";
46
+ import { publishFinalCommitStatus } from "#pr/status";
47
+ import { log } from "#ui/primitives";
48
+ import { canonicalStatusText, STATUS_CONTEXT } from "../brand";
49
+
50
+ // ROADMAP Pillar 3 (GitHub Actions CI). The mechanical glue behind a gate
51
+ // skip in CI mode: every DECISION (what to say, which marker, what the
52
+ // outputs are) already happened in `plan` (planCiSizeSkip/planCiBudgetSkip,
53
+ // ci/gates.ts) — this function has nothing left to decide, only three
54
+ // straight-line I/O calls gated by shouldWriteStepSummary/shouldWriteCiOutputs.
55
+ // `repostMarkedPrComment` keeps one notice per marker without hiding it: a
56
+ // repeat CI run on the same still-failing PR posts the fresh notice at the
57
+ // bottom and deletes its own older ones, instead of silently editing the old
58
+ // one in place (an edit neither notifies nor moves down the timeline).
59
+ export type CiAdmissionLedgerState = {
60
+ record: AdmissionRecord;
61
+ checkRunId: number;
62
+ headSha: string;
63
+ operatorRoot: string;
64
+ };
65
+
66
+ export async function persistCiAdmissionLedger(
67
+ state: CiAdmissionLedgerState,
68
+ options?: { spawnFn?: typeof Bun.spawn },
69
+ ): Promise<void> {
70
+ state.checkRunId = await upsertAdmissionCheckRun(
71
+ state.operatorRoot,
72
+ {
73
+ headSha: state.headSha,
74
+ record: state.record,
75
+ checkRunId: state.checkRunId,
76
+ },
77
+ options,
78
+ );
79
+ }
80
+
81
+ export async function tryPersistCiAdmissionLedger(
82
+ state: CiAdmissionLedgerState | null,
83
+ options?: { spawnFn?: typeof Bun.spawn },
84
+ ): Promise<void> {
85
+ if (state === null) return;
86
+ try {
87
+ await persistCiAdmissionLedger(state, options);
88
+ } catch {
89
+ // Best-effort: settlement must not mask the underlying review failure.
90
+ }
91
+ }
92
+
93
+ // `"yielded"` is terminal too: without it here, teardown's safety net (or
94
+ // any later exit) could overwrite a yield with `"failed"`, which is the red
95
+ // check this status exists to prevent. `"gate-skipped"` (#326) is the same:
96
+ // a later settle must not rewrite a gate skip as `"failed"`.
97
+ const TERMINAL_ADMISSION_STATUSES: ReadonlySet<AdmissionAttemptStatus> =
98
+ new Set([
99
+ "completed",
100
+ "failed",
101
+ "cancelled",
102
+ "skipped",
103
+ "yielded",
104
+ "gate-skipped",
105
+ ]);
106
+
107
+ // A record that already reached a terminal status is never re-settled: the
108
+ // review shells call this from several exits (and teardown's finally), and
109
+ // a later call must not overwrite an earlier `completed` with `failed`.
110
+ // `spawnFn` is the gh boundary for offline tests; production omits it.
111
+ // Same shape as the commit-status lock in status.ts, and for the same reason:
112
+ // the SIGTERM/SIGINT handlers live in runCli and end in process.exit(), which
113
+ // skips reviewPr's finally. A cancel-in-progress run otherwise leaves its
114
+ // ledger row at "provider-started" forever, and that status both counts as a
115
+ // spent attempt and blocks the next reservation (#164).
116
+ let heldAdmission: CiAdmissionLedgerState | null = null;
117
+
118
+ export function holdCiAdmissionLedger(
119
+ state: CiAdmissionLedgerState | null,
120
+ ): void {
121
+ heldAdmission = state;
122
+ }
123
+
124
+ export function releaseCiAdmissionLedger(): void {
125
+ heldAdmission = null;
126
+ }
127
+
128
+ // Take-and-clear BEFORE the await. Actions sends SIGINT and then SIGTERM
129
+ // inside the grace window, so both handlers can be in flight; the second
130
+ // must see nothing left to settle. A row that already reached a terminal
131
+ // status (completed, failed, skipped, cancelled, yielded) is left alone —
132
+ // settleCiAdmissionLedger's own guard. Every error is swallowed: failing to
133
+ // settle is the old bug, and a throw here would cost the exit code.
134
+ export async function settleHeldAdmissionLedgerOnSignal(
135
+ settle: typeof settleCiAdmissionLedger = settleCiAdmissionLedger,
136
+ ): Promise<void> {
137
+ const state = heldAdmission;
138
+ heldAdmission = null;
139
+ if (state === null) return;
140
+ if (
141
+ state.record.status !== "reserved" &&
142
+ state.record.status !== "provider-started"
143
+ ) {
144
+ return;
145
+ }
146
+ try {
147
+ await settle(
148
+ state,
149
+ "cancelled",
150
+ "workflow cancelled before the review produced anything",
151
+ );
152
+ } catch {
153
+ // Ignore
154
+ }
155
+ }
156
+
157
+ export async function settleCiAdmissionLedger(
158
+ state: CiAdmissionLedgerState | null,
159
+ status: AdmissionAttemptStatus,
160
+ reason: string,
161
+ options?: { spawnFn?: typeof Bun.spawn },
162
+ ): Promise<void> {
163
+ if (state === null) return;
164
+ if (TERMINAL_ADMISSION_STATUSES.has(state.record.status)) return;
165
+ state.record = settleAdmissionAttempt(state.record, status, reason);
166
+ await tryPersistCiAdmissionLedger(state, options);
167
+ }
168
+
169
+ // #326: the SIZE gate and the BUDGET gate settle through here, not with
170
+ // `"skipped"`. An admission skip (recordCiAdmissionGateSkip below) keeps
171
+ // `"skipped"` and keeps counting; a gate skip spent nothing, so its row must
172
+ // not count against the PR's attempts (see TERMINAL_BUDGET_STATUSES).
173
+ export async function settleCiGateSkip(
174
+ state: CiAdmissionLedgerState | null,
175
+ reason: string,
176
+ options?: { spawnFn?: typeof Bun.spawn },
177
+ ): Promise<void> {
178
+ await settleCiAdmissionLedger(state, "gate-skipped", reason, options);
179
+ }
180
+
181
+ export async function reserveCiAdmissionLedger(input: {
182
+ operatorRoot: string;
183
+ prNumber: number;
184
+ headSha: string;
185
+ policy: CiReviewPolicy;
186
+ policyHash: string;
187
+ existing: readonly AdmissionRecord[];
188
+ decisionReason: string;
189
+ priorScore?: number | null;
190
+ blockingCount?: number | null;
191
+ advisoryCount?: number | null;
192
+ // A comment-triggered run (`/pr-hero review`, `/pr-hero recheck`): its row is
193
+ // marked so the attempt count leaves it out (see countTerminalAttempts).
194
+ forced?: boolean;
195
+ // Test-only seam (default: the real Bun.spawn), threaded to the check-run write.
196
+ spawnFn?: typeof Bun.spawn;
197
+ }): Promise<CiAdmissionLedgerState> {
198
+ const { record } = reserveAdmissionAttempt({
199
+ existing: input.existing,
200
+ prNumber: input.prNumber,
201
+ headSha: input.headSha,
202
+ policyHash: input.policyHash,
203
+ workflowRunId: process.env.GITHUB_RUN_ID ?? null,
204
+ decisionReason: input.decisionReason,
205
+ priorScore: input.priorScore ?? null,
206
+ blockingCount: input.blockingCount ?? null,
207
+ advisoryCount: input.advisoryCount ?? null,
208
+ reservationTtlSeconds: input.policy.reservationTtlSeconds,
209
+ forced: input.forced,
210
+ });
211
+ const checkRunId = await upsertAdmissionCheckRun(
212
+ input.operatorRoot,
213
+ {
214
+ headSha: input.headSha,
215
+ record,
216
+ },
217
+ { spawnFn: input.spawnFn },
218
+ );
219
+ return {
220
+ record,
221
+ checkRunId,
222
+ headSha: input.headSha,
223
+ operatorRoot: input.operatorRoot,
224
+ };
225
+ }
226
+
227
+ export async function recordCiAdmissionGateSkip(input: {
228
+ operatorRoot: string;
229
+ prNumber: number;
230
+ headSha: string;
231
+ policy: CiReviewPolicy;
232
+ policyHash: string;
233
+ existing: readonly AdmissionRecord[];
234
+ reason: string;
235
+ priorScore: number | null;
236
+ blockingCount: number | null;
237
+ advisoryCount: number | null;
238
+ // A skip that spent nothing and must not count against ci_max_attempts
239
+ // (a /pr-hero stop): settled as "gate-skipped", like a size or budget skip.
240
+ unspent?: boolean;
241
+ }): Promise<void> {
242
+ try {
243
+ const state = await reserveCiAdmissionLedger({
244
+ operatorRoot: input.operatorRoot,
245
+ prNumber: input.prNumber,
246
+ headSha: input.headSha,
247
+ policy: input.policy,
248
+ policyHash: input.policyHash,
249
+ existing: input.existing,
250
+ decisionReason: input.reason,
251
+ priorScore: input.priorScore,
252
+ blockingCount: input.blockingCount,
253
+ advisoryCount: input.advisoryCount,
254
+ });
255
+ await settleCiAdmissionLedger(
256
+ state,
257
+ input.unspent === true ? "gate-skipped" : "skipped",
258
+ input.reason,
259
+ );
260
+ } catch {
261
+ // The skip notice is the operator-facing outcome; a check-run write must
262
+ // not block publishing it.
263
+ }
264
+ }
265
+
266
+ // S4 carry-forward (the owner's decision). A head an admission gate skips inherits the verdict of the
267
+ // last reviewed commit of this PR, so the required check reads what that review decided, never a green
268
+ // the review did not earn. The source is the PR's own commit statuses, never comment content: the walk
269
+ // (findCarriedVerdict) reads this PR's commits newest-first from the head, and takes the first commit
270
+ // whose status list carries a review's verdict (isReviewVerdictStatus). A skip, a fail-closed, a budget
271
+ // or a manual-only failure is not a verdict, so the walk passes over it.
272
+ //
273
+ // WHY the commit statuses and not the summary marker: a marker is a comment, and any commenter can post
274
+ // one naming a green head. Only a write-access actor can write a commit status, so a verdict read from
275
+ // the statuses is one a review wrote. The summary's head is never read for the carry.
276
+ // WHY the walk: a multi-commit push statuses only its tip, so the commits before it may carry no status.
277
+ // The walk skips those and stops at the first commit with a verdict, within CARRY_WALK_CAP commits.
278
+ // WHY a carried verdict may be carried again: a carried status on an earlier skipped head is a verdict a
279
+ // gate wrote from a real review, so chaining it keeps the verdict honest.
280
+ //
281
+ // WHY an override is not carried: an override is a human's decision for the code at that head only.
282
+ // The skipped head was never reviewed, so an override carried onto it would turn green with no review.
283
+ // WHY fail closed: no verdict within the cap, a failed read, a head missing from the PR's commits (a
284
+ // force-push, or a list cut short by GitHub's cap), or no reviewed head writes failure, so a trivial push
285
+ // cannot pass the gate without a verdict behind it.
286
+ // WHY an exhausted budget and a manual-only policy carry too (budget-exhausted-carry S2, the owner's
287
+ // decision of 2026-10-30, replacing the fixed failure S4 first wrote): every review rule is respected the
288
+ // same way. The once-per-pr, threshold and stop skips already carried a green over an unreviewed push, so a
289
+ // fixed failure here only turned the agent's last fix-up push red and made a human override routine.
290
+ // Same-head writes nothing, because that head's own status already exists.
291
+ // WHY answered findings may turn a carried blocking red green (S3): with no review left, the fixes cannot
292
+ // be verified. A write-access `applied` reply, or a dismissal the CI adjudicator upheld, on every blocking
293
+ // finding of the reviewed head is the most the gate can know, and the green it writes says so
294
+ // (unverifiedFixesDescription), so it never reads as a green a review earned.
295
+ export type AdmissionStatusReason =
296
+ | "same-head"
297
+ | "once-per-pr"
298
+ | "below-threshold"
299
+ | "low-risk-delta"
300
+ | "stopped"
301
+ | "max-attempts-exhausted"
302
+ | "manual-only-policy";
303
+
304
+ export interface AdmissionStatusInput {
305
+ reason: AdmissionStatusReason;
306
+ // The head the summary names as reviewed; null when no summary names one, and a null here fails the
307
+ // carry closed with no read. The carry never reads this head's verdict: it comes from the PR's own
308
+ // commit statuses (findCarriedVerdict).
309
+ reviewedHead: string | null;
310
+ // The admission's own blocking-tier count for the reviewed head. It stands in only when the carried
311
+ // failure's description does not name a count. Every text isReviewVerdictStatus admits names one, so this
312
+ // is unreachable through the walk today; it stays because ci-admission-gate.ts still supplies it.
313
+ priorBlocking: number;
314
+ // Reads the reviewed head's answered blocking findings (pr/answered-findings.ts). Called only when the
315
+ // carried verdict is a blocking red, so every other skip makes no extra API call. Absent means never read.
316
+ // `verdictAt` is when the carried verdict was written (its status's created_at), or null when unknown.
317
+ readAnswered?: (verdictAt: string | null) => Promise<AnsweredFindings | null>;
318
+ }
319
+
320
+ export interface AdmissionStatusDecision {
321
+ state: "success" | "failure";
322
+ description: string;
323
+ }
324
+
325
+ // The verdict a carried skip inherits: the commit it was found on, and that commit's status list.
326
+ export interface CarriedVerdict {
327
+ sha: string;
328
+ statuses: readonly CommitStatusFact[];
329
+ // The PR's commits older than `sha`, newest first, within the walk's cap: where a chained carry's review
330
+ // verdict is looked up (reviewVerdictTime). Absent means none to look at.
331
+ older?: readonly string[];
332
+ }
333
+
334
+ type CarriedReason = Exclude<AdmissionStatusReason, "same-head">;
335
+
336
+ // Every rule that skips a review carries the last verdict the same way (budget-exhausted-carry S2): the
337
+ // rule is respected, so no review runs, and the head reads what the last review decided. Same-head is the
338
+ // one exception: that head's own status already exists.
339
+ function isCarriedReason(
340
+ reason: AdmissionStatusReason,
341
+ ): reason is CarriedReason {
342
+ return reason !== "same-head";
343
+ }
344
+
345
+ // The readers below rewrite a legacy `pr-hero` lead into `crysk` first (canonicalStatusText), so the
346
+ // patterns and the builders speak one spelling.
347
+ const BLOCKING_COUNT = /^crysk: (\d+) blocking finding\(s\)/;
348
+
349
+ function blockingCountIn(
350
+ description: string | null | undefined,
351
+ ): number | null {
352
+ const match = BLOCKING_COUNT.exec(canonicalStatusText(description ?? ""));
353
+ if (match === null) return null;
354
+ const count = Number(match[1]);
355
+ return count > 0 ? count : null;
356
+ }
357
+
358
+ const CARRIED_FROM = "carried from ";
359
+ // Reads the carried sha out of a carried text. It only proposes the sha: the builders below must then
360
+ // reproduce the whole text, so a prefix or a suffix alone never qualifies.
361
+ const CARRIED_SHA = new RegExp(`${CARRIED_FROM}([0-9a-f]{7})`);
362
+
363
+ // The text a skip writes when it inherits a finished review's success, for the review's label and the
364
+ // carried-from sha. The carry writes it, and isReviewVerdictStatus rebuilds it, so the two cannot drift.
365
+ export function carriedSuccessDescription(label: string, sha: string): string {
366
+ return clipStatusDescription(
367
+ `${STATUS_CONTEXT}: no review needed (${label}); ${CARRIED_FROM}${sha.slice(0, 7)}`,
368
+ );
369
+ }
370
+
371
+ // The text a skip writes when it inherits a finished review's blocking failure, with that review's count.
372
+ export function carriedBlockingDescription(count: number, sha: string): string {
373
+ return clipStatusDescription(
374
+ `${STATUS_CONTEXT}: ${count} blocking finding(s) ${CARRIED_FROM}${sha.slice(0, 7)} — fix and push, or /pr-hero override`,
375
+ );
376
+ }
377
+
378
+ // The text a skip writes when a carried blocking red has every blocking finding answered and no review is
379
+ // left to verify the fixes (S3, S6). It names the rule that skipped, so a reader sees why nothing verified it.
380
+ // WHY "answered finding(s)" and not "blocking finding(s)": BLOCKING_COUNT reads that prefix as a red count.
381
+ export function unverifiedFixesDescription(
382
+ count: number,
383
+ label: string,
384
+ sha: string,
385
+ ): string {
386
+ return clipStatusDescription(
387
+ `${STATUS_CONTEXT}: ${count} answered finding(s), fixes unverified (${label}); ${CARRIED_FROM}${sha.slice(0, 7)}`,
388
+ );
389
+ }
390
+
391
+ const ANSWERED_COUNT = /^crysk: (\d+) answered finding\(s\), fixes unverified/;
392
+
393
+ function answeredCountIn(description: string): number | null {
394
+ const match = ANSWERED_COUNT.exec(canonicalStatusText(description));
395
+ if (match === null) return null;
396
+ const count = Number(match[1]);
397
+ return count > 0 ? count : null;
398
+ }
399
+
400
+ // The text a skip writes when it inherits a finished review's partial verdict (some hunters failed).
401
+ export function carriedPartialDescription(
402
+ failed: number,
403
+ total: number,
404
+ sha: string,
405
+ set?: string,
406
+ ): string {
407
+ const suffix = set === undefined ? "" : `, set ${set}`;
408
+ return clipStatusDescription(
409
+ `${STATUS_CONTEXT}: review partial (${failed} of ${total} hunters failed${suffix}) ${CARRIED_FROM}${sha.slice(0, 7)} — /pr-hero review retries it`,
410
+ );
411
+ }
412
+
413
+ const CARRY_REASONS: readonly CarriedReason[] = [
414
+ "once-per-pr",
415
+ "below-threshold",
416
+ "low-risk-delta",
417
+ "stopped",
418
+ "max-attempts-exhausted",
419
+ "manual-only-policy",
420
+ ];
421
+
422
+ function finishedSuccessMatches(rawDescription: string): boolean {
423
+ const description = canonicalStatusText(rawDescription);
424
+ return [true, false].some(
425
+ (posted) =>
426
+ commitStatusRequest({
427
+ phase: "success",
428
+ posted,
429
+ targetUrl: undefined,
430
+ context: COMMIT_STATUS_CONTEXT,
431
+ }).description === description,
432
+ );
433
+ }
434
+
435
+ function finishedBlockingMatches(rawDescription: string): boolean {
436
+ const description = canonicalStatusText(rawDescription);
437
+ const count = blockingCountIn(description);
438
+ return (
439
+ count !== null &&
440
+ blockingCommitStatusRequest({
441
+ blockingCount: count,
442
+ targetUrl: undefined,
443
+ context: COMMIT_STATUS_CONTEXT,
444
+ }).description === description
445
+ );
446
+ }
447
+
448
+ function carriedSha(description: string): string | null {
449
+ return CARRIED_SHA.exec(description)?.[1] ?? null;
450
+ }
451
+
452
+ function carriedSuccessMatches(rawDescription: string): boolean {
453
+ const description = canonicalStatusText(rawDescription);
454
+ const sha = carriedSha(description);
455
+ return (
456
+ sha !== null &&
457
+ CARRY_REASONS.some(
458
+ (reason) =>
459
+ carriedSuccessDescription(ciReviewSkipLabel(reason), sha) ===
460
+ description,
461
+ )
462
+ );
463
+ }
464
+
465
+ function unverifiedFixesMatches(rawDescription: string): boolean {
466
+ const description = canonicalStatusText(rawDescription);
467
+ const sha = carriedSha(description);
468
+ const count = answeredCountIn(description);
469
+ return (
470
+ sha !== null &&
471
+ count !== null &&
472
+ CARRY_REASONS.some(
473
+ (reason) =>
474
+ unverifiedFixesDescription(count, ciReviewSkipLabel(reason), sha) ===
475
+ description,
476
+ )
477
+ );
478
+ }
479
+
480
+ function carriedBlockingMatches(rawDescription: string): boolean {
481
+ const description = canonicalStatusText(rawDescription);
482
+ const sha = carriedSha(description);
483
+ const count = blockingCountIn(description);
484
+ return (
485
+ sha !== null &&
486
+ count !== null &&
487
+ carriedBlockingDescription(count, sha) === description
488
+ );
489
+ }
490
+
491
+ // S5: a partial review is a red verdict with its own text (N of M hunters failed). Its counts are read
492
+ // first, then the builder must reproduce the whole text, the same rule as the blocking verdict.
493
+ // W3-PARTIAL S2: the repeat form ('again') reads the same counts; the flag only picks the builder that must rebuild the text.
494
+ // W4-R363 S1: the failed-set key (", set abc123") is read when present; a text from before the key has none.
495
+ const PARTIAL_COUNTS =
496
+ /^crysk: review partial( again)? \((\d+) of (\d+) hunters failed(?:, set ([0-9a-f]{6}))?\)/;
497
+
498
+ export function partialCountsIn(
499
+ description: string | null | undefined,
500
+ ): { failed: number; total: number; again: boolean; set?: string } | null {
501
+ const match = PARTIAL_COUNTS.exec(canonicalStatusText(description ?? ""));
502
+ if (match === null) return null;
503
+ return {
504
+ failed: Number(match[2]),
505
+ total: Number(match[3]),
506
+ again: match[1] !== undefined,
507
+ ...(match[4] === undefined ? {} : { set: match[4] }),
508
+ };
509
+ }
510
+
511
+ // Exported for the teardown's repeat check (teardown.ts previousPartialIsSame): the one rule for a finished
512
+ // partial verdict, so a carried row never counts as a review's own verdict.
513
+ export function finishedPartialMatches(rawDescription: string): boolean {
514
+ const description = canonicalStatusText(rawDescription);
515
+ const counts = partialCountsIn(description);
516
+ if (counts === null) return false;
517
+ const rebuilt = counts.again
518
+ ? partialReviewAgainDescription(counts.failed, counts.total, counts.set)
519
+ : partialReviewDescription(counts.failed, counts.total, counts.set);
520
+ return rebuilt === description;
521
+ }
522
+
523
+ function carriedPartialMatches(rawDescription: string): boolean {
524
+ const description = canonicalStatusText(rawDescription);
525
+ const sha = carriedSha(description);
526
+ const counts = partialCountsIn(description);
527
+ return (
528
+ sha !== null &&
529
+ counts !== null &&
530
+ carriedPartialDescription(counts.failed, counts.total, sha, counts.set) ===
531
+ description
532
+ );
533
+ }
534
+
535
+ // WHY the walk takes only these: a skip, a fail-closed, a budget or a manual-only failure is written with
536
+ // no review behind it. Counting it as a verdict would stop the walk on it, so a green review on an older
537
+ // commit would be lost, and one skip would turn the gate red until a human acts. Overrides need no check of
538
+ // their own: an override's text is none of the texts below.
539
+ // WHY each text is rebuilt rather than matched by a pattern: the writer of a verdict is the only authority
540
+ // on its exact text. The variable parts (a count, a carried sha) are read first, then the same builder must
541
+ // reproduce the whole description.
542
+ // WHY no context check here: the walk reads only the gate's own context (newestCarriedVerdict).
543
+ export function isReviewVerdictStatus(
544
+ status: Pick<CommitStatusFact, "state" | "description">,
545
+ ): boolean {
546
+ const description = status.description;
547
+ if (typeof description !== "string") return false;
548
+ if (status.state === "success") {
549
+ return (
550
+ finishedSuccessMatches(description) ||
551
+ carriedSuccessMatches(description) ||
552
+ unverifiedFixesMatches(description)
553
+ );
554
+ }
555
+ if (status.state === "failure") {
556
+ return (
557
+ finishedBlockingMatches(description) ||
558
+ carriedBlockingMatches(description) ||
559
+ finishedPartialMatches(description) ||
560
+ carriedPartialMatches(description)
561
+ );
562
+ }
563
+ return false;
564
+ }
565
+
566
+ // The newest verdict on the head: a review's verdict of the gate's own context (isReviewVerdictStatus),
567
+ // newest by created_at, the rule every other reader of this context uses (newestStatusInContext).
568
+ function newestCarriedVerdict(statuses: readonly CommitStatusFact[]) {
569
+ return newestStatusInContext(
570
+ statuses.filter((status) => isReviewVerdictStatus(status)),
571
+ COMMIT_STATUS_CONTEXT,
572
+ );
573
+ }
574
+
575
+ function failClosed(label: string): AdmissionStatusDecision {
576
+ return {
577
+ state: "failure",
578
+ description: clipStatusDescription(
579
+ `${STATUS_CONTEXT} skipped the review (${label}) and found no earlier verdict — /pr-hero review reviews it`,
580
+ ),
581
+ };
582
+ }
583
+
584
+ // What the gate's skip writes on the new head, or null for no write. `carried` is the verdict the skip
585
+ // inherits (findCarriedVerdict), or null when none was read or found. A reason that never carries reads none.
586
+ export function admissionSkipDecision(
587
+ input: AdmissionStatusInput & {
588
+ carried: CarriedVerdict | null;
589
+ // The blocking findings of the reviewed head and how many are still open (answeredBlockingFindings),
590
+ // read only when the carried verdict is a blocking red. Null when unread or failed closed.
591
+ answered?: AnsweredFindings | null;
592
+ },
593
+ ): AdmissionStatusDecision | null {
594
+ if (input.reason === "same-head") return null;
595
+ const label = ciReviewSkipLabel(input.reason);
596
+ if (input.carried === null) return failClosed(label);
597
+ const verdict = newestCarriedVerdict(input.carried.statuses);
598
+ if (verdict === undefined) return failClosed(label);
599
+ if (verdict.state === "success") {
600
+ // A carried unverified green stays unverified: chaining it never turns it into a green a review earned.
601
+ const answeredCount = answeredCountIn(verdict.description ?? "");
602
+ return {
603
+ state: "success",
604
+ description:
605
+ answeredCount === null
606
+ ? carriedSuccessDescription(label, input.carried.sha)
607
+ : unverifiedFixesDescription(answeredCount, label, input.carried.sha),
608
+ };
609
+ }
610
+ // S5: a partial verdict is red, and it is never read as a blocking count (it has none). Taking the
611
+ // admission's own priorBlocking here would turn a partial review into a count it never had.
612
+ const partial = partialCountsIn(verdict.description);
613
+ if (partial !== null) {
614
+ return {
615
+ state: "failure",
616
+ description: carriedPartialDescription(
617
+ partial.failed,
618
+ partial.total,
619
+ input.carried.sha,
620
+ partial.set,
621
+ ),
622
+ };
623
+ }
624
+ const blocking =
625
+ blockingCountIn(verdict.description) ??
626
+ (input.priorBlocking > 0 ? input.priorBlocking : null);
627
+ if (blocking === null) return failClosed(label);
628
+ // S3, S5: every blocking finding answered unlocks the red, and the read must see at least as many
629
+ // blocking findings as the red counts; fewer means some live where this read cannot see them.
630
+ const answered = input.answered ?? null;
631
+ if (
632
+ answered !== null &&
633
+ answered.open === 0 &&
634
+ answered.blocking > 0 &&
635
+ answered.blocking >= blocking
636
+ ) {
637
+ return {
638
+ state: "success",
639
+ description: unverifiedFixesDescription(
640
+ answered.blocking,
641
+ label,
642
+ input.carried.sha,
643
+ ),
644
+ };
645
+ }
646
+ return {
647
+ state: "failure",
648
+ description: carriedBlockingDescription(blocking, input.carried.sha),
649
+ };
650
+ }
651
+
652
+ // The carried verdict's blocking count when it is a blocking red (not a partial), else null. The gate reads
653
+ // the answered findings only then, so a carried green or a partial red makes no extra API call.
654
+ export function carriedBlockingCount(
655
+ carried: CarriedVerdict | null,
656
+ ): number | null {
657
+ if (carried === null) return null;
658
+ const verdict = newestCarriedVerdict(carried.statuses);
659
+ if (verdict === undefined || verdict.state !== "failure") return null;
660
+ if (partialCountsIn(verdict.description) !== null) return null;
661
+ return blockingCountIn(verdict.description);
662
+ }
663
+
664
+ // The most earlier commits the carry reads for a verdict. A push on top of a longer run of commits with
665
+ // no verdict fails closed rather than walking the whole PR.
666
+ const CARRY_WALK_CAP = 20;
667
+
668
+ // The carry's verdict source: the newest earlier commit of this PR whose status list carries a verdict,
669
+ // or null. GitHub lists the commits oldest first; the walk takes the commits before the head, newest first.
670
+ // WHY the head's index, not the list's last element: the walk starts from the head this gate evaluates, so
671
+ // a head that moved on, or one missing from the list, cannot send the walk to the wrong commits. A head
672
+ // missing from the list fails closed.
673
+ // WHY a failed read ends the walk: a commit whose statuses did not read is not a commit with no verdict,
674
+ // so skipping it would carry an older verdict across a read that never happened.
675
+ async function findCarriedVerdict(input: {
676
+ operatorRoot: string;
677
+ prNumber: number;
678
+ headSha: string;
679
+ spawnFn?: typeof Bun.spawn;
680
+ listCommits: typeof fetchPrCommitShas;
681
+ readStatuses: typeof fetchCommitStatusList;
682
+ }): Promise<CarriedVerdict | null> {
683
+ const shas = await input.listCommits(input.operatorRoot, input.prNumber, {
684
+ spawnFn: input.spawnFn,
685
+ });
686
+ if (shas === null) return null;
687
+ const headIndex = shas.indexOf(input.headSha);
688
+ if (headIndex < 0) return null;
689
+ const earlier = shas.slice(0, headIndex).reverse().slice(0, CARRY_WALK_CAP);
690
+ for (const sha of earlier) {
691
+ const statuses = await input.readStatuses(input.operatorRoot, sha, {
692
+ spawnFn: input.spawnFn,
693
+ });
694
+ if (statuses === null) return null;
695
+ if (newestCarriedVerdict(statuses) !== undefined) {
696
+ return { sha, statuses, older: earlier.slice(earlier.indexOf(sha) + 1) };
697
+ }
698
+ }
699
+ return null;
700
+ }
701
+
702
+ // WHY the head's override holds: a human's `/pr-hero override` on this head is the decision for it. A
703
+ // re-run or reopen of the gate on that unchanged head would otherwise write the skip's verdict over it.
704
+ // So where the newest pr-hero status on the head is an override, the skip writes nothing. This holds when
705
+ // the head's statuses can be read.
706
+ // WHY the read is strict: the reader is asked with failClosed, so a failed read throws instead of looking
707
+ // like a head with no rows (fetchCommitStatuses, src/pr/pr.ts).
708
+ // WHY a failed read still writes the status: on a failed read we cannot tell whether an override stands, so
709
+ // the skip's status is written as planned. That is a tradeoff, not a guarantee: this write can replace an
710
+ // override on the head that we could not read. Leaving a fresh head with no status is the original bug, a
711
+ // head that reads as nothing decided, so we take the rarer overwrite and log a warning that says so.
712
+ async function overrideStandsOnHead(input: {
713
+ operatorRoot: string;
714
+ headSha: string;
715
+ spawnFn?: typeof Bun.spawn;
716
+ readHeadStatus: typeof fetchCommitStatuses;
717
+ }): Promise<boolean> {
718
+ let statuses: readonly CommitStatusFact[];
719
+ try {
720
+ statuses = await input.readHeadStatus(input.operatorRoot, input.headSha, {
721
+ spawnFn: input.spawnFn,
722
+ failClosed: true,
723
+ });
724
+ } catch {
725
+ log(
726
+ formatWorkflowCommand(
727
+ "warning",
728
+ `crysk: could not read the statuses of ${input.headSha.slice(0, 7)}, so an override on it cannot be checked; the skip's status is written as planned`,
729
+ ),
730
+ );
731
+ return false;
732
+ }
733
+ const newest = newestStatusInContext(statuses, COMMIT_STATUS_CONTEXT);
734
+ return newest !== undefined && isOverrideStatus(newest);
735
+ }
736
+
737
+ // When the review behind the carried verdict wrote its own verdict, or null when none reads: the stale-reply
738
+ // cutoff (answered-findings.ts isStaleReply). WHY the review's own verdict, not the carried one: a chained
739
+ // skip carries a status a skip wrote later, and a reply made between the review and that skip answers the
740
+ // review; cutting at the skip's time would drop it. The walk goes on down the PR's own commits from the
741
+ // carried one, the carry's source (never the summary's head, which a comment can name), and stops at the
742
+ // first commit with a review's own verdict. A failed read, or none within the cap, is null: fail closed.
743
+ async function reviewVerdictTime(input: {
744
+ operatorRoot: string;
745
+ carried: CarriedVerdict | null;
746
+ spawnFn?: typeof Bun.spawn;
747
+ readStatuses: typeof fetchCommitStatusList;
748
+ }): Promise<string | null> {
749
+ if (input.carried === null) return null;
750
+ const ownIn = (statuses: readonly CommitStatusFact[]) =>
751
+ newestStatusInContext(
752
+ statuses.filter((status) => finishedVerdict(status)),
753
+ COMMIT_STATUS_CONTEXT,
754
+ );
755
+ const first = ownIn(input.carried.statuses);
756
+ if (first !== undefined) return first.created_at ?? null;
757
+ for (const sha of input.carried.older ?? []) {
758
+ const statuses = await input.readStatuses(input.operatorRoot, sha, {
759
+ spawnFn: input.spawnFn,
760
+ });
761
+ if (statuses === null) return null;
762
+ const own = ownIn(statuses);
763
+ if (own !== undefined) return own.created_at ?? null;
764
+ }
765
+ return null;
766
+ }
767
+
768
+ // A verdict a review wrote itself: never a carried, skipped, or override text.
769
+ function finishedVerdict(
770
+ status: Pick<CommitStatusFact, "state" | "description">,
771
+ ): boolean {
772
+ const description = status.description;
773
+ if (typeof description !== "string") return false;
774
+ if (status.state === "success") return finishedSuccessMatches(description);
775
+ if (status.state === "failure") {
776
+ return (
777
+ finishedBlockingMatches(description) ||
778
+ finishedPartialMatches(description)
779
+ );
780
+ }
781
+ return false;
782
+ }
783
+
784
+ // The status a gate-mode skip writes, or null for none. A size or budget skip is a fixed failure.
785
+ // An admission skip or manual-required is decided by admissionSkipDecision; the carry's walk runs only
786
+ // when the verdict carries forward, so same-head and manual-required make no read.
787
+ async function gateSkipDecision(
788
+ input: {
789
+ operatorRoot: string;
790
+ prNumber: number;
791
+ headSha: string;
792
+ spawnFn?: typeof Bun.spawn;
793
+ admission?: AdmissionStatusInput;
794
+ readStatuses?: typeof fetchCommitStatusList;
795
+ listCommits?: typeof fetchPrCommitShas;
796
+ },
797
+ skip: CliRecord["skip"],
798
+ ): Promise<AdmissionStatusDecision | null> {
799
+ if (skip === "size" || skip === "budget") {
800
+ const request = skipCommitStatusRequest({
801
+ kind: skip,
802
+ targetUrl: undefined,
803
+ context: COMMIT_STATUS_CONTEXT,
804
+ });
805
+ // skipCommitStatusRequest only ever builds a failure; the literal narrows its type.
806
+ return { state: "failure", description: request.description };
807
+ }
808
+ if (input.admission === undefined) return null;
809
+ const { reason, reviewedHead } = input.admission;
810
+ // WHY the summary's presence still gates the walk: a skip whose summary names no reviewed head fails
811
+ // closed with no read, as it always has. The carried head is never taken from the summary.
812
+ const carried =
813
+ isCarriedReason(reason) && reviewedHead !== null
814
+ ? await findCarriedVerdict({
815
+ operatorRoot: input.operatorRoot,
816
+ prNumber: input.prNumber,
817
+ headSha: input.headSha,
818
+ spawnFn: input.spawnFn,
819
+ listCommits: input.listCommits ?? fetchPrCommitShas,
820
+ readStatuses: input.readStatuses ?? fetchCommitStatusList,
821
+ })
822
+ : null;
823
+ // S3: a carried blocking red asks whether every blocking finding was answered. A read that throws fails
824
+ // closed: the red stays.
825
+ let answered: AnsweredFindings | null = null;
826
+ if (
827
+ carriedBlockingCount(carried) !== null &&
828
+ input.admission.readAnswered !== undefined
829
+ ) {
830
+ try {
831
+ answered = await input.admission.readAnswered(
832
+ await reviewVerdictTime({
833
+ operatorRoot: input.operatorRoot,
834
+ carried,
835
+ spawnFn: input.spawnFn,
836
+ readStatuses: input.readStatuses ?? fetchCommitStatusList,
837
+ }),
838
+ );
839
+ } catch {
840
+ answered = null;
841
+ }
842
+ }
843
+ return admissionSkipDecision({ ...input.admission, carried, answered });
844
+ }
845
+
846
+ // The skip kind a plan stands for, read from the status its outputs carry. The
847
+ // status is a plain string in CiOutputs, so an unknown one yields no kind and no
848
+ // record: a skip the publisher cannot name is not a skip it may report.
849
+ function cliSkipKindOf(plan: CiGateSkipPlan): CliRecord["skip"] {
850
+ switch (plan.outputs.status) {
851
+ case "skipped-size":
852
+ return "size";
853
+ case "skipped-budget":
854
+ return "budget";
855
+ case "skipped-coverage":
856
+ return "coverage";
857
+ case "manual-required":
858
+ return "manual-required";
859
+ default:
860
+ return undefined;
861
+ }
862
+ }
863
+
864
+ export async function publishCiSkip(input: {
865
+ operatorRoot: string;
866
+ prNumber: number;
867
+ post: boolean;
868
+ isCi: boolean;
869
+ stepSummaryFlag: boolean | undefined;
870
+ plan: CiGateSkipPlan;
871
+ noticeMessage: string;
872
+ // S4. In gate mode with a known head, a size or budget skip posts a failure
873
+ // status. Absent means no status, which is every caller but the two gates.
874
+ ciMode?: CiMode;
875
+ headSha?: string;
876
+ // The gate's admission skip or manual-required verdict (S4 carry-forward, gate mode only).
877
+ // Absent means no status: advisory, a non-CI run, and every caller but the gate's two admission skips.
878
+ admission?: AdmissionStatusInput;
879
+ // The run's spawnFn, threaded to the status read, the status write and the repo lookup.
880
+ spawnFn?: typeof Bun.spawn;
881
+ // Test-only seams (defaults: the real repostMarkedPrComment, publishFinalCommitStatus,
882
+ // fetchCommitStatusList for each commit's statuses, fetchPrCommitShas for the PR's commits, and
883
+ // fetchCommitStatuses for the head's override check).
884
+ repost?: typeof repostMarkedPrComment;
885
+ postStatus?: typeof publishFinalCommitStatus;
886
+ repoWebUrl?: typeof ghRepoWebUrl;
887
+ readStatuses?: typeof fetchCommitStatusList;
888
+ listCommits?: typeof fetchPrCommitShas;
889
+ readHeadStatus?: typeof fetchCommitStatuses;
890
+ }): Promise<number> {
891
+ log(formatWorkflowCommand("notice", input.noticeMessage));
892
+ // The record names the skip kind only. The plan carries no head, so none is
893
+ // written: the publisher takes the head from the trigger's record.
894
+ const skip = cliSkipKindOf(input.plan);
895
+ if (input.post) {
896
+ // Repost, never edit in place: an edited notice is invisible on GitHub,
897
+ // so a later push that was skipped again looked like nothing happened.
898
+ // See repostMarkedPrComment's WHY. A repost that throws is the notice's own
899
+ // failure, so its record names the step, and the error is rethrown unchanged.
900
+ try {
901
+ await (input.repost ?? repostMarkedPrComment)({
902
+ operatorRoot: input.operatorRoot,
903
+ pr: input.prNumber,
904
+ body: input.plan.comment,
905
+ markerPrefix: input.plan.markerPrefix,
906
+ });
907
+ } catch (error) {
908
+ writeCliRecord({
909
+ v: 1,
910
+ outcome: "error",
911
+ cls: classifyCliError(error),
912
+ params: { step: "posting the skip notice" },
913
+ });
914
+ throw error;
915
+ }
916
+ }
917
+ // S4: the head's status is part of "this skip reached the PR", so it is
918
+ // written before the record. A failed write rethrows, leaving no skipped
919
+ // record behind. Gate mode only: a size or budget skip is a fixed failure, and
920
+ // an admission skip or manual-required writes the verdict admissionSkipDecision
921
+ // reaches (the carry-forward above).
922
+ const decision =
923
+ input.ciMode === "gate" && input.headSha !== undefined
924
+ ? await gateSkipDecision({ ...input, headSha: input.headSha }, skip)
925
+ : null;
926
+ // WHY the override is read before the write: a re-run or reopen of the gate on an overridden head would
927
+ // otherwise write this skip's verdict over the human's decision. The notice, record and outputs still
928
+ // write; only the status is held back, and one line says why.
929
+ const headOverridden =
930
+ decision !== null && input.headSha !== undefined
931
+ ? await overrideStandsOnHead({
932
+ operatorRoot: input.operatorRoot,
933
+ headSha: input.headSha,
934
+ spawnFn: input.spawnFn,
935
+ readHeadStatus: input.readHeadStatus ?? fetchCommitStatuses,
936
+ })
937
+ : false;
938
+ if (headOverridden && input.headSha !== undefined) {
939
+ log(
940
+ `crysk: the override on ${input.headSha.slice(0, 7)} stands; no status is written over it`,
941
+ );
942
+ }
943
+ if (decision !== null && input.headSha !== undefined && !headOverridden) {
944
+ // The run's pull URL, like every other status the CLI writes (T3 advisory
945
+ // 3): a skip is a red check, and the link is how a reader reaches the PR.
946
+ // Best effort: ghRepoWebUrl answers undefined when it cannot, and the status
947
+ // still lands, without a link.
948
+ const targetUrl = prHtmlUrl(
949
+ await (
950
+ input.repoWebUrl ??
951
+ ((root: string) => ghRepoWebUrl(root, { spawnFn: input.spawnFn }))
952
+ )(input.operatorRoot),
953
+ input.prNumber,
954
+ );
955
+ // Gate-only, and gate implies `--ci` (resolveCiPosture), so this is the gate's
956
+ // own context: the one skip write that names pr-hero.
957
+ await (input.postStatus ?? publishFinalCommitStatus)(
958
+ input.operatorRoot,
959
+ input.headSha,
960
+ {
961
+ state: decision.state,
962
+ description: decision.description,
963
+ context: COMMIT_STATUS_CONTEXT,
964
+ targetUrl,
965
+ },
966
+ input.spawnFn,
967
+ );
968
+ }
969
+ // Written only once the notice is on the PR, or once the log line is out when
970
+ // posting is off: the record is what the publisher reads as "this skip was
971
+ // reported", so it must not come before the repost it claims.
972
+ if (skip !== undefined) {
973
+ writeCliRecord({ v: 1, outcome: "skipped", skip });
974
+ }
975
+ const summaryPath = process.env.GITHUB_STEP_SUMMARY;
976
+ if (shouldWriteStepSummary(input.isCi, input.stepSummaryFlag, summaryPath)) {
977
+ await appendStepSummary(summaryPath as string, input.plan.summaryMarkdown);
978
+ }
979
+ const outputPath = process.env.GITHUB_OUTPUT;
980
+ if (shouldWriteCiOutputs(input.isCi, outputPath)) {
981
+ await appendCiOutputs(outputPath as string, input.plan.outputs);
982
+ }
983
+ return 0;
984
+ }