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,665 @@
1
+ // PR mode's CI admission gate (ROADMAP Pillar 3): decides, before any git
2
+ // fetch or worktree is touched, whether a CI-triggered review of an
3
+ // already-reviewed head should run, skip, or fall back to a human decision.
4
+ // Relocated out of reviewPr() (src/pr/review-pr.ts): identifiers renamed to
5
+ // explicit parameters (`target.headSha` -> `headSha`, etc.), control flow
6
+ // unchanged. The WHY comments below explain decisions made while this code
7
+ // still lived inline, and they move with it.
8
+ //
9
+ // A no-op on --dry-run (a dry run creates nothing, including ledger writes)
10
+ // and on --force (an explicit override answers the same question this gate
11
+ // asks). Both guards are read straight off the caller's own CliOptions.
12
+ //
13
+ // yieldToInFlightReview (below) is the later, second stand-down point: a
14
+ // review already in flight on the same head. It lives here rather than
15
+ // inline in reviewPr() so its ledger settlement is reachable from a test.
16
+
17
+ import {
18
+ type AdmissionRecord,
19
+ selectActiveReservation,
20
+ } from "#ci/admission-ledger";
21
+ import { writeCliRecord } from "#ci/cli-record";
22
+ import {
23
+ type AdmissionContext,
24
+ planCiReviewManualRequired,
25
+ planCiReviewSkip,
26
+ } from "#ci/gates";
27
+ import { formatWorkflowCommand } from "#ci/reporter";
28
+ import {
29
+ type CiReviewPolicy,
30
+ ciReviewManualRequiredDetail,
31
+ ciReviewPolicyHash,
32
+ ciReviewSkipDetail,
33
+ countableWorkflowHeads,
34
+ deltaTouchesPriorFindings,
35
+ evaluateCiReviewAdmission,
36
+ formatCiAdmissionObserveNotice,
37
+ parseCiAdmissionBlock,
38
+ pathsFromPostedFindingMarkers,
39
+ resolveCiAdmissionAttemptCount,
40
+ resolveCiReviewPolicy,
41
+ resolveCiTrustedActors,
42
+ scanPostedFindingTiers,
43
+ stateReviewCount,
44
+ stopCommandsNewestFirst,
45
+ validateAdmissionAuthority,
46
+ } from "#ci/review-admission";
47
+ import {
48
+ classifyChangedPaths,
49
+ type DeltaRiskAssessment,
50
+ } from "#ci/review-risk";
51
+ import {
52
+ type CiAdmissionLedgerState,
53
+ publishCiSkip,
54
+ recordCiAdmissionGateSkip,
55
+ reserveCiAdmissionLedger,
56
+ settleCiAdmissionLedger,
57
+ settleCiGateSkip,
58
+ } from "#pr/admission";
59
+ import {
60
+ CommentsTruncatedError,
61
+ fetchCommitStatuses,
62
+ fetchPrComments,
63
+ fetchPrReviewComments,
64
+ ghCollaboratorPermission,
65
+ ghCompareChangedFilesWithStatus,
66
+ ghPrHeroWorkflowRunHeads,
67
+ listAdmissionCheckRuns,
68
+ } from "#pr/pr";
69
+ import {
70
+ type CiMode,
71
+ type CommitStatusContext,
72
+ findMarkedCommentId,
73
+ IN_FLIGHT_TTL_MS,
74
+ inFlightContextsFor,
75
+ isInFlightCommitStatus,
76
+ } from "#pr/preflight";
77
+ import { parseStateBlock } from "#rereview/state";
78
+ import type { CliOptions, LocalConfig } from "#review/preflight";
79
+ import { log } from "#ui/primitives";
80
+ import {
81
+ markerCommentSeen,
82
+ parsePrCommentMarker,
83
+ summaryMarkerFields,
84
+ } from "#watch/preflight";
85
+ import { CliError } from "../errors";
86
+
87
+ export interface CiAdmissionGateResult {
88
+ ciPolicy: CiReviewPolicy;
89
+ ciPolicyHash: string;
90
+ ledgerRecords: AdmissionRecord[];
91
+ // Defined only when the gate decided the run must stop here — the caller
92
+ // returns this value immediately, exactly as reviewPr() used to `return`
93
+ // inline from inside this block.
94
+ exitCode: number | undefined;
95
+ }
96
+
97
+ export async function evaluateCiAdmissionGate(input: {
98
+ operatorRoot: string;
99
+ prNumber: number;
100
+ headSha: string;
101
+ config: LocalConfig;
102
+ isCi: boolean;
103
+ // The run's one resolved CI mode (resolveCiMode, reviewPr): the footer of the
104
+ // admission skip's summary follows it.
105
+ ciMode: CiMode;
106
+ options: CliOptions;
107
+ // Test-only seams (defaults: the real Bun.spawn / recordCiAdmissionGateSkip).
108
+ // Every gh() caller below already threads an invisible-to-production
109
+ // `spawnFn` (see pr/pr.ts's own WHY); this gate had no way to reach any of
110
+ // them because it never exposed the option itself. `recordSkip` covers
111
+ // recordCiAdmissionGateSkip specifically because it (via
112
+ // reserveCiAdmissionLedger -> upsertAdmissionCheckRun) has no spawnFn
113
+ // threading of its own and admission.ts is out of scope for this slice.
114
+ // publishCiSkip is deliberately NOT seamed here: with `options.post`
115
+ // unset it never calls gh at all, only the two env-path file writers.
116
+ spawnFn?: typeof Bun.spawn;
117
+ recordSkip?: typeof recordCiAdmissionGateSkip;
118
+ // Test-only: the wait before a stop's permission lookup is retried.
119
+ sleepFn?: (ms: number) => Promise<void>;
120
+ }): Promise<CiAdmissionGateResult> {
121
+ const { operatorRoot, prNumber, headSha, config, isCi, options } = input;
122
+ const spawnFn = input.spawnFn;
123
+ const recordSkip = input.recordSkip ?? recordCiAdmissionGateSkip;
124
+ const ciPolicy = resolveCiReviewPolicy(config);
125
+ const ciPolicyHash = ciReviewPolicyHash(ciPolicy);
126
+ let ledgerRecords: AdmissionRecord[] = [];
127
+
128
+ if (!options.dryRun && isCi) {
129
+ ledgerRecords = await listAdmissionCheckRuns(operatorRoot, headSha, {
130
+ spawnFn,
131
+ });
132
+ }
133
+
134
+ if (!options.dryRun && !options.force && isCi) {
135
+ let issueComments: Awaited<ReturnType<typeof fetchPrComments>>;
136
+ let reviewComments: Awaited<ReturnType<typeof fetchPrReviewComments>>;
137
+ let authorityFailOpen = false;
138
+ try {
139
+ [issueComments, reviewComments] = await Promise.all([
140
+ fetchPrComments(operatorRoot, prNumber, { spawnFn }),
141
+ fetchPrReviewComments(operatorRoot, prNumber, { spawnFn }),
142
+ ]);
143
+ } catch (error) {
144
+ if (error instanceof CommentsTruncatedError) {
145
+ authorityFailOpen = true;
146
+ issueComments = [];
147
+ reviewComments = [];
148
+ } else {
149
+ throw error;
150
+ }
151
+ }
152
+ const existingSummaryId = findMarkedCommentId(issueComments);
153
+ const summaryBody =
154
+ existingSummaryId === null
155
+ ? null
156
+ : (issueComments.find((c) => c.id === existingSummaryId)?.body ?? null);
157
+ const summaryMarker =
158
+ summaryBody === null ? null : parsePrCommentMarker(summaryBody);
159
+ const { summaryHead, summaryComplete } = summaryMarkerFields(summaryMarker);
160
+ const state = summaryBody === null ? null : parseStateBlock(summaryBody);
161
+ const parsedAdmission =
162
+ summaryBody === null ? null : parseCiAdmissionBlock(summaryBody);
163
+ const authority = validateAdmissionAuthority({
164
+ summaryHead,
165
+ reportMarkerHead: summaryHead,
166
+ state,
167
+ admission: parsedAdmission,
168
+ });
169
+ if (!authority.ok) {
170
+ authorityFailOpen = true;
171
+ }
172
+ const trustedActors = resolveCiTrustedActors({
173
+ githubActor: process.env.GITHUB_ACTOR,
174
+ extra: config.ci_trusted_actors,
175
+ });
176
+ const allComments = [...reviewComments, ...issueComments];
177
+ const postedFindings =
178
+ summaryHead === null
179
+ ? null
180
+ : scanPostedFindingTiers({
181
+ summaryHead,
182
+ comments: allComments,
183
+ trustedActors,
184
+ });
185
+ const markerSeen = markerCommentSeen(issueComments);
186
+ const stateCount = stateReviewCount(state, markerSeen, parsedAdmission);
187
+ const headBranch = process.env.GITHUB_HEAD_REF;
188
+ const workflowHeads =
189
+ headBranch === undefined || headBranch.length === 0
190
+ ? new Set<string>()
191
+ : await ghPrHeroWorkflowRunHeads(operatorRoot, headBranch, {
192
+ spawnFn,
193
+ });
194
+ // #326: a run concluded `success` even when the gate skipped it (a skip
195
+ // exits 0), so the run list alone over-counts. Each workflow head's ledger
196
+ // rows say whether it spent. One read per distinct head: `gh run list`
197
+ // returns at most 20 runs by default, so that is at most 20 reads per gate
198
+ // evaluation. Each read fails open to [], which keeps that head counted (the
199
+ // pre-fix behavior), so a failed read can only over-count, never under-count.
200
+ // Each read asks for the head's full attempt history (`includeHistory`): the
201
+ // default returns only the newest row, which would hide a spent attempt
202
+ // behind a later skip.
203
+ //
204
+ // WHY every head reads history, the current head included: the current head
205
+ // can be a workflow head too (a prior concluded run on this same head), and
206
+ // its newest row alone can be a gate-skip that hides an earlier spent
207
+ // attempt. Reusing ledgerRecords (latest-only) here would drop that head and
208
+ // admit an extra paid review past ci_max_attempts. ledgerRecords itself stays
209
+ // latest-only because its other readers (the active-reservation check and
210
+ // countTerminalAttempts) want current state; changing them is a separate
211
+ // decision.
212
+ const ledgerByHead = new Map<string, readonly AdmissionRecord[]>();
213
+ await Promise.all(
214
+ [...workflowHeads].map(async (head) => {
215
+ ledgerByHead.set(
216
+ head,
217
+ await listAdmissionCheckRuns(operatorRoot, head, {
218
+ spawnFn,
219
+ includeHistory: true,
220
+ }),
221
+ );
222
+ }),
223
+ );
224
+ const countedHeads = countableWorkflowHeads(workflowHeads, ledgerByHead);
225
+ const reviewCount = resolveCiAdmissionAttemptCount({
226
+ stateCount,
227
+ workflowHeads: countedHeads,
228
+ ledgerRecords,
229
+ });
230
+ let deltaTouchesPriorFindingsFlag = false;
231
+ let deltaRisk: DeltaRiskAssessment | null = null;
232
+ if (summaryHead !== null && summaryHead !== headSha) {
233
+ const compareFiles = await ghCompareChangedFilesWithStatus(
234
+ operatorRoot,
235
+ summaryHead,
236
+ headSha,
237
+ { spawnFn },
238
+ );
239
+ const changedPaths = compareFiles.map((entry) => entry.path);
240
+ deltaRisk = classifyChangedPaths(
241
+ changedPaths,
242
+ compareFiles.map((entry) => ({
243
+ path: entry.path,
244
+ status: entry.status,
245
+ })),
246
+ );
247
+ const priorPaths = pathsFromPostedFindingMarkers(
248
+ allComments,
249
+ summaryHead,
250
+ trustedActors,
251
+ );
252
+ if (priorPaths.length > 0) {
253
+ deltaTouchesPriorFindingsFlag = deltaTouchesPriorFindings(
254
+ changedPaths,
255
+ priorPaths,
256
+ );
257
+ }
258
+ }
259
+ const stopped = await stoppedByMaintainer(
260
+ operatorRoot,
261
+ issueComments,
262
+ spawnFn,
263
+ input.sleepFn ?? Bun.sleep,
264
+ );
265
+ const admissionVerdict = evaluateCiReviewAdmission({
266
+ currentHead: headSha,
267
+ summaryHead,
268
+ summaryComplete,
269
+ markerSeen,
270
+ reviewCount,
271
+ state,
272
+ admission: parsedAdmission,
273
+ postedFindings,
274
+ policy: ciPolicy,
275
+ deltaTouchesPriorFindings: deltaTouchesPriorFindingsFlag,
276
+ deltaRisk,
277
+ authorityFailOpen,
278
+ stopped,
279
+ });
280
+ const admissionContext: AdmissionContext = {
281
+ currentHead: headSha,
282
+ reviewedHead: summaryHead,
283
+ policyMode: ciPolicy.mode,
284
+ policyHash: ciPolicyHash,
285
+ deltaRisk,
286
+ };
287
+ // WHY a stop skips even in observe-only mode: observe-only is a rollout
288
+ // setting for automatic decisions, and a stop is a maintainer's explicit one.
289
+ const observeOnly =
290
+ config.ci_admission_observe_only === true &&
291
+ !(
292
+ admissionVerdict.action === "skip" &&
293
+ admissionVerdict.reason === "stopped"
294
+ );
295
+ if (
296
+ observeOnly &&
297
+ (admissionVerdict.action === "skip" ||
298
+ admissionVerdict.action === "manual-required")
299
+ ) {
300
+ log(
301
+ formatWorkflowCommand(
302
+ "notice",
303
+ formatCiAdmissionObserveNotice({
304
+ verdict: admissionVerdict,
305
+ currentHead: headSha,
306
+ reviewedHead: summaryHead,
307
+ policyMode: ciPolicy.mode,
308
+ policyHash: ciPolicyHash,
309
+ deltaRisk,
310
+ }),
311
+ ),
312
+ );
313
+ }
314
+ if (!observeOnly && admissionVerdict.action === "skip") {
315
+ const skipReason = ciReviewSkipDetail(admissionVerdict);
316
+ await recordSkip({
317
+ operatorRoot,
318
+ prNumber,
319
+ headSha,
320
+ policy: ciPolicy,
321
+ policyHash: ciPolicyHash,
322
+ existing: ledgerRecords,
323
+ reason: skipReason,
324
+ priorScore: admissionVerdict.prior.score,
325
+ blockingCount: admissionVerdict.prior.blocking,
326
+ advisoryCount: admissionVerdict.prior.advisory,
327
+ // WHY unspent: a stop is lifted by the next maintainer review command, and
328
+ // stopped pushes counted as attempts would leave that PR with no budget.
329
+ unspent: admissionVerdict.reason === "stopped",
330
+ });
331
+ // S4: in gate mode the head inherits the verdict of the PR's own last reviewed commit, read from
332
+ // that commit's statuses (publishCiSkip, admissionSkipDecision): a skipped head never reads as one
333
+ // nobody decided about.
334
+ const plan = planCiReviewSkip({
335
+ prNumber,
336
+ verdict: admissionVerdict,
337
+ admission: admissionContext,
338
+ ciMode: input.ciMode,
339
+ });
340
+ const exitCode = await publishCiSkip({
341
+ operatorRoot,
342
+ prNumber,
343
+ post: options.post === true,
344
+ isCi,
345
+ stepSummaryFlag: options.stepSummary,
346
+ plan,
347
+ noticeMessage: `crysk review skipped — ${skipReason}`,
348
+ ciMode: input.ciMode,
349
+ headSha,
350
+ spawnFn,
351
+ admission: {
352
+ reason: admissionVerdict.reason,
353
+ reviewedHead: summaryHead,
354
+ priorBlocking: admissionVerdict.prior.blocking,
355
+ },
356
+ });
357
+ return { ciPolicy, ciPolicyHash, ledgerRecords, exitCode };
358
+ }
359
+ if (!observeOnly && admissionVerdict.action === "manual-required") {
360
+ const manualReason = ciReviewManualRequiredDetail(admissionVerdict);
361
+ await recordSkip({
362
+ operatorRoot,
363
+ prNumber,
364
+ headSha,
365
+ policy: ciPolicy,
366
+ policyHash: ciPolicyHash,
367
+ existing: ledgerRecords,
368
+ reason: manualReason,
369
+ priorScore: admissionVerdict.prior.score,
370
+ blockingCount: admissionVerdict.prior.blocking,
371
+ advisoryCount: admissionVerdict.prior.advisory,
372
+ });
373
+ // S4: manual-required is a failure in gate mode: its code was never reviewed.
374
+ const plan = planCiReviewManualRequired({
375
+ prNumber,
376
+ verdict: admissionVerdict,
377
+ admission: admissionContext,
378
+ ciMode: input.ciMode,
379
+ });
380
+ const exitCode = await publishCiSkip({
381
+ operatorRoot,
382
+ prNumber,
383
+ post: options.post === true,
384
+ isCi,
385
+ stepSummaryFlag: options.stepSummary,
386
+ plan,
387
+ noticeMessage: `crysk review requires manual override — ${manualReason}`,
388
+ ciMode: input.ciMode,
389
+ headSha,
390
+ spawnFn,
391
+ admission: {
392
+ reason: admissionVerdict.reason,
393
+ reviewedHead: summaryHead,
394
+ priorBlocking: admissionVerdict.prior.blocking,
395
+ },
396
+ });
397
+ return { ciPolicy, ciPolicyHash, ledgerRecords, exitCode };
398
+ }
399
+ }
400
+ return { ciPolicy, ciPolicyHash, ledgerRecords, exitCode: undefined };
401
+ }
402
+
403
+ // Cross-machine TOCTOU: the watcher already skipped fresh pendings at
404
+ // gather, but a CLI and a watcher can still overlap between that fetch
405
+ // and this process posting its own pending. --yes (the watcher child)
406
+ // aborts before createPrRunDir so it consumes no poison-PR attempt.
407
+ // Interactive continues: a stuck pending must not trap the operator
408
+ // behind the 90-minute TTL.
409
+ //
410
+ // Relocated out of reviewPr() (src/pr/review-pr.ts) with its log lines
411
+ // byte-identical. One addition: a CI run reaches this check AFTER reviewPr
412
+ // reserved its admission ledger row, so a stand-down must settle that row
413
+ // as `"yielded"` before returning. Left `"reserved"`, it reached teardown's
414
+ // safety net, which settles it `"failed"` (musive #1935, run 37018094654: a
415
+ // red pr-hero/ci-admission check and a spent attempt for a run that reviewed
416
+ // nothing, while the local review it yielded to posted fine). Outside CI the
417
+ // ledger is null and the settle is a no-op, so the watcher child behaves as
418
+ // before. The check stays where it is, after the reservation, on purpose:
419
+ // moving it earlier would change the CI path's ordering for every other exit.
420
+ //
421
+ // Which pendings stand the run down depends on its posture. A watcher child or a
422
+ // local run (no --ci) reads every run context, because local runs and the watcher
423
+ // post their pending on pr-hero/local and would otherwise double-spend on the
424
+ // same head. A --ci run reads only the gate: it settles pr-hero alone, and a stand-
425
+ // down on a local pending would leave pr-hero unwritten, since no local run writes
426
+ // that context. action.yml runs CI as `review --ci --yes`, so the yield is live
427
+ // there, and this is why the --ci narrowing matters.
428
+ //
429
+ // Returns the exit code when the run must stop here, `undefined` to proceed.
430
+ // `spawnFn` and `nowMs` are test-only seams (defaults: the real Bun.spawn and
431
+ // Date.now()). The one spawnFn reaches both gh calls made here: the
432
+ // commit-status read and the check-run upsert inside settleCiAdmissionLedger.
433
+ export async function yieldToInFlightReview(input: {
434
+ operatorRoot: string;
435
+ headSha: string;
436
+ options: Pick<CliOptions, "yes" | "force">;
437
+ // The run's posture (resolveCiPosture): decides which pending contexts stand it down.
438
+ statusContext: CommitStatusContext;
439
+ ciAdmissionLedger: CiAdmissionLedgerState | null;
440
+ spawnFn?: typeof Bun.spawn;
441
+ nowMs?: number;
442
+ }): Promise<number | undefined> {
443
+ const { operatorRoot, headSha, options, ciAdmissionLedger, spawnFn } = input;
444
+ const statuses = await fetchCommitStatuses(operatorRoot, headSha, {
445
+ spawnFn,
446
+ });
447
+ if (
448
+ !isInFlightCommitStatus(
449
+ statuses,
450
+ input.nowMs ?? Date.now(),
451
+ IN_FLIGHT_TTL_MS,
452
+ inFlightContextsFor(input.statusContext),
453
+ )
454
+ ) {
455
+ return undefined;
456
+ }
457
+ // `--yes` without `--force` is the watcher child: a second launch
458
+ // would double-spend. `--force` is the CI comment override, and the
459
+ // workflow's concurrency group cancels the run already holding this
460
+ // pending status. Treating that leftover pending as a skip would
461
+ // cancel the review the comment just asked for and then refuse to
462
+ // start the replacement.
463
+ if (options.yes && !options.force) {
464
+ log("skip: a crysk review is already in-flight on this head");
465
+ await settleCiAdmissionLedger(
466
+ ciAdmissionLedger,
467
+ "yielded",
468
+ "another crysk review is already in flight on this head",
469
+ { spawnFn },
470
+ );
471
+ writeCliRecord({ v: 1, outcome: "yielded" });
472
+ return 0;
473
+ }
474
+ log(
475
+ "warning: a crysk review is already in-flight on this head; " +
476
+ "continuing",
477
+ );
478
+ return undefined;
479
+ }
480
+
481
+ // A configuration error that stops a CI run before it reviews anything: the
482
+ // gotchas file (review/run.ts validateGotchas) or the prompt set (review/
483
+ // preflight.ts). Both throw a CliError with a classified `cls`, and only those.
484
+ // WHY the class and not the message: a wording change must not move an error
485
+ // in or out of the budget rule.
486
+ export function isCiConfigError(error: unknown): boolean {
487
+ if (!(error instanceof CliError) || error.cls === undefined) return false;
488
+ return error.cls.kind === "gotchas" || error.cls.kind === "prompt-set";
489
+ }
490
+
491
+ // WHY this writes a row: the attempt count reads each head's ledger rows, and a
492
+ // head with no row counts as a spent attempt (its run is in the workflow-run
493
+ // list). A run that stops on a configuration error before it reviews spent
494
+ // nothing, so it writes the same `gate-skipped` row the size and budget gates
495
+ // write (#326). The caller rethrows the ORIGINAL error after this returns, so
496
+ // the error, the exit code and the outcome code are unchanged.
497
+ // WHY every step is swallowed: the row is bookkeeping for a run that is already
498
+ // failing. A gh or check-run failure here must not replace the configuration
499
+ // error the operator needs to see. A head that cannot be recorded simply keeps
500
+ // counting, which is the behavior before this function existed.
501
+ // WHY an active reservation is left alone: settling it would finish another
502
+ // run's reservation on the same head as if it were ours.
503
+ export const CONFIG_SKIP_RECORD_TIMEOUT_MS = 15_000;
504
+
505
+ export async function recordCiConfigErrorSkip(input: {
506
+ operatorRoot: string;
507
+ prNumber: number;
508
+ config: LocalConfig;
509
+ resolveHeadSha: () => Promise<string>;
510
+ reason: string;
511
+ spawnFn?: typeof Bun.spawn;
512
+ // Test-only seam: the bound on the READS before the reservation.
513
+ timeoutMs?: number;
514
+ }): Promise<void> {
515
+ // WHY the deadline covers only the reads: the head lookup and the ledger list
516
+ // have no bound of their own, and the caller rethrows the configuration error
517
+ // right after this returns. Once a reservation exists, though, it must be
518
+ // settled, or it stays `reserved` and counts as a spent attempt forever. So the
519
+ // deadline ends before the reserve, and the settle always runs. Its gh calls
520
+ // are already bounded by the check-run upsert (ADMISSION_CHECK_RUN_TIMEOUT_MS,
521
+ // two attempts), and a failed settle is swallowed by tryPersistCiAdmissionLedger.
522
+ const reads = await readBeforeReservation(input);
523
+ if (reads === null) return;
524
+ try {
525
+ const active = selectActiveReservation(
526
+ reads.existing,
527
+ reads.headSha,
528
+ reads.ciPolicyHash,
529
+ reads.ciPolicy.reservationTtlSeconds,
530
+ new Date(),
531
+ );
532
+ if (active !== null) return;
533
+ // If the reserve fails there is no row, so there is nothing to settle.
534
+ const state = await reserveCiAdmissionLedger({
535
+ operatorRoot: input.operatorRoot,
536
+ prNumber: input.prNumber,
537
+ headSha: reads.headSha,
538
+ policy: reads.ciPolicy,
539
+ policyHash: reads.ciPolicyHash,
540
+ existing: reads.existing,
541
+ decisionReason: input.reason,
542
+ spawnFn: input.spawnFn,
543
+ });
544
+ await settleCiGateSkip(state, input.reason, { spawnFn: input.spawnFn });
545
+ } catch {
546
+ // Swallowed on purpose: see the WHY above.
547
+ }
548
+ }
549
+
550
+ // The reads before the reservation, under one deadline. Returns null when the
551
+ // deadline wins or a read fails: nothing was reserved, so there is nothing to
552
+ // settle, and the caller rethrows the original error.
553
+ async function readBeforeReservation(input: {
554
+ operatorRoot: string;
555
+ config: LocalConfig;
556
+ resolveHeadSha: () => Promise<string>;
557
+ spawnFn?: typeof Bun.spawn;
558
+ timeoutMs?: number;
559
+ }): Promise<{
560
+ headSha: string;
561
+ ciPolicy: CiReviewPolicy;
562
+ ciPolicyHash: string;
563
+ existing: AdmissionRecord[];
564
+ } | null> {
565
+ let timer: ReturnType<typeof setTimeout> | undefined;
566
+ const deadline = new Promise<"timeout">((resolve) => {
567
+ timer = setTimeout(
568
+ () => resolve("timeout"),
569
+ input.timeoutMs ?? CONFIG_SKIP_RECORD_TIMEOUT_MS,
570
+ );
571
+ });
572
+ const work = (async () => {
573
+ const headSha = await input.resolveHeadSha();
574
+ const ciPolicy = resolveCiReviewPolicy(input.config);
575
+ const ciPolicyHash = ciReviewPolicyHash(ciPolicy);
576
+ const existing = await listAdmissionCheckRuns(input.operatorRoot, headSha, {
577
+ spawnFn: input.spawnFn,
578
+ });
579
+ return { headSha, ciPolicy, ciPolicyHash, existing };
580
+ })();
581
+ try {
582
+ const outcome = await Promise.race([work, deadline]);
583
+ if (outcome === "timeout") {
584
+ log(
585
+ "config-error ledger row not recorded: GitHub did not answer in time",
586
+ );
587
+ return null;
588
+ }
589
+ return outcome;
590
+ } catch {
591
+ return null;
592
+ } finally {
593
+ clearTimeout(timer);
594
+ }
595
+ }
596
+
597
+ // Whether a write-access maintainer's `/crysk stop` is in force: the
598
+ // newest stop, review or recheck command from a write or admin author decides.
599
+ // Commands from anyone else are passed over, so a stranger can neither set a
600
+ // stop nor lift one. Fails open: an author whose permission cannot be read
601
+ // counts as a maintainer for a lift and as nobody for a stop, so either way
602
+ // the review runs. A wrong skip loses a review someone wanted; a wrong run
603
+ // only costs one.
604
+ async function stoppedByMaintainer(
605
+ operatorRoot: string,
606
+ issueComments: readonly { user: string; body: string }[],
607
+ spawnFn: typeof Bun.spawn | undefined,
608
+ sleepFn: (ms: number) => Promise<void>,
609
+ ): Promise<boolean> {
610
+ const commands = stopCommandsNewestFirst(issueComments);
611
+ // Nothing older than the oldest stop can change the answer: with no stop
612
+ // left below it, the walk ends "not stopped" anyway. So a PR without a stop
613
+ // looks up nobody, however many review commands it has.
614
+ const oldestStop = commands.map((c) => c.kind).lastIndexOf("stop");
615
+ const permissions = new Map<string, string | null>();
616
+ for (const command of commands.slice(0, oldestStop + 1)) {
617
+ let permission = permissions.get(command.user);
618
+ if (!permissions.has(command.user)) {
619
+ permission = await stopAuthorPermission(
620
+ operatorRoot,
621
+ command.user,
622
+ spawnFn,
623
+ sleepFn,
624
+ );
625
+ permissions.set(command.user, permission ?? null);
626
+ }
627
+ if (permission === null || permission === undefined) {
628
+ if (command.kind === "lift") return false;
629
+ log(
630
+ formatWorkflowCommand(
631
+ "warning",
632
+ `Could not read the permission of ${command.user}, who posted a stop command, so the stop does not count and the review runs.`,
633
+ ),
634
+ );
635
+ continue;
636
+ }
637
+ if (permission === "admin" || permission === "write") {
638
+ return command.kind === "stop";
639
+ }
640
+ }
641
+ return false;
642
+ }
643
+
644
+ // Same bounds as the trigger's commenter lookup (lookupCommenterPermission):
645
+ // one retry after a short wait, so a single API blip does not override a
646
+ // maintainer's stop, and a timeout, so a hung gh call cannot stall admission.
647
+ const STOP_PERMISSION_RETRY_DELAY_MS = 2_000;
648
+ const STOP_PERMISSION_TIMEOUT_MS = 30_000;
649
+
650
+ async function stopAuthorPermission(
651
+ operatorRoot: string,
652
+ login: string,
653
+ spawnFn: typeof Bun.spawn | undefined,
654
+ sleepFn: (ms: number) => Promise<void>,
655
+ ): Promise<string | null> {
656
+ const ask = () =>
657
+ ghCollaboratorPermission(operatorRoot, login, {
658
+ spawnFn,
659
+ timeoutMs: STOP_PERMISSION_TIMEOUT_MS,
660
+ });
661
+ const first = await ask();
662
+ if (first !== null) return first;
663
+ await sleepFn(STOP_PERMISSION_RETRY_DELAY_MS);
664
+ return ask();
665
+ }