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,927 @@
1
+ // PR mode (ROADMAP B1): one command from a PR number to a reviewed range, a
2
+ // detached worktree, and a pipeline run. Moved out of
3
+ // src/cli.ts (cli-decomp Phase 2, odd/tasks/cli-decomposition.md) as a
4
+ // byte-for-byte relocation — no behaviour change.
5
+ //
6
+ // Two roots run through everything below, and confusing them is the failure
7
+ // this design exists to prevent:
8
+ // - the OPERATOR root: --repo's toplevel. cwd for gh and for .prhero/
9
+ // config+gotchas. Config is NEVER read from the worktree — the operator
10
+ // checkout is the trust anchor, and a reviewed PR's tree must not
11
+ // influence engine config. Dirtiness here is irrelevant.
12
+ // - the GIT-DIR OWNER: the clone registered for this origin under
13
+ // ~/.prhero/repos/<id>/registry.json. Fetch, worktree add/prune/remove
14
+ // and the object-db git (rev-parse, diff) run against it, because
15
+ // `git worktree add` is bound to one git dir (W3 / #24).
16
+ // - the REVIEW root: the worktree, detached at the PR's head, living
17
+ // under ~/.prhero/repos/<id>/worktrees/pr-<n>. The pipeline's cwd, the
18
+ // tree the codegraph checks run against, and a root the run dir must
19
+ // stay outside of.
20
+
21
+ import path from "node:path";
22
+ import {
23
+ cliHeadField,
24
+ hunterFailureRecords,
25
+ writeCliRecord,
26
+ } from "#ci/cli-record";
27
+ import { planCiSizeSkip } from "#ci/gates";
28
+ import { withCiWorkflowGroup } from "#ci/reporter";
29
+ import { RECHECK_COMMAND, REVIEW_COMMAND } from "#ci/trigger";
30
+ import { pipelineConfigInput } from "#config/config";
31
+ import {
32
+ exclusionLines,
33
+ git,
34
+ gitCommitExists,
35
+ gitIsAncestor,
36
+ gitNameOnly,
37
+ gitNameStatus,
38
+ } from "#git/git";
39
+ import { engineIdentity } from "#git/identity";
40
+ import {
41
+ type CiAdmissionLedgerState,
42
+ holdCiAdmissionLedger,
43
+ publishCiSkip,
44
+ reserveCiAdmissionLedger,
45
+ settleCiAdmissionLedger,
46
+ settleCiGateSkip,
47
+ } from "#pr/admission";
48
+ import {
49
+ evaluateCiAdmissionGate,
50
+ isCiConfigError,
51
+ recordCiConfigErrorSkip,
52
+ yieldToInFlightReview,
53
+ } from "#pr/ci-admission-gate";
54
+ import { discoveryHunters, resolvePrDiscovery } from "#pr/discovery";
55
+ import type { InlinePostOutcome } from "#pr/inline";
56
+ import { resolvePrPlanAndConfirm } from "#pr/plan";
57
+ import {
58
+ fetchPostedFindingComments,
59
+ fetchPrComments,
60
+ fetchPrReviewComments,
61
+ ghPrFiles,
62
+ ghPrView,
63
+ postReviewCommentReply,
64
+ } from "#pr/pr";
65
+ import {
66
+ createPrRunDir,
67
+ resolveCiPosture,
68
+ resolvePrTarget,
69
+ } from "#pr/preflight";
70
+ import { publishRunOutcome } from "#pr/publish-outcome";
71
+ import { resolveEagerLocalIgnore, resolvePrFetchAndRange } from "#pr/range";
72
+ import {
73
+ renderPrDryRunPlan,
74
+ resolvePrDryRunNumstat,
75
+ resolvePrPromptSetAndBudget,
76
+ resolvePrRunOptions,
77
+ resolvePrTargetRecord,
78
+ } from "#pr/target";
79
+ import { finalizePrReviewRun, settleCommitStatusAndLedger } from "#pr/teardown";
80
+ import { setupPrWorktree } from "#pr/worktree-setup";
81
+ import {
82
+ type HunterFailure,
83
+ type PipelineResult,
84
+ runPipeline,
85
+ } from "#review/pipeline";
86
+ import {
87
+ type CliOptions,
88
+ resolveMaxConcurrentSteps,
89
+ resolveSharedPrefix,
90
+ } from "#review/preflight";
91
+ import { estimateCost } from "#review/report";
92
+ import {
93
+ pipelineConsolidateInput,
94
+ pipelineScoutInput,
95
+ pipelineSummarizerInput,
96
+ } from "#review/route-preflight";
97
+ import {
98
+ prepareRunnerForRoute,
99
+ resolveParityFires,
100
+ validateGotchas,
101
+ } from "#review/run";
102
+ import { sizeGateConfigFor, sizeGateLine } from "#review/size-gate";
103
+ import { registerActiveRun, unregisterActiveRun } from "#store/activity";
104
+ import {
105
+ type AdjudicationOutcome,
106
+ adjudicationMarker,
107
+ CI_ADJUDICATOR_LOGIN,
108
+ } from "#triage/adjudication";
109
+ import { dryRunHunterCount, reviewingLine } from "#ui/plan";
110
+ import { log, styleEnabled, terminalWidth } from "#ui/primitives";
111
+ import { applySizeGate, startProgressRenderer } from "#ui/progress";
112
+ import { parsePrFiles } from "#watch/preflight";
113
+ import { commandHint } from "../brand";
114
+ import { CliError } from "../errors";
115
+ import { acquirePidLock } from "../home";
116
+ import { worktreeLockPath } from "../home-preflight";
117
+ import { readLocalIgnoreRules } from "../ignore-read";
118
+ import type { ProductionRuntime } from "../production-runtime";
119
+
120
+ // The CLI's record for a pipeline whose every hunter failed (cli.json,
121
+ // odd/tasks/agent-first-ci.md, T2c). reviewPr writes it right after the pipeline's
122
+ // group closes, before publishRunOutcome. A completed pipeline writes NOTHING here:
123
+ // the pipeline finishing is not the review being delivered, so reviewed is written by
124
+ // publishRunOutcome at the delivery point (recordReviewDelivered). A failure while
125
+ // posting therefore never leaves reviewed behind. A pipeline that never returned
126
+ // writes nothing either: its throw reaches the fatal record instead.
127
+ export function recordPipelineOutcome(
128
+ result:
129
+ | {
130
+ readonly sessionFailed: boolean;
131
+ readonly hunterFailures?: readonly HunterFailure[];
132
+ }
133
+ | undefined,
134
+ headSha: string,
135
+ env: Readonly<Record<string, string | undefined>> = process.env,
136
+ ): void {
137
+ if (result?.sessionFailed !== true) return;
138
+ // WHY the causes ride on the record: the publisher names the provider and the model
139
+ // when every hunter failed on the provider's side (PRH-MODEL-UNAVAILABLE). A run with
140
+ // no failed hunter list keeps the record as it was before the field existed.
141
+ const failures = result.hunterFailures ?? [];
142
+ writeCliRecord(
143
+ {
144
+ v: 1,
145
+ outcome: "hunters-failed",
146
+ ...cliHeadField(headSha),
147
+ ...(failures.length === 0
148
+ ? {}
149
+ : { hunter_failures: hunterFailureRecords(failures) }),
150
+ },
151
+ env,
152
+ );
153
+ }
154
+
155
+ // T5b: one reply per adjudication, on the finding's own thread. Posted after the
156
+ // review is published. WHY a failed post only warns: no verdict changes this run's
157
+ // gate. A reply that fails or does not land leaves the dismissal with no CI ruling,
158
+ // so the next /crysk recheck rules on it again and the next review still counts
159
+ // the finding, which fails closed.
160
+ const ADJUDICATION_REPLY_TIMEOUT_MS = 30_000;
161
+
162
+ const ADJUDICATION_BADGES = {
163
+ upheld: `✅ **CI adjudication: upheld** — the dismissal stands; from the next review of this head (${commandHint(REVIEW_COMMAND)}) this finding no longer counts toward the gate.`,
164
+ rejected:
165
+ "❌ **CI adjudication: rejected** — the finding stands and still counts.",
166
+ inconclusive:
167
+ "❔ **CI adjudication: inconclusive** — the repository did not settle it; the finding still counts.",
168
+ } as const;
169
+
170
+ // The author of a posted reply, read back from GitHub. The gh helper in pr.ts is
171
+ // private to that module, so the one GET this needs runs here, with the same
172
+ // spawn shape: cwd is the operator root, so gh resolves the repo from its remote.
173
+ async function readCommentAuthor(input: {
174
+ operatorRoot: string;
175
+ commentId: number;
176
+ spawnFn?: typeof Bun.spawn;
177
+ }): Promise<string> {
178
+ const spawn = input.spawnFn ?? Bun.spawn;
179
+ const proc = spawn(
180
+ [
181
+ "gh",
182
+ "api",
183
+ `repos/{owner}/{repo}/pulls/comments/${input.commentId}`,
184
+ "--jq",
185
+ ".user.login",
186
+ ],
187
+ {
188
+ cwd: input.operatorRoot,
189
+ stdout: "pipe",
190
+ stderr: "pipe",
191
+ timeout: ADJUDICATION_REPLY_TIMEOUT_MS,
192
+ },
193
+ );
194
+ const [stdout, exitCode] = await Promise.all([
195
+ new Response(proc.stdout).text(),
196
+ proc.exited,
197
+ ]);
198
+ if (exitCode !== 0) {
199
+ throw new Error(`gh api (read comment author) exited ${exitCode}`);
200
+ }
201
+ return stdout.trim();
202
+ }
203
+
204
+ export async function postAdjudicationReplies(input: {
205
+ operatorRoot: string;
206
+ pr: number;
207
+ headSha: string;
208
+ adjudications: readonly AdjudicationOutcome[];
209
+ spawnFn?: typeof Bun.spawn;
210
+ }): Promise<void> {
211
+ for (const entry of input.adjudications) {
212
+ // No ruling exists: post nothing, so the dismissal stays pending for a later recheck.
213
+ if (entry.failed === true) {
214
+ process.stdout.write(
215
+ `::notice::crysk: the CI adjudicator could not rule on ${entry.priorId}; it stays pending for the next ${commandHint(RECHECK_COMMAND, "")}\n`,
216
+ );
217
+ continue;
218
+ }
219
+ const marker = adjudicationMarker({
220
+ verdict: entry.verdict,
221
+ reply: entry.replyId,
222
+ head: input.headSha,
223
+ });
224
+ const evidence =
225
+ entry.evidence.length > 0
226
+ ? `\n\nEvidence:\n${entry.evidence.map((e) => `- \`${e}\``).join("\n")}`
227
+ : "";
228
+ const body = `${marker}\n\n${ADJUDICATION_BADGES[entry.verdict]}${evidence}`;
229
+ let commentId: number | undefined;
230
+ try {
231
+ commentId = await postReviewCommentReply({
232
+ operatorRoot: input.operatorRoot,
233
+ pr: input.pr,
234
+ inReplyTo: entry.threadId,
235
+ body,
236
+ spawnFn: input.spawnFn,
237
+ timeoutMs: ADJUDICATION_REPLY_TIMEOUT_MS,
238
+ });
239
+ } catch (error) {
240
+ const message = error instanceof Error ? error.message : String(error);
241
+ process.stdout.write(
242
+ `::warning::crysk: could not post the CI adjudication for ${entry.priorId}: ${message}\n`,
243
+ );
244
+ }
245
+ // Only an upheld verdict can clear the finding on the next review, so only its
246
+ // landing is checked. A read that fails counts as not landed.
247
+ if (entry.verdict !== "upheld") continue;
248
+ const author =
249
+ commentId === undefined
250
+ ? undefined
251
+ : await readCommentAuthor({
252
+ operatorRoot: input.operatorRoot,
253
+ commentId,
254
+ spawnFn: input.spawnFn,
255
+ }).catch(() => undefined);
256
+ if (author !== CI_ADJUDICATOR_LOGIN) {
257
+ process.stdout.write(
258
+ `::warning::crysk: the CI adjudication for ${entry.priorId} was not recorded under ${CI_ADJUDICATOR_LOGIN}; the finding still counts toward the gate\n`,
259
+ );
260
+ }
261
+ }
262
+ }
263
+
264
+ export async function reviewPr(
265
+ options: CliOptions,
266
+ prArg: number | "current",
267
+ ): Promise<number> {
268
+ // 1-2 — the operator root, resolved config, prompt set, and PR record. See
269
+ // resolvePrRunOptions / resolvePrPromptSetAndBudget / resolvePrTargetRecord
270
+ // (src/pr/target.ts) for the full rationale, including why the gotchas
271
+ // validation call below stays inline here rather than moving into that
272
+ // module.
273
+ const step1 = await resolvePrRunOptions(options, prArg);
274
+ options = step1.options;
275
+ const { operatorRoot, prNumber, home, isCi, loaded, config, summary } = step1;
276
+ // S4 + T3 S7: the run's one posture. Every gate, skip, status, comment and
277
+ // summary below takes these values; nothing re-resolves them. Both key on the
278
+ // explicit --ci flag, never on `isCi` (which also folds in the CI/GITHUB_ACTIONS
279
+ // environment): a shell that exports CI=1 is advisory, on pr-hero/local.
280
+ const { ciMode, statusContext } = resolveCiPosture(options);
281
+ // The eager, non-CI-only `.prheroignore` read (O-8). See
282
+ // resolveEagerLocalIgnore (src/pr/range.ts) for the full rationale — under
283
+ // CI this stays `undefined` on purpose; the CI read instead needs the
284
+ // RESOLVED base sha, not known yet here (see resolvePrFetchAndRange below).
285
+ const localIgnore = await resolveEagerLocalIgnore({
286
+ isCi,
287
+ operatorRoot,
288
+ readLocal: readLocalIgnoreRules,
289
+ });
290
+ let step2: Awaited<ReturnType<typeof resolvePrPromptSetAndBudget>>;
291
+ try {
292
+ step2 = await resolvePrPromptSetAndBudget({
293
+ options,
294
+ loaded,
295
+ config,
296
+ isCi,
297
+ operatorRoot,
298
+ });
299
+ await validateGotchas(step2.gotchasPath);
300
+ } catch (error) {
301
+ // WHY a row before the rethrow: this run stops before the admission
302
+ // reservation below, so without one its head would count as a spent
303
+ // attempt (see recordCiConfigErrorSkip). Only CI writes it, the same way the
304
+ // size gate does, and never on a dry run, which writes nothing. The error
305
+ // itself is rethrown unchanged.
306
+ if (isCi && !options.dryRun && isCiConfigError(error)) {
307
+ await recordCiConfigErrorSkip({
308
+ operatorRoot,
309
+ prNumber,
310
+ config,
311
+ resolveHeadSha: async () =>
312
+ resolvePrTarget(await ghPrView(operatorRoot, prNumber)).headSha,
313
+ reason: "configuration error before the review; no provider spend",
314
+ });
315
+ }
316
+ throw error;
317
+ }
318
+ const {
319
+ ciBudgetCeiling,
320
+ ciSizeLimits,
321
+ agents,
322
+ spec,
323
+ agentFiles,
324
+ promptSet,
325
+ gotchasPath,
326
+ } = step2;
327
+ const { dir: agentsDir, source: agentsDirSource } = agents;
328
+ // CI resolves the limits from the route (resolveCiSizeLimits); a local run
329
+ // keeps the flags. An `undefined` knob falls through to the repo config,
330
+ // then the engine default, inside sizeGateConfigFor. Computed ONCE so the
331
+ // dry-run plan and the real gate cannot disagree about the same PR.
332
+ const sizeGateOverrides =
333
+ ciSizeLimits === undefined
334
+ ? options
335
+ : {
336
+ ...(ciSizeLimits.maxChangedLines === undefined
337
+ ? {}
338
+ : { maxChangedLines: ciSizeLimits.maxChangedLines }),
339
+ ...(ciSizeLimits.maxChangedFiles === undefined
340
+ ? {}
341
+ : { maxChangedFiles: ciSizeLimits.maxChangedFiles }),
342
+ };
343
+ // Local mode's dirty-tree and HEAD-match gates are both skipped here ON
344
+ // PURPOSE: the hunters read the worktree and never this checkout, and the
345
+ // worktree satisfies the HEAD gate by construction (created detached at
346
+ // the PR's own head).
347
+ const { repoHome, gitDirOwner, target, worktreePath } =
348
+ await resolvePrTargetRecord({
349
+ home,
350
+ operatorRoot,
351
+ prNumber,
352
+ dryRun: options.dryRun,
353
+ });
354
+
355
+ // The CI admission gate (ROADMAP Pillar 3): decides, before any git fetch
356
+ // or worktree is touched, whether a CI-triggered review of an
357
+ // already-reviewed head should run, skip, or fall back to a human
358
+ // decision. See evaluateCiAdmissionGate (src/pr/ci-admission-gate.ts) for
359
+ // the full rationale.
360
+ const ciAdmissionGate = await evaluateCiAdmissionGate({
361
+ operatorRoot,
362
+ prNumber,
363
+ headSha: target.headSha,
364
+ config,
365
+ isCi,
366
+ ciMode,
367
+ options,
368
+ });
369
+ if (ciAdmissionGate.exitCode !== undefined) return ciAdmissionGate.exitCode;
370
+ const { ciPolicy, ciPolicyHash, ledgerRecords } = ciAdmissionGate;
371
+ let ciAdmissionLedger: CiAdmissionLedgerState | null = null;
372
+
373
+ // 3 — the free exit, BEFORE the git fetch: a PR-mode dry run still creates
374
+ // NOTHING — no `git fetch`, no worktree, no run dir — but it does now make
375
+ // a SECOND read-only `gh` call, alongside the `ghPrView` one at step 1
376
+ // above. That call was always there; "fetches nothing" never meant "talks
377
+ // to GitHub zero times", only that nothing GIT-side happens. Overriding
378
+ // the original all-aggregate estimate (PR1b Addition 1 / #5557): the
379
+ // aggregate counters carry no per-file paths, so `.prheroignore`
380
+ // exclusions were structurally impossible to apply here, and that gap
381
+ // widens from "tens of lines" (lockfiles) to "potentially thousands" (a
382
+ // whole ignored directory) the moment a user defines their own rules — a
383
+ // dry run that says SKIP for a PR the real per-file run happily accepts
384
+ // reads as a broken tool, not a conservative estimate.
385
+ if (options.dryRun) {
386
+ const hunterCount = dryRunHunterCount(spec, config);
387
+ const estimate = estimateCost(
388
+ target.ghDiffStat,
389
+ hunterCount,
390
+ summary.enabled,
391
+ options.scout,
392
+ 0,
393
+ true,
394
+ );
395
+ const dryRunGateConfig = sizeGateConfigFor(
396
+ sizeGateOverrides,
397
+ config,
398
+ localIgnore,
399
+ );
400
+ // See resolvePrDryRunNumstat (src/pr/target.ts) for the full rationale —
401
+ // the degrade-to-aggregate-estimate rule PR1b Addition 1 / #5557 needs
402
+ // when `gh`'s per-file `files` list is truncated, unavailable, or the
403
+ // fetch itself throws (GH_PR_VIEW_TIMEOUT_MS bounds it).
404
+ const perFile = await resolvePrDryRunNumstat({
405
+ fetchFiles: async () =>
406
+ parsePrFiles(await ghPrFiles(operatorRoot, prNumber)),
407
+ totalFiles: target.ghDiffStat.files,
408
+ });
409
+ // See renderPrDryRunPlan (src/pr/target.ts) for the full rationale.
410
+ return renderPrDryRunPlan({
411
+ options,
412
+ operatorRoot,
413
+ prNumber,
414
+ target,
415
+ worktreePath,
416
+ repoHome,
417
+ agentsDir,
418
+ agentsDirSource,
419
+ agentFiles,
420
+ spec,
421
+ config,
422
+ summary,
423
+ loaded,
424
+ isCi,
425
+ hunterCount,
426
+ estimate,
427
+ dryRunGateConfig,
428
+ perFile,
429
+ });
430
+ }
431
+
432
+ if (isCi) {
433
+ try {
434
+ ciAdmissionLedger = await reserveCiAdmissionLedger({
435
+ operatorRoot,
436
+ prNumber,
437
+ headSha: target.headSha,
438
+ policy: ciPolicy,
439
+ policyHash: ciPolicyHash,
440
+ existing: ledgerRecords,
441
+ decisionReason: options.force
442
+ ? "manual override (--force)"
443
+ : "admission: run",
444
+ forced: options.force === true,
445
+ });
446
+ holdCiAdmissionLedger(ciAdmissionLedger);
447
+ } catch (error) {
448
+ throw new CliError(
449
+ `CI admission reservation failed: ${(error as Error).message}`,
450
+ );
451
+ }
452
+ }
453
+
454
+ const lockPath = worktreeLockPath(home, repoHome.repoId, prNumber);
455
+ await acquirePidLock(lockPath);
456
+ try {
457
+ // 4 — fetch, then canonicalize, then the base-ref `.prheroignore` read.
458
+ // See resolvePrFetchAndRange (src/pr/range.ts) for the full rationale —
459
+ // fetchPrRefs's refspec pair, why baseSha must be resolveCommit's output
460
+ // (never target.baseRef/baseRefName directly — a merged PR's baseRef is
461
+ // a `<sha>^1` EXPRESSION), and design D1 (CI reads the ignore file at the
462
+ // resolved base sha, never author-controlled; non-CI reuses the eager
463
+ // `localIgnore` read above rather than re-reading).
464
+ const { headSha, baseSha, diffFromSha, prIgnore, headLabel } =
465
+ await resolvePrFetchAndRange({
466
+ gitDirOwner,
467
+ prNumber,
468
+ target,
469
+ isCi,
470
+ localIgnore,
471
+ runGit: git,
472
+ });
473
+
474
+ // 5 — last-reviewed head, the two deltas (D9), Phase B classification,
475
+ // and the size gate over the discovery range. Discovery is the
476
+ // restricted L..H intersection (or full B..H); the size gate counts
477
+ // that same discovery diff, never the whole PR, so a merge of main
478
+ // cannot inflate the bill. Empty discovery is a re-review state, not
479
+ // an error (C6) — first review (case A) still fails loud. See
480
+ // resolvePrDiscovery (src/pr/discovery.ts) for the full rationale; the
481
+ // three comment fetches stay here (its own header explains why).
482
+ const [issueComments, postedFindings, reviewComments] = await Promise.all([
483
+ fetchPrComments(operatorRoot, prNumber),
484
+ fetchPostedFindingComments(operatorRoot, prNumber),
485
+ fetchPrReviewComments(operatorRoot, prNumber),
486
+ ]);
487
+ const {
488
+ prepared,
489
+ skipDiscovery,
490
+ rawDiff,
491
+ effectiveDiff,
492
+ anchorPatch,
493
+ gateConfig,
494
+ rereview,
495
+ verifyQueue,
496
+ overlapCandidates,
497
+ adjudicationQueue,
498
+ phaseB,
499
+ diffStat,
500
+ sizeGate,
501
+ } = await resolvePrDiscovery({
502
+ diffFromSha,
503
+ headSha,
504
+ full: options.full,
505
+ adjudicate: options.adjudicate === true,
506
+ baseRef: target.baseRef,
507
+ headLabel,
508
+ isCi,
509
+ sizeGateOverrides,
510
+ config,
511
+ prIgnore,
512
+ issueComments,
513
+ postedFindings,
514
+ reviewComments,
515
+ git: {
516
+ commitExists: (sha) => gitCommitExists(gitDirOwner, sha),
517
+ isAncestor: (ancestor, descendant) =>
518
+ gitIsAncestor(gitDirOwner, ancestor, descendant),
519
+ nameOnly: (from, to) => gitNameOnly(gitDirOwner, from, to),
520
+ nameStatus: (from, to) => gitNameStatus(gitDirOwner, from, to),
521
+ runGit: (args) => git(gitDirOwner, args),
522
+ },
523
+ log,
524
+ });
525
+
526
+ // 5b(CI) — the assistant-posture branch, BEFORE applySizeGate: outside
527
+ // CI, a hard skip in non-interactive mode THROWS a CliError (see
528
+ // applySizeGate below), which the top-level catch turns into exit 1 —
529
+ // exactly the "blocks CI" behavior spec 2.1 forbids. `--force` bypasses
530
+ // here too, same as the non-CI path just below, since it answers the
531
+ // same question ("is this diff too big to be worth its cost") either
532
+ // way. planCiSizeSkip (ci/gates.ts) is the ONE call: it is null unless
533
+ // isCi && the gate actually failed, so no separate isCi guard is needed
534
+ // around it beyond --force.
535
+ if (!options.force) {
536
+ const sizePlan = planCiSizeSkip({
537
+ isCi,
538
+ verdict: sizeGate,
539
+ prNumber,
540
+ maxChangedLines: gateConfig.maxChangedLines,
541
+ maxChangedFiles: gateConfig.maxChangedFiles,
542
+ ciMode,
543
+ });
544
+ if (sizePlan !== null) {
545
+ await settleCiGateSkip(
546
+ ciAdmissionLedger,
547
+ "diff exceeds the configured size gate",
548
+ );
549
+ return await publishCiSkip({
550
+ operatorRoot,
551
+ prNumber,
552
+ post: options.post === true,
553
+ isCi,
554
+ stepSummaryFlag: options.stepSummary,
555
+ plan: sizePlan,
556
+ noticeMessage:
557
+ "crysk review skipped — diff exceeds the configured size gate",
558
+ ciMode,
559
+ headSha,
560
+ });
561
+ }
562
+ }
563
+
564
+ // 5b — the size gate, on the REAL per-file numstat and placed here on
565
+ // purpose: before createPrRunDir, so a skipped PR leaves no run dir
566
+ // behind. That matters beyond tidiness — the watcher counts attempts from
567
+ // run artifacts, so a gate skip cannot consume a poison-PR attempt even
568
+ // when the watcher was the one that launched this review. Unattended
569
+ // (--yes) still skips with no prompt; an interactive TTY is asked first.
570
+ // A hard skip (and the interactive prompt) never reach the plan, so the
571
+ // verdict states itself here. --force falls through and the plan's
572
+ // decision block prints the same line plus the override note.
573
+ const sizeGateChoice = await applySizeGate(sizeGate, options, () => {
574
+ log(sizeGateLine(sizeGate));
575
+ // The shell owns BOTH impure decisions here (style flag and width), the
576
+ // same way printDryRun does — this is the one exclusion line that is
577
+ // printed outside a plan renderer, so it cannot inherit a resolved width
578
+ // from one.
579
+ for (const line of exclusionLines(
580
+ effectiveDiff.droppedPaths,
581
+ styleEnabled(),
582
+ terminalWidth(),
583
+ )) {
584
+ log(line);
585
+ }
586
+ });
587
+ if (sizeGateChoice === "abort") return 1;
588
+ const sizeGateConfirmed = !sizeGate.ok && !options.force;
589
+
590
+ // Cross-machine TOCTOU: another pr-hero review already in flight on this
591
+ // head. A stand-down settles the CI ledger as `yielded`, never leaving it
592
+ // for teardown to mark `failed`. See yieldToInFlightReview
593
+ // (src/pr/ci-admission-gate.ts) for the full rationale.
594
+ const inFlightExit = await yieldToInFlightReview({
595
+ operatorRoot,
596
+ headSha,
597
+ options,
598
+ statusContext,
599
+ ciAdmissionLedger,
600
+ });
601
+ if (inFlightExit !== undefined) return inFlightExit;
602
+
603
+ // 6 — run dir + diff artifact (PR naming; outside BOTH roots).
604
+ const runDir = await createPrRunDir(
605
+ options,
606
+ operatorRoot,
607
+ worktreePath,
608
+ repoHome.paths.runs,
609
+ prNumber,
610
+ headSha,
611
+ );
612
+ // diff.patch is the EFFECTIVE diff — exactly what the hunters read (see
613
+ // filterDiffByIgnoreRules); diff.raw.patch preserves the unfiltered
614
+ // bytes, and only when the filter actually dropped something.
615
+ const diffPath = path.join(runDir, "diff.patch");
616
+ await Bun.write(diffPath, effectiveDiff.patch);
617
+ // anchor.patch is the full PR diff inline comments anchor against (see
618
+ // resolvePrDiscovery). post --from and triage read it, falling back to
619
+ // diff.patch for run dirs written before it existed.
620
+ await Bun.write(path.join(runDir, "anchor.patch"), anchorPatch);
621
+ if (effectiveDiff.droppedPaths.length > 0) {
622
+ await Bun.write(path.join(runDir, "diff.raw.patch"), rawDiff);
623
+ }
624
+
625
+ // 7 — the plan and the paid gate, exactly like local mode but with the
626
+ // real numstat replacing GitHub's counters.
627
+ const parityFires = resolveParityFires(
628
+ effectiveDiff.patch,
629
+ config.parity_trigger_paths,
630
+ );
631
+ const activeHunters = discoveryHunters({
632
+ skipDiscovery,
633
+ agents: spec.agents,
634
+ parityFires,
635
+ });
636
+ const hunterCount = activeHunters.length;
637
+ // See resolvePrPlanAndConfirm (src/pr/plan.ts) for the full rationale —
638
+ // the CI budget gate, route/capability resolution, the plan card, the
639
+ // interactive confirm, and the "committed to spending" commit-status
640
+ // hold that follows a successful one.
641
+ const planResult = await resolvePrPlanAndConfirm({
642
+ options,
643
+ operatorRoot,
644
+ prNumber,
645
+ target,
646
+ worktreePath,
647
+ runDir,
648
+ headSha,
649
+ baseSha,
650
+ diffFromSha,
651
+ diffPath,
652
+ diffStat,
653
+ droppedPaths: effectiveDiff.droppedPaths,
654
+ sizeGate,
655
+ sizeGateConfirmed,
656
+ agentsDir,
657
+ agentsDirSource,
658
+ agentFiles,
659
+ spec,
660
+ config,
661
+ summary,
662
+ loaded,
663
+ isCi,
664
+ ciMode,
665
+ statusContext,
666
+ ciBudgetCeiling,
667
+ ciAdmissionLedger,
668
+ skipDiscovery,
669
+ hunterCount,
670
+ parityFires,
671
+ verifyQueue,
672
+ prepared,
673
+ });
674
+ if (planResult.exitCode !== undefined) return planResult.exitCode;
675
+ const {
676
+ postEnabled,
677
+ routePlan,
678
+ productionAdmission,
679
+ runnerAuthority,
680
+ maxVerificationSteps,
681
+ estimate,
682
+ statusTargetUrl,
683
+ freeRoute,
684
+ } = planResult;
685
+
686
+ let result: PipelineResult | undefined;
687
+ let posted: InlinePostOutcome | null = null;
688
+ // S4: written by publishRunOutcome's onBlockingCount sink, read by the
689
+ // commit-status finally. Null until the findings doc exists.
690
+ let blockingCount: number | null = null;
691
+ // Set by the catch below, read by the commit-status finally: a body that threw
692
+ // must keep its own error, so a failed status write there only logs.
693
+ let bodyFailed = false;
694
+ try {
695
+ // 8-10 — the review root, its own codegraph index, and the MCP
696
+ // registry the hunters read. See setupPrWorktree
697
+ // (src/pr/worktree-setup.ts) for the full rationale.
698
+ const { mcpConfigPath, indexMs } = await setupPrWorktree({
699
+ gitDirOwner,
700
+ worktreePath,
701
+ headSha,
702
+ registryPath: repoHome.paths.registry,
703
+ prNumber,
704
+ runDir,
705
+ });
706
+
707
+ // 11 — run, with live progress (same shape as local mode's leg). The
708
+ // pipeline is untouched beyond the observational tap: it gets the worktree
709
+ // as its cwd and the PR's real number for the envelope.
710
+ // Spec 2.1: "Progress updates MUST use GitHub Actions log workflow
711
+ // groups (`::group::` / `::endgroup::`) to structure runner logs
712
+ // cleanly." One group around the whole hunt+refute run is the minimum
713
+ // that satisfies it. The arm and the close both live inside
714
+ // withCiWorkflowGroup rather than at this call site, and EVERY
715
+ // statement of the setup below sits inside its body: the progress
716
+ // renderer and registerActiveRun (whose mkdirSync/writeFileSync are
717
+ // unguarded) can throw on a read-only or full runner filesystem, and
718
+ // anything armed-but-not-yet-guarded there folds the whole rest of the
719
+ // job log — the `::error::` annotation naming the cause included —
720
+ // into a group nothing ever closes.
721
+ let started = 0;
722
+ await withCiWorkflowGroup(isCi, "crysk review", log, async () => {
723
+ log(reviewingLine(hunterCount, summary, options));
724
+ // runnerAuthority resolved before confirm with the exact-binding gate.
725
+ if (runnerAuthority.error !== undefined) {
726
+ throw new CliError(
727
+ `execution authority unavailable: ${runnerAuthority.error}`,
728
+ );
729
+ }
730
+ // §5.3 D1-10b: one controller shared by the pipeline and the runner,
731
+ // exactly as in local mode — the ceiling aborts it and the harness
732
+ // reads the same signal.
733
+ const ceilingController = new AbortController();
734
+ let productionRuntime: ProductionRuntime | undefined;
735
+ started = performance.now();
736
+ const progress = startProgressRenderer(
737
+ started,
738
+ `PR #${prNumber}`,
739
+ activeHunters.map((a) => a.key),
740
+ spec.agents.some((a) => a.role === "refuter"),
741
+ summary.enabled,
742
+ );
743
+ try {
744
+ const prepared = await prepareRunnerForRoute({
745
+ routePlan,
746
+ productionAdmission,
747
+ workspaceRoot: worktreePath,
748
+ runnerAuthority,
749
+ ceilingController,
750
+ onProgress: progress.onProgress,
751
+ maxConcurrentSteps: resolveMaxConcurrentSteps(config),
752
+ });
753
+ productionRuntime = prepared.productionRuntime;
754
+ // registerActiveRun rides INSIDE this try, not before it: the
755
+ // renderer is already ticking by now, and a throw here used to
756
+ // leak its 250ms interval — which keeps the event loop alive and
757
+ // hangs process exit, the exact failure the finally below exists
758
+ // to prevent.
759
+ await registerActiveRun({
760
+ pid: process.pid,
761
+ repo: repoHome.paths.repoId ?? path.basename(gitDirOwner),
762
+ pr: prNumber,
763
+ runDir,
764
+ startedAt: new Date().toISOString(),
765
+ });
766
+ await settleCiAdmissionLedger(
767
+ ciAdmissionLedger,
768
+ "provider-started",
769
+ "pipeline starting",
770
+ );
771
+ result = await runPipeline(
772
+ {
773
+ pr: prNumber,
774
+ // Same rule as local mode: record the commit the diff was actually
775
+ // computed against, or nothing downstream can reproduce the range.
776
+ baseSha: diffFromSha,
777
+ headSha,
778
+ worktree: worktreePath,
779
+ diffPath,
780
+ excludedPaths: effectiveDiff.droppedPaths,
781
+ exclusions: effectiveDiff.exclusions,
782
+ ignoreFile: {
783
+ readFrom: isCi ? "base-ref" : "working-tree",
784
+ ...(isCi ? { ref: baseSha } : {}),
785
+ found: prIgnore.found,
786
+ },
787
+ gotchasPath,
788
+ agentsDir,
789
+ ...(agents.files ? { agentFiles: agents.files } : {}),
790
+ runDir,
791
+ outPath: path.join(runDir, "findings.json"),
792
+ mcpConfigPath,
793
+ hopBudget: options.hopBudget,
794
+ ...(options.model ? { model: options.model } : {}),
795
+ parityTriggerPaths: config.parity_trigger_paths,
796
+ suspicionPriors: config.suspicion_priors,
797
+ ...(skipDiscovery ? {} : pipelineSummarizerInput(summary)),
798
+ ...(skipDiscovery ? {} : pipelineScoutInput(options)),
799
+ ...(skipDiscovery ? {} : pipelineConsolidateInput()),
800
+ ...(resolveSharedPrefix(options) ? { sharedPrefix: true } : {}),
801
+ // NOT gated on skipDiscovery: an empty-delta re-review still
802
+ // classifies and verifies against this config, and a run whose
803
+ // artifact cannot name its config inputs is the unpoolable case
804
+ // D7 exists to prevent — whether or not hunters fanned out.
805
+ ...pipelineConfigInput(loaded),
806
+ ...(routePlan === undefined ? {} : { routePlan }),
807
+ engine: await engineIdentity(),
808
+ promptSet,
809
+ spec,
810
+ ...(skipDiscovery ? { skipDiscovery: true } : {}),
811
+ ...(rereview === undefined ? {} : { rereview }),
812
+ ...(verifyQueue.length > 0 ? { verifyQueue } : {}),
813
+ ...(overlapCandidates.length > 0 ? { overlapCandidates } : {}),
814
+ ...(adjudicationQueue.length > 0 ? { adjudicationQueue } : {}),
815
+ maxVerificationSteps,
816
+ ...(phaseB === undefined ? {} : { phaseB }),
817
+ },
818
+ prepared.deps,
819
+ );
820
+ } finally {
821
+ // try/finally, never success-only: a leaked interval keeps the
822
+ // event loop alive and hangs process exit on the error path.
823
+ // `::endgroup::` is no longer emitted here — it rides
824
+ // withCiWorkflowGroup's own finally, which wraps this whole block.
825
+ progress.stop();
826
+ await unregisterActiveRun(process.pid);
827
+ if (productionRuntime !== undefined) {
828
+ await productionRuntime.dispose();
829
+ }
830
+ }
831
+ });
832
+ recordPipelineOutcome(result, headSha);
833
+ // 12-16 — everything from the artifact write through CI publishing and
834
+ // the ledger's terminal settlement. See publishRunOutcome
835
+ // (src/pr/publish-outcome.ts) for the full rationale, including the
836
+ // `onPosted` hazard: `posted` is declared outside this try (the
837
+ // finally below reads it on every exit path, including a throw from
838
+ // inside publishRunOutcome itself), so the callback assigns it the
839
+ // instant the posting stage resolves — never only at the end.
840
+ //
841
+ // `await`, never a bare `return publishRunOutcome(...)`: this
842
+ // sits inside a try/finally, and a bare `return` hands back the
843
+ // pending promise WITHOUT suspending here, so the `finally` below runs
844
+ // synchronously right away — before publishRunOutcome has done
845
+ // anything, let alone fired `onPosted`. That would settle the commit
846
+ // status (and read `posted`) against pre-run state on every call, not
847
+ // just on a throw. The `await` is what makes this function actually
848
+ // wait for publishRunOutcome to settle before the finally can run.
849
+ const exitCode = await publishRunOutcome({
850
+ result,
851
+ started,
852
+ indexMs,
853
+ runDir,
854
+ prNumber,
855
+ diffFromSha,
856
+ headSha,
857
+ options,
858
+ agentFiles,
859
+ promptSet,
860
+ operatorRoot,
861
+ baseRef: target.baseRef,
862
+ diffStat,
863
+ droppedPaths: effectiveDiff.droppedPaths,
864
+ diffPatch: anchorPatch,
865
+ home,
866
+ repoId: repoHome.repoId,
867
+ postEnabled,
868
+ rereview,
869
+ phaseB,
870
+ gitDirOwner,
871
+ worktreePath,
872
+ isCi,
873
+ ciMode,
874
+ estimate,
875
+ freeRoute,
876
+ ciAdmissionLedger,
877
+ onPosted: (outcome) => {
878
+ posted = outcome;
879
+ },
880
+ onBlockingCount: (count) => {
881
+ blockingCount = count;
882
+ },
883
+ });
884
+ // T5b: the verdicts are posted only after the review itself published.
885
+ // Only a `--ci` run with posting on writes them to the PR.
886
+ if (postEnabled && options.ci === true) {
887
+ // The verdicts never change this run's count: the next review of this head
888
+ // reads them back (see fillRereviewProvenance).
889
+ await postAdjudicationReplies({
890
+ operatorRoot,
891
+ pr: prNumber,
892
+ headSha,
893
+ adjudications: result?.adjudications ?? [],
894
+ });
895
+ }
896
+ return exitCode;
897
+ } catch (error) {
898
+ bodyFailed = true;
899
+ throw error;
900
+ } finally {
901
+ // The commit status must settle BEFORE the lock is released, and the
902
+ // ledger settlement must still run on throw or early return. See
903
+ // settleCommitStatusAndLedger (src/pr/teardown.ts) for the full
904
+ // rationale, including why a failed write never replaces a body's error.
905
+ await settleCommitStatusAndLedger({
906
+ result,
907
+ posted,
908
+ operatorRoot,
909
+ headSha,
910
+ statusTargetUrl,
911
+ ciAdmissionLedger,
912
+ ciMode,
913
+ statusContext,
914
+ blockingCount,
915
+ bodyFailed,
916
+ });
917
+ }
918
+ } finally {
919
+ // See finalizePrReviewRun (src/pr/teardown.ts) for the full rationale.
920
+ await finalizePrReviewRun({
921
+ ciAdmissionLedger,
922
+ lockPath,
923
+ home,
924
+ repoId: repoHome.repoId,
925
+ });
926
+ }
927
+ }