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
package/src/pr/pr.ts ADDED
@@ -0,0 +1,3642 @@
1
+ // PR mode's I/O (ROADMAP B1): gh, the fetch, the detached worktree, the
2
+ // worktree's codegraph index — every side effect `pr-hero review --pr <n>`
3
+ // needs beyond what cli.ts already owns.
4
+ // Same contract as cli.ts: this is an I/O shell, and every decision it acts
5
+ // on is a pure function in pr/preflight.ts / pr/inline.ts (or review/preflight.ts),
6
+ // where most of the tests live.
7
+ //
8
+ // ROADMAP B6 exception, spelled out because it changes the file's own
9
+ // header claim: the review-submission functions below (`postPrReview`,
10
+ // `postIssueComment`, `fetchPrReviewComments`, `fetchPostedFindingComments`,
11
+ // `postCommitStatus`, `fetchCommitStatuses`)
12
+ // ARE offline-tested, in test/pr/pr.test.ts, via an injectable `spawnFn` on the
13
+ // internal `gh()` helper — the 422 recovery path is exactly the kind of
14
+ // branch that must never rest on "we'll catch it live".
15
+ //
16
+ // Every git and gh call here runs with the OPERATOR root as cwd — gh talks
17
+ // to GitHub, and the operator checkout is the trust anchor — EXCEPT the
18
+ // object-db git that owns the review worktree (fetchPrRefs, ensureWorktree)
19
+ // and the two read-only inspections of the worktree itself. W3: `git
20
+ // worktree add` is bound to one git dir, the registered owner for that
21
+ // origin, which may not be the operator cwd.
22
+
23
+ import { randomUUID } from "node:crypto";
24
+ import { existsSync } from "node:fs";
25
+ import path from "node:path";
26
+ import {
27
+ ADMISSION_CHECK_RUN_NAME,
28
+ type AdmissionAttemptStatus,
29
+ type AdmissionRecord,
30
+ parseAdmissionRecord,
31
+ serializeAdmissionRecord,
32
+ } from "#ci/admission-ledger";
33
+ import { CI_FORCE_WORKFLOW_FILE } from "#ci/force-comment";
34
+ import {
35
+ canonicalAdmissionFindings,
36
+ nextStateReviewCount,
37
+ renderCiAdmissionBlock,
38
+ tierCountsFromFindings,
39
+ } from "#ci/review-admission";
40
+ import type { PrHeroFindingRef } from "#compare/compare";
41
+ import { THREAD_PAGE_SIZE } from "#corpus/preflight";
42
+ import { git } from "#git/git";
43
+ import { isFullCommitId } from "#git/refs";
44
+ import type { FindingChannel } from "#rereview/classify";
45
+ import { collapseTargets, type RereviewProvenance } from "#rereview/prepare";
46
+ import {
47
+ droppedStateNote,
48
+ type FreshStateFinding,
49
+ GITHUB_ISSUE_COMMENT_MAX,
50
+ type MergedState,
51
+ mergeStateFindings,
52
+ parseStateBlock,
53
+ renderStateBlock,
54
+ stateBlockBudget,
55
+ } from "#rereview/state";
56
+ import type { Finding, FindingsDocument } from "#review/findings";
57
+ import {
58
+ type PrCommentDelta,
59
+ parseFindingCommentBadge,
60
+ renderInlineComment,
61
+ renderIssueFindingComment,
62
+ renderPrComment,
63
+ renderRereviewClosedComment,
64
+ rereviewDeltaFromProvenance,
65
+ } from "#review/report";
66
+ import { GH_PR_VIEW_TIMEOUT_MS } from "#store/gc-preflight";
67
+ import { log } from "#ui/primitives";
68
+ import { parseMarkerHead } from "#watch/preflight";
69
+ import {
70
+ isAdmissionCheckRunName,
71
+ LEGACY_ADMISSION_CHECK_RUN_NAME,
72
+ LEGACY_WORKFLOW_FILE_NAME,
73
+ matchMarkerPrefix,
74
+ statusContextForms,
75
+ WORKFLOW_FILE_NAME,
76
+ } from "../brand";
77
+ import { CliError } from "../errors";
78
+ import {
79
+ buildPostPlan,
80
+ computeDroppedFindingIds,
81
+ type InlinePostOutcome,
82
+ matchPostedFindings,
83
+ type PostedFindingComment,
84
+ type PostPlan,
85
+ parseHunkAnchors,
86
+ resolvePostLine,
87
+ } from "./inline";
88
+ import {
89
+ type CiMode,
90
+ COMMIT_STATUS_TIMEOUT_MS,
91
+ type CommitStatusFact,
92
+ type CommitStatusRequest,
93
+ claimFingerprint,
94
+ decideWorktree,
95
+ findMarkedCommentId,
96
+ parseFindingMarker,
97
+ type WorktreeDecision,
98
+ worktreeDirty,
99
+ } from "./preflight";
100
+
101
+ export const GRAPHQL_COMMENT_MAX_PAGES = 50;
102
+
103
+ export class CommentsTruncatedError extends CliError {}
104
+
105
+ // `spawnFn` is the ONLY seam this module adds for testability, and it is
106
+ // deliberately invisible to production callers: every existing call site
107
+ // omits it and gets `Bun.spawn` exactly as before. Only test/pr/pr.test.ts
108
+ // passes one, to script gh's response (including a 422) without a live PR.
109
+ // The `Bun.which("gh")` guard is skipped under a fake spawn on purpose — a
110
+ // real environment missing `gh` must still fail loud, but an offline test
111
+ // must never depend on whether the machine RUNNING it happens to have `gh`
112
+ // installed, or the suite becomes non-hermetic for a reason that has
113
+ // nothing to do with the behavior under test.
114
+ async function gh(
115
+ operatorRoot: string,
116
+ args: string[],
117
+ stdin?: string,
118
+ spawnFn?: typeof Bun.spawn,
119
+ timeoutMs?: number,
120
+ ): Promise<{ ok: boolean; stdout: string; stderr: string }> {
121
+ const spawn = spawnFn ?? Bun.spawn;
122
+ // A missing gh must name itself: Bun.spawn's error for a binary that is
123
+ // not there reads like a crash, not like "install the GitHub CLI".
124
+ if (spawnFn === undefined && Bun.which("gh") === null) {
125
+ throw new CliError(
126
+ "gh not found on PATH — PR mode resolves the PR through the GitHub " +
127
+ "CLI. Install it and authenticate (gh auth login) first.",
128
+ );
129
+ }
130
+ // cwd = operator root: gh resolves owner/repo from the checkout's remote,
131
+ // so the PR consulted always belongs to the repo passed as --repo.
132
+ //
133
+ // stdin carries a field value when the caller passes `-F key=@-` (gh reads
134
+ // `@-` from stdin; verified against `gh api --help`, 2026-08-10): a report
135
+ // body on stdin dodges ARG_MAX and needs no shell-quoting, because there
136
+ // is no shell anywhere in this call.
137
+ const proc = spawn(["gh", ...args], {
138
+ cwd: operatorRoot,
139
+ ...(stdin === undefined ? {} : { stdin: new TextEncoder().encode(stdin) }),
140
+ stdout: "pipe",
141
+ stderr: "pipe",
142
+ ...(timeoutMs === undefined ? {} : { timeout: timeoutMs }),
143
+ });
144
+ // Watchdog, same shape as ClaudeCodeRunner.runAttempt's
145
+ // (`src/review/step-runner.ts:361-378`): kill on the deadline, clear in a
146
+ // `finally`, and report the kill as a failure rather than as an empty
147
+ // success. Bun.spawn's own `timeout` above would also reap a real process,
148
+ // but only a real one — every `gh` seam in this codebase is a `spawnFn`,
149
+ // and an explicit kill is the only bound that holds for both. Without it
150
+ // an accepted-but-unanswered `gh` call parks on `proc.exited` forever and
151
+ // takes the whole command with it, including an unattended `--yes` run.
152
+ let timedOut = false;
153
+ const watchdog =
154
+ timeoutMs === undefined
155
+ ? undefined
156
+ : setTimeout(() => {
157
+ timedOut = true;
158
+ proc.kill();
159
+ }, timeoutMs);
160
+ let stdout: string;
161
+ let stderr: string;
162
+ let exitCode: number;
163
+ try {
164
+ [stdout, stderr, exitCode] = await Promise.all([
165
+ new Response(proc.stdout).text(),
166
+ new Response(proc.stderr).text(),
167
+ proc.exited,
168
+ ]);
169
+ } finally {
170
+ if (watchdog !== undefined) clearTimeout(watchdog);
171
+ }
172
+ if (timedOut) {
173
+ return {
174
+ ok: false,
175
+ stdout,
176
+ stderr: `gh timed out after ${timeoutMs} ms${
177
+ stderr.trim().length === 0 ? "" : `: ${stderr.trim()}`
178
+ }`,
179
+ };
180
+ }
181
+ return { ok: exitCode === 0, stdout, stderr };
182
+ }
183
+
184
+ // The contract between this call and the pure resolvePrTarget, which parses
185
+ // exactly these fields; change them together.
186
+ export const PR_VIEW_JSON_FIELDS =
187
+ "number,title,state,headRefOid,baseRefName,baseRefOid,mergeCommit," +
188
+ "additions,deletions,changedFiles";
189
+
190
+ export async function ghPrView(
191
+ operatorRoot: string,
192
+ pr: number,
193
+ options?: { spawnFn?: typeof Bun.spawn; timeoutMs?: number },
194
+ ): Promise<string> {
195
+ // Unbounded unless the caller names a bound, as before: a caller that must not hang passes
196
+ // one (pr-hero status does, with GH_PR_VIEW_TIMEOUT_MS).
197
+ const result = await gh(
198
+ operatorRoot,
199
+ ["pr", "view", String(pr), "--json", PR_VIEW_JSON_FIELDS],
200
+ undefined,
201
+ options?.spawnFn,
202
+ options?.timeoutMs,
203
+ );
204
+ if (!result.ok) {
205
+ throw new CliError(`gh pr view ${pr} failed: ${result.stderr.trim()}`);
206
+ }
207
+ return result.stdout;
208
+ }
209
+
210
+ // The NO-ARGUMENT `gh pr view`: gh resolves the PR belonging to the
211
+ // checkout's current branch, which is the whole feature behind bare `--pr`
212
+ // — "review the PR I am standing on". Returns raw stdout for the pure
213
+ // resolveCurrentPrNumber; a branch with no PR fails loud, with gh's own
214
+ // message appended because it names the branch.
215
+ export async function ghCurrentBranchPr(
216
+ operatorRoot: string,
217
+ options?: { spawnFn?: typeof Bun.spawn },
218
+ ): Promise<string> {
219
+ const result = await gh(
220
+ operatorRoot,
221
+ ["pr", "view", "--json", "number"],
222
+ undefined,
223
+ options?.spawnFn,
224
+ );
225
+ if (!result.ok) {
226
+ throw new CliError(
227
+ `no PR found for the current branch of ${operatorRoot} — open one ` +
228
+ "first or pass --pr <n> explicitly" +
229
+ (result.stderr.trim() ? `: ${result.stderr.trim()}` : ""),
230
+ );
231
+ }
232
+ return result.stdout;
233
+ }
234
+
235
+ // The open-PR listing the watch tick (B3) candidates from. Raw stdout for
236
+ // the pure parsePrList — same contract as ghPrView/resolvePrTarget. An
237
+ // explicit --limit, because gh's default caps the list at 30 NEWEST PRs:
238
+ // the watcher picks the LOWEST eligible number (FIFO), and a busy repo's
239
+ // oldest open PRs falling off the list would be exactly the silent
240
+ // truncation the comments fetch already learned to avoid with --paginate.
241
+ // additions/deletions/changedFiles ride along FREE: gh returns them in the
242
+ // same list response, and they are the watcher's zero-extra-call first tier
243
+ // for the size gate (see gatherRepoFacts). Verified against `gh pr list
244
+ // --json` on 2026-08-11 — all three are real list fields, alongside the
245
+ // per-file `files`, which is deliberately NOT requested here: it would make
246
+ // every tick carry the full file list of every open PR.
247
+ export const PR_LIST_JSON_FIELDS =
248
+ "number,headRefOid,isDraft,additions,deletions,changedFiles";
249
+ export const PR_LIST_LIMIT = 200;
250
+
251
+ export async function ghPrList(operatorRoot: string): Promise<string> {
252
+ const result = await gh(operatorRoot, [
253
+ "pr",
254
+ "list",
255
+ "--limit",
256
+ String(PR_LIST_LIMIT),
257
+ "--json",
258
+ PR_LIST_JSON_FIELDS,
259
+ ]);
260
+ if (!result.ok) {
261
+ throw new CliError(`gh pr list failed: ${result.stderr.trim()}`);
262
+ }
263
+ return result.stdout;
264
+ }
265
+
266
+ // The repository's web URL (https://github.com/org/repo), used only to turn
267
+ // the PR comment's locations into links. Cosmetic by contract: ANY failure
268
+ // returns undefined and the comment renders plain — a review must never die,
269
+ // or even warn loudly, because a nicety could not be resolved.
270
+ // The size gate's SECOND tier, and only for a PR whose aggregate already
271
+ // exceeds a limit: the per-file list, so an exclusion (a regenerated
272
+ // lockfile, a minified bundle) can still rescue it. One gh call per such PR
273
+ // — the same "pay per candidate, only when the free check did not settle
274
+ // it" shape the comments fetch already uses.
275
+ //
276
+ // Field names verified live against `gh pr view <n> -R cli/cli --json files`
277
+ // on 2026-08-11: `{"files":[{"path":…,"additions":…,"deletions":…,
278
+ // "changeType":…}]}`.
279
+ //
280
+ // BOUNDED, and the bound is load-bearing since PR #205 put this call on the
281
+ // WATCH TICK path (the pre-launch exclusion veto in watch/watch.ts calls it every
282
+ // tick, for the chosen launch). `gh()`'s watchdog only arms when a timeoutMs
283
+ // is passed, so without this an accepted-but-unanswered `gh pr view` parks on
284
+ // `proc.exited` forever, and the tick that is holding watch.lock never
285
+ // returns — silencing every later tick, exactly what GH_PR_VIEW_TIMEOUT_MS's
286
+ // own WHY (store/gc-preflight.ts) exists to prevent, and what fetchCommitStatuses
287
+ // on the same path already spells out. Same constant as the GC's `gh pr
288
+ // view` because this IS a `gh pr view`. A timeout surfaces as a thrown
289
+ // CliError, which the veto's fail-open turns into "launch anyway" — the
290
+ // correct direction: an unreadable file list is no evidence against a PR.
291
+ export async function ghPrFiles(
292
+ operatorRoot: string,
293
+ pr: number,
294
+ options?: { spawnFn?: typeof Bun.spawn },
295
+ ): Promise<string> {
296
+ const result = await gh(
297
+ operatorRoot,
298
+ ["pr", "view", String(pr), "--json", "files"],
299
+ undefined,
300
+ options?.spawnFn,
301
+ GH_PR_VIEW_TIMEOUT_MS,
302
+ );
303
+ if (!result.ok) {
304
+ throw new CliError(
305
+ `gh pr view ${pr} --json files failed: ${result.stderr.trim()}`,
306
+ );
307
+ }
308
+ return result.stdout;
309
+ }
310
+
311
+ // The PR's head AS GITHUB SEES IT RIGHT NOW — the re-read behind the
312
+ // moved-head disclosure (GitHub #39, ROADMAP-DOORDASH M1). Deliberately a
313
+ // separate, narrow call rather than reusing ghPrView: this runs in the
314
+ // posting sequence, milliseconds before a mutating POST, and the one field
315
+ // it needs is the one field it asks for.
316
+ //
317
+ // NON-THROWING, same cosmetic-degradation contract as ghRepoWebUrl above,
318
+ // and the WHY is the load-bearing part: `commit_id` on the review submission
319
+ // is the CORRECTNESS mechanism — with it, GitHub anchors every comment to
320
+ // the reviewed commit whatever the branch has done since. This re-read is
321
+ // only the DISCLOSURE on top of it. A disclosure that cannot be made must
322
+ // never cost the post that the pin already protects, so a gh failure (rate
323
+ // limit, transient 5xx, a repo the token lost access to) degrades to "we do
324
+ // not know", never to a thrown run. Empty stdout is treated as failure for
325
+ // the same reason `-q` on a deleted PR prints nothing: an empty string is
326
+ // not a sha, and comparing it against the reviewed head would manufacture a
327
+ // mismatch out of a missing answer.
328
+ export async function ghPrHeadSha(
329
+ operatorRoot: string,
330
+ pr: number,
331
+ options?: { spawnFn?: typeof Bun.spawn; timeoutMs?: number },
332
+ ): Promise<string | undefined> {
333
+ try {
334
+ // Bounded by default (F004): its only caller is the findings POST's
335
+ // pre-review re-read, and an unanswered read there would park the POST.
336
+ const result = await gh(
337
+ operatorRoot,
338
+ ["pr", "view", String(pr), "--json", "headRefOid", "-q", ".headRefOid"],
339
+ undefined,
340
+ options?.spawnFn,
341
+ options?.timeoutMs ?? POSTING_GH_TIMEOUT_MS,
342
+ );
343
+ if (!result.ok) return undefined;
344
+ const sha = result.stdout.trim();
345
+ return sha === "" ? undefined : sha;
346
+ } catch {
347
+ return undefined;
348
+ }
349
+ }
350
+
351
+ export async function ghRepoWebUrl(
352
+ operatorRoot: string,
353
+ options?: { spawnFn?: typeof Bun.spawn; timeoutMs?: number },
354
+ ): Promise<string | undefined> {
355
+ try {
356
+ // Bounded by default (F004): posting.ts calls this with no options, and an
357
+ // unanswered `gh repo view` there would park the findings POST before its
358
+ // first write. Every caller already treats undefined as "unknown", so a
359
+ // timeout here degrades exactly like a failed call.
360
+ const result = await gh(
361
+ operatorRoot,
362
+ ["repo", "view", "--json", "url", "-q", ".url"],
363
+ undefined,
364
+ options?.spawnFn,
365
+ options?.timeoutMs ?? POSTING_GH_TIMEOUT_MS,
366
+ );
367
+ if (!result.ok) return undefined;
368
+ const url = result.stdout.trim();
369
+ return url === "" ? undefined : url;
370
+ } catch {
371
+ return undefined;
372
+ }
373
+ }
374
+
375
+ // The PR's own web URL, the fallback an outside-channel triage reply links its finding through
376
+ // when the repo's web URL cannot be read. Bounded like ghRepoWebUrl, and undefined on any
377
+ // failure, so the caller can fall through to the next source.
378
+ export async function ghPrWebUrl(
379
+ operatorRoot: string,
380
+ pr: number,
381
+ options?: { spawnFn?: typeof Bun.spawn; timeoutMs?: number },
382
+ ): Promise<string | undefined> {
383
+ try {
384
+ const result = await gh(
385
+ operatorRoot,
386
+ ["pr", "view", String(pr), "--json", "url", "-q", ".url"],
387
+ undefined,
388
+ options?.spawnFn,
389
+ options?.timeoutMs ?? POSTING_GH_TIMEOUT_MS,
390
+ );
391
+ if (!result.ok) return undefined;
392
+ const url = result.stdout.trim();
393
+ return url === "" ? undefined : url;
394
+ } catch {
395
+ return undefined;
396
+ }
397
+ }
398
+
399
+ // The repo's owner/name (`owner/repo`), the last source an outside-channel triage reply's link
400
+ // is built from. Bounded like ghRepoWebUrl; undefined on any failure.
401
+ export async function ghRepoNameWithOwner(
402
+ operatorRoot: string,
403
+ options?: { spawnFn?: typeof Bun.spawn; timeoutMs?: number },
404
+ ): Promise<string | undefined> {
405
+ try {
406
+ const result = await gh(
407
+ operatorRoot,
408
+ ["repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"],
409
+ undefined,
410
+ options?.spawnFn,
411
+ options?.timeoutMs ?? POSTING_GH_TIMEOUT_MS,
412
+ );
413
+ if (!result.ok) return undefined;
414
+ const name = result.stdout.trim();
415
+ return name === "" ? undefined : name;
416
+ } catch {
417
+ return undefined;
418
+ }
419
+ }
420
+
421
+ // In-flight / completed signal on the head SHA. Fail-loud here: the CLI
422
+ // catches and warns, because a missing `repo:status` scope must not abort a
423
+ // review that already cost hunter money. The context is the request's own
424
+ // (T3 S7): the gate's `crysk` only from a `--ci` run's request, and
425
+ // `crysk/local` from every other run, so the POST can never pick a context
426
+ // the caller did not choose.
427
+ //
428
+ // WHY two POSTs: for one version every status is also written on the legacy
429
+ // `pr-hero` name (`pr-hero/local` for a local run). Users have `pr-hero` as a
430
+ // required check in branch protection, and a head that stops getting it blocks
431
+ // every PR until they add `crysk`. Both POSTs carry one state, one description
432
+ // and one target. They start together, crysk first, so the cancellation settle
433
+ // (which runs inside a signal handler racing a SIGKILL) spends one short
434
+ // window, not two. A failed POST never skips the other: the required check may
435
+ // be either name, so the call still throws if either failed, and the caller's
436
+ // own handling (fail-soft or fail-loud) applies exactly as it did to one POST.
437
+ // Resolves with the created_at of the crysk row, the context the CLI reads back.
438
+ export async function postCommitStatus(
439
+ operatorRoot: string,
440
+ sha: string,
441
+ status: CommitStatusRequest,
442
+ spawnFn?: typeof Bun.spawn,
443
+ // Only the cancellation settle narrows these. It runs inside a signal
444
+ // handler racing the runner's SIGKILL, where the retry below costs more
445
+ // time than it buys. Every other caller keeps the two-attempt default.
446
+ options?: { attempts?: number; timeoutMs?: number },
447
+ ): Promise<string | undefined> {
448
+ if (!isFullCommitId(sha)) {
449
+ throw new CliError(
450
+ `commit status: head sha is not a full 40-char id: ${sha.slice(0, 16)}`,
451
+ );
452
+ }
453
+ const results = await Promise.allSettled(
454
+ statusContextForms(status.context).map((context) =>
455
+ postCommitStatusOn(
456
+ operatorRoot,
457
+ sha,
458
+ { ...status, context },
459
+ spawnFn,
460
+ options,
461
+ ),
462
+ ),
463
+ );
464
+ for (const result of results) {
465
+ if (result.status === "rejected") throw result.reason;
466
+ }
467
+ const [crysk] = results;
468
+ return crysk?.status === "fulfilled" ? crysk.value : undefined;
469
+ }
470
+
471
+ // One POST of a status on one context, with the retry.
472
+ async function postCommitStatusOn(
473
+ operatorRoot: string,
474
+ sha: string,
475
+ status: {
476
+ state: string;
477
+ context: string;
478
+ description: string;
479
+ targetUrl?: string;
480
+ },
481
+ spawnFn: typeof Bun.spawn | undefined,
482
+ options: { attempts?: number; timeoutMs?: number } | undefined,
483
+ ): Promise<string | undefined> {
484
+ const args = [
485
+ "api",
486
+ "--method",
487
+ "POST",
488
+ `repos/{owner}/{repo}/statuses/${sha}`,
489
+ "-f",
490
+ `state=${status.state}`,
491
+ "-f",
492
+ `context=${status.context}`,
493
+ "-f",
494
+ `description=${status.description}`,
495
+ ];
496
+ if (status.targetUrl !== undefined) {
497
+ args.push("-f", `target_url=${status.targetUrl}`);
498
+ }
499
+ // Two attempts: a single blip on the completing POST is exactly how a
500
+ // yellow pending gets stuck on a finished review.
501
+ const attempts = options?.attempts ?? 2;
502
+ const timeoutMs = options?.timeoutMs ?? COMMIT_STATUS_TIMEOUT_MS;
503
+ let lastStderr = "";
504
+ for (let attempt = 0; attempt < attempts; attempt++) {
505
+ const result = await gh(operatorRoot, args, undefined, spawnFn, timeoutMs);
506
+ if (result.ok) return createdAtOf(result.stdout);
507
+ lastStderr = result.stderr.trim();
508
+ }
509
+ throw new CliError(
510
+ `gh api (commit status ${status.state} on ${status.context}) failed: ${lastStderr}`,
511
+ );
512
+ }
513
+
514
+ // The created_at of the status a POST created, or undefined when the answer has none (a
515
+ // fake, or an answer gh did not print). Never throws: the write already landed.
516
+ function createdAtOf(stdout: string): string | undefined {
517
+ try {
518
+ const parsed = JSON.parse(stdout) as { created_at?: unknown };
519
+ return typeof parsed.created_at === "string"
520
+ ? parsed.created_at
521
+ : undefined;
522
+ } catch {
523
+ return undefined;
524
+ }
525
+ }
526
+
527
+ // Combined status (singular `/status`), not the paginated list (`/statuses`).
528
+ // The list interleaves every CI context newest-first, so a busy SHA can bury
529
+ // `pr-hero` past page 1 and the watcher would miss an in-flight pending.
530
+ // Combined returns the latest row per context in one shot.
531
+ //
532
+ // WHY per_page=100: the combined endpoint pages its contexts at 30 by default, so a
533
+ // busy head's `pr-hero` row can sit past the first page. The publisher's reader asks for
534
+ // 100 (src/ci/publish.ts, readHeadStatuses), and this one must see the same rows, or the
535
+ // CLI writes its verdict over an override the publisher sees. The in-flight readers
536
+ // (watch, the admission yield guard) take the newest row per context, so the extra rows
537
+ // only add contexts they would otherwise miss.
538
+ //
539
+ // The description rides along for the override check (src/pr/teardown.ts), which tells
540
+ // an override from a review's own status by it. The in-flight readers ignore it. The
541
+ // target_url rides along for `pr-hero status`, which names the run that wrote the gate.
542
+ //
543
+ // The head's full status history, every row, newest first, for the CI admission carry-forward
544
+ // (src/pr/admission.ts) and the skip's override check. It reads the paginated list (`/statuses`),
545
+ // not the combined endpoint: the combined one keeps only the newest row per context, so an override
546
+ // would show in place of the review's own verdict under it. Null on any failure, a malformed row
547
+ // included, so the caller can fail closed; an empty array means the head has no rows at all.
548
+ //
549
+ // WHY --paginate: a head with more than 100 rows keeps its older rows on page 2, and the carry reads
550
+ // the newest verdict. Page 1 alone would miss it and carry a false red. The call stays bounded by
551
+ // its timeout, and --paginate runs the --jq projection on every page, so the output is still one
552
+ // row per line.
553
+ export async function fetchCommitStatusList(
554
+ operatorRoot: string,
555
+ sha: string,
556
+ options?: { spawnFn?: typeof Bun.spawn },
557
+ ): Promise<CommitStatusFact[] | null> {
558
+ if (!isFullCommitId(sha)) return null;
559
+ try {
560
+ const result = await gh(
561
+ operatorRoot,
562
+ [
563
+ "api",
564
+ "--paginate",
565
+ `repos/{owner}/{repo}/commits/${sha}/statuses?per_page=100`,
566
+ "--jq",
567
+ ".[]? | {state: .state, context: .context, created_at: .created_at, description: .description}",
568
+ ],
569
+ undefined,
570
+ options?.spawnFn,
571
+ COMMIT_STATUS_TIMEOUT_MS,
572
+ );
573
+ if (!result.ok) return null;
574
+ const statuses: CommitStatusFact[] = [];
575
+ for (const line of result.stdout.split("\n")) {
576
+ if (line.trim() === "") continue;
577
+ const parsed = JSON.parse(line) as CommitStatusFact;
578
+ if (
579
+ typeof parsed.state !== "string" ||
580
+ typeof parsed.context !== "string" ||
581
+ typeof parsed.created_at !== "string"
582
+ ) {
583
+ return null;
584
+ }
585
+ statuses.push(parsed);
586
+ }
587
+ return statuses;
588
+ } catch {
589
+ return null;
590
+ }
591
+ }
592
+
593
+ // The PR's commit shas, OLDEST first (GitHub's order for pulls/<n>/commits). The CI admission
594
+ // carry-forward walks them newest-first from the head (src/pr/admission.ts). WHY --paginate: a PR
595
+ // above 100 commits keeps its newest commits on page 2, which a single page would never reach. GitHub
596
+ // lists at most 250 commits per pull request, so the call is at most three requests, and it stays
597
+ // bounded by its timeout. Null on any failure or a malformed sha, so the caller can fail closed; an
598
+ // empty array means the list has no commits.
599
+ export async function fetchPrCommitShas(
600
+ operatorRoot: string,
601
+ pr: number,
602
+ options?: { spawnFn?: typeof Bun.spawn },
603
+ ): Promise<string[] | null> {
604
+ try {
605
+ const result = await gh(
606
+ operatorRoot,
607
+ [
608
+ "api",
609
+ "--paginate",
610
+ `repos/{owner}/{repo}/pulls/${pr}/commits?per_page=100`,
611
+ "--jq",
612
+ ".[]?.sha",
613
+ ],
614
+ undefined,
615
+ options?.spawnFn,
616
+ COMMIT_STATUS_TIMEOUT_MS,
617
+ );
618
+ if (!result.ok) return null;
619
+ const shas: string[] = [];
620
+ for (const line of result.stdout.split("\n")) {
621
+ const sha = line.trim();
622
+ if (sha === "") continue;
623
+ if (!isFullCommitId(sha)) return null;
624
+ shas.push(sha);
625
+ }
626
+ return shas;
627
+ } catch {
628
+ return null;
629
+ }
630
+ }
631
+
632
+ // Never throws by default: a 403, a hung gh (timeout), or garbage jq must not take the watch tick
633
+ // down. Unreadable reads as no rows, which the watch reads as not in-flight.
634
+ //
635
+ // WHY failClosed: two readers must tell a failed read from a head with no status rows, because an
636
+ // empty answer for an unreadable head reads as "no status". The CI override check
637
+ // (src/ci/publish.ts, src/pr/teardown.ts) would then write over a human's decision, and `pr-hero status`,
638
+ // the skill's only reading of the gate (src/commands/status.ts), would send a review out blind. The
639
+ // default keeps the empty answer every watch and admission caller relies on.
640
+ //
641
+ // Three modes, because the readers need different things from a bad row:
642
+ // - false (default): a failed read returns [], and a bad row is dropped.
643
+ // - "read": a failed read throws, and so does an abbreviated sha, which is a head that cannot be read.
644
+ // A bad row is still dropped, so one garbage line cannot hide a valid override on the same head.
645
+ // This is the mode the override checks use: the only unknown is whether gh answered at all.
646
+ // - true: a failed read throws, and so does a bad row, because the row it would drop could be the
647
+ // override. Used by `pr-hero status` and admission, which must not read past a row they cannot parse.
648
+ export async function fetchCommitStatuses(
649
+ operatorRoot: string,
650
+ sha: string,
651
+ options?: { spawnFn?: typeof Bun.spawn; failClosed?: boolean | "read" },
652
+ ): Promise<CommitStatusFact[]> {
653
+ const failClosed = options?.failClosed;
654
+ const strictRead = failClosed === true || failClosed === "read";
655
+ const strictRows = failClosed === true;
656
+ const unreadable = (why: string): CommitStatusFact[] => {
657
+ if (strictRead) {
658
+ throw new CliError(
659
+ `could not read the statuses of ${sha.slice(0, 7)}: ${why}`,
660
+ );
661
+ }
662
+ return [];
663
+ };
664
+ if (!isFullCommitId(sha)) return unreadable("not a full commit id");
665
+ try {
666
+ const result = await gh(
667
+ operatorRoot,
668
+ [
669
+ "api",
670
+ `repos/{owner}/{repo}/commits/${sha}/status?per_page=100`,
671
+ "--jq",
672
+ ".statuses[]? | {state: .state, context: .context, created_at: .created_at, description: .description, target_url: .target_url}",
673
+ ],
674
+ undefined,
675
+ options?.spawnFn,
676
+ COMMIT_STATUS_TIMEOUT_MS,
677
+ );
678
+ if (!result.ok) return unreadable(result.stderr.trim() || "gh failed");
679
+ const statuses: CommitStatusFact[] = [];
680
+ for (const line of result.stdout.split("\n")) {
681
+ if (line.trim() === "") continue;
682
+ // Every bad line takes one of two paths, decided per line: a line that does not parse, and a line
683
+ // that parses to something other than a status (`null`, a bare string, a row missing a field). Both
684
+ // are skipped by default and in "read" mode, and both throw under true. The shape check sits inside
685
+ // this per-line handling on purpose: outside it, a `null` throws a TypeError into the outer catch,
686
+ // which returns [] and drops every status, not just the bad line.
687
+ const parsed = parseStatusLine(line);
688
+ if (parsed === null) {
689
+ if (strictRows) {
690
+ return unreadable(
691
+ `unreadable commit status line from gh api: ${line.slice(0, 120)}`,
692
+ );
693
+ }
694
+ // Drop the bad line; keep whatever parsed. One garbage object must not hide a real pending on
695
+ // the next line.
696
+ continue;
697
+ }
698
+ statuses.push(parsed);
699
+ }
700
+ return statuses;
701
+ } catch (error) {
702
+ if (strictRead) throw error;
703
+ return [];
704
+ }
705
+ }
706
+
707
+ // One line of the commit-status stream as a status fact, or null when the line is not one:
708
+ // unparseable JSON, or JSON that is not an object with the three string fields a status
709
+ // read needs. Pure, so both modes of fetchCommitStatuses judge a line the same way.
710
+ function parseStatusLine(line: string): CommitStatusFact | null {
711
+ let parsed: unknown;
712
+ try {
713
+ parsed = JSON.parse(line);
714
+ } catch {
715
+ return null;
716
+ }
717
+ if (typeof parsed !== "object" || parsed === null) return null;
718
+ const fact = parsed as Partial<CommitStatusFact>;
719
+ if (
720
+ typeof fact.state !== "string" ||
721
+ typeof fact.context !== "string" ||
722
+ typeof fact.created_at !== "string"
723
+ ) {
724
+ return null;
725
+ }
726
+ return fact as CommitStatusFact;
727
+ }
728
+
729
+ // WHY this exact refspec pair (paid-for): a merged PR's branch is usually
730
+ // deleted, so nothing but `refs/pull/<n>/head` keeps headRefOid fetchable —
731
+ // and fetching the base branch by name in the same call brings the merge
732
+ // commit and the baseRefOid ancestry along, so every rev the flow
733
+ // canonicalizes afterwards resolves against a single fetch.
734
+ export async function fetchPrRefs(
735
+ gitDirOwner: string,
736
+ pr: number,
737
+ baseRefName: string,
738
+ ): Promise<void> {
739
+ const result = await git(gitDirOwner, [
740
+ "fetch",
741
+ "origin",
742
+ `refs/pull/${pr}/head`,
743
+ baseRefName,
744
+ ]);
745
+ if (!result.ok) {
746
+ throw new CliError(
747
+ `git fetch origin refs/pull/${pr}/head ${baseRefName} failed: ` +
748
+ result.stderr.trim(),
749
+ );
750
+ }
751
+ }
752
+
753
+ // Create, reuse, or recreate the detached worktree at the PR's head. The
754
+ // decision itself is pure (decideWorktree); this runs the inspections that
755
+ // feed it and the git plumbing that enacts it.
756
+ export async function ensureWorktree(
757
+ gitDirOwner: string,
758
+ worktreePath: string,
759
+ headSha: string,
760
+ ): Promise<WorktreeDecision> {
761
+ // Prune first: a worktree deleted by hand leaves a stale registration
762
+ // behind, and a stale registration makes the add below refuse.
763
+ const pruned = await git(gitDirOwner, ["worktree", "prune"]);
764
+ if (!pruned.ok) {
765
+ throw new CliError(`git worktree prune failed: ${pruned.stderr.trim()}`);
766
+ }
767
+ const exists = existsSync(worktreePath);
768
+ let headMatches = false;
769
+ let dirty = false;
770
+ if (exists) {
771
+ const head = await git(worktreePath, [
772
+ "rev-parse",
773
+ "--verify",
774
+ "HEAD^{commit}",
775
+ ]);
776
+ headMatches = head.ok && head.stdout.trim() === headSha;
777
+ if (headMatches) {
778
+ const status = await git(worktreePath, ["status", "--porcelain"]);
779
+ if (!status.ok) {
780
+ throw new CliError(
781
+ `git status failed in worktree ${worktreePath}: ` +
782
+ status.stderr.trim(),
783
+ );
784
+ }
785
+ dirty = worktreeDirty(status.stdout);
786
+ }
787
+ }
788
+ const decision = decideWorktree({ exists, headMatches, dirty });
789
+ if (decision.action === "recreate") {
790
+ // --force is REQUIRED, and never rm -rf (VERIFIED 2026-08-10): a plain
791
+ // `worktree remove` exits 128 on the untracked .codegraph/, and rm -rf
792
+ // would yank .codegraph/daemon.sock out from under a live codegraph
793
+ // daemon instead of letting git detach the tree cleanly.
794
+ const removed = await git(gitDirOwner, [
795
+ "worktree",
796
+ "remove",
797
+ "--force",
798
+ worktreePath,
799
+ ]);
800
+ if (!removed.ok) {
801
+ throw new CliError(
802
+ `git worktree remove --force ${worktreePath} failed: ` +
803
+ removed.stderr.trim(),
804
+ );
805
+ }
806
+ const reprune = await git(gitDirOwner, ["worktree", "prune"]);
807
+ if (!reprune.ok) {
808
+ throw new CliError(`git worktree prune failed: ${reprune.stderr.trim()}`);
809
+ }
810
+ }
811
+ if (decision.action !== "reuse") {
812
+ const added = await git(gitDirOwner, [
813
+ "worktree",
814
+ "add",
815
+ "--detach",
816
+ worktreePath,
817
+ headSha,
818
+ ]);
819
+ if (!added.ok) {
820
+ throw new CliError(
821
+ `git worktree add --detach ${worktreePath} ${headSha} failed: ` +
822
+ added.stderr.trim(),
823
+ );
824
+ }
825
+ }
826
+ return decision;
827
+ }
828
+
829
+ // Builds the worktree's OWN index — never another checkout's, whose bytes
830
+ // may differ (the ROADMAP forbids riding a sibling's index). Synchronous by
831
+ // design: the initial build is ~10s/~68MB (measured 8x in the bench), and a
832
+ // pipeline started before the index exists would run its hunters with an
833
+ // inert codegraph grant. The measured elapsed feeds telemetry.index_ms,
834
+ // which local mode hardcodes to 0 because it never builds anything.
835
+ export async function initCodegraphIndex(
836
+ worktreePath: string,
837
+ ): Promise<number> {
838
+ const started = performance.now();
839
+ const proc = Bun.spawn(["codegraph", "init", worktreePath], {
840
+ stdout: "pipe",
841
+ stderr: "pipe",
842
+ });
843
+ const [, stderr, exitCode] = await Promise.all([
844
+ new Response(proc.stdout).text(),
845
+ new Response(proc.stderr).text(),
846
+ proc.exited,
847
+ ]);
848
+ if (exitCode !== 0) {
849
+ throw new CliError(
850
+ `codegraph init ${worktreePath} failed: ${stderr.trim()}`,
851
+ );
852
+ }
853
+ return Math.round(performance.now() - started);
854
+ }
855
+
856
+ // Publishes the review as ONE marked PR comment: update the existing marked
857
+ // comment when there is one, create it otherwise. Idempotency lives in the
858
+ // marker contract (prCommentMarker as the body's first line, matched by
859
+ // findMarkedCommentId on the bare prefix) — a re-run refreshes the same
860
+ // comment instead of stacking a new one per run. Throws CliError on any gh
861
+ // failure and is NOT
862
+ // caught here: the caller asked for a public side effect, so the caller
863
+ // decides what a failed one means.
864
+ // ROADMAP B6 addition: `spawnFn`, same invisible-to-production seam as the
865
+ // other B6 functions (see gh()'s WHY). Needed so test/cli.test.ts can drive
866
+ // the WHOLE step-14 sequence — review, Outside Diff in the summary, summary
867
+ // PATCH LAST —
868
+ // through one shared fake gh, the same way test/pr/pr.test.ts already does for
869
+ // the per-finding functions; a summary PATCH the caller-level test could not
870
+ // see would leave the "PATCHed last" ordering unpinned.
871
+ //
872
+ // `knownCommentId` (create-first rework, Juanma's PR #2 feedback item 2):
873
+ // when the caller already knows the comment id — because IT just created
874
+ // the comment moments ago in this same run, and now wants the closing
875
+ // PATCH — skip the re-fetch-and-find-by-marker lookup entirely and PATCH
876
+ // that id directly. Without this, the closing PATCH would re-discover the
877
+ // comment via `findMarkedCommentId`, which is both a wasted round-trip
878
+ // (the id is already known) and, in a NO-op fake spawn, indistinguishable
879
+ // from "no comment exists yet" — silently creating a SECOND comment instead
880
+ // of patching the first. Omitted (the ordinary re-run path, where the
881
+ // existing comment came from a PREVIOUS run, not this one), the lookup runs
882
+ // exactly as before.
883
+ // `markerPrefix` defaults inside findMarkedCommentId itself (undefined here
884
+ // triggers ITS default, PR_COMMENT_MARKER_PREFIX), so every existing caller
885
+ // — both of which always pass a `knownCommentId` and never reach the lookup
886
+ // at all — stays byte-identical. ROADMAP Pillar 3's CI skip-comment posting
887
+ // is the first caller to exercise the lookup fallback for real, passing
888
+ // ci/gates.ts's SKIP_SIZE_COMMENT_MARKER / SKIP_BUDGET_COMMENT_MARKER so a
889
+ // repeat CI run finds and updates its own prior skip comment instead of
890
+ // stacking a new one.
891
+ // `timeoutMs` bounds the lookup and the write alike (F004). Its default is the
892
+ // findings POST's bound, and both production callers are on that path; the
893
+ // parameter exists so a test can prove a hang fails inside a few ms.
894
+ export async function postPrComment(
895
+ operatorRoot: string,
896
+ pr: number,
897
+ body: string,
898
+ spawnFn?: typeof Bun.spawn,
899
+ knownCommentId?: number,
900
+ markerPrefix?: string,
901
+ timeoutMs: number = POSTING_GH_TIMEOUT_MS,
902
+ ): Promise<{ action: "created" | "updated"; commentId: number }> {
903
+ const existingId =
904
+ knownCommentId ??
905
+ findMarkedCommentId(
906
+ await fetchPrComments(operatorRoot, pr, { spawnFn, timeoutMs }),
907
+ markerPrefix,
908
+ );
909
+ const action = existingId === null ? "created" : "updated";
910
+ // The body travels on stdin via `-F body=@-` (see gh()); PATCH updates the
911
+ // found comment in place, POST creates the first one.
912
+ const result =
913
+ existingId === null
914
+ ? await gh(
915
+ operatorRoot,
916
+ [
917
+ "api",
918
+ "--method",
919
+ "POST",
920
+ `repos/{owner}/{repo}/issues/${pr}/comments`,
921
+ "-F",
922
+ "body=@-",
923
+ ],
924
+ body,
925
+ spawnFn,
926
+ timeoutMs,
927
+ )
928
+ : await gh(
929
+ operatorRoot,
930
+ [
931
+ "api",
932
+ "--method",
933
+ "PATCH",
934
+ `repos/{owner}/{repo}/issues/comments/${existingId}`,
935
+ "-F",
936
+ "body=@-",
937
+ ],
938
+ body,
939
+ spawnFn,
940
+ timeoutMs,
941
+ );
942
+ if (!result.ok) {
943
+ throw new CliError(
944
+ `gh api (${action} PR comment) failed: ${result.stderr.trim()}`,
945
+ );
946
+ }
947
+ // gh api prints the API's response object; its .id names the comment this
948
+ // run touched, which the summary reports for later verification by hand.
949
+ let parsed: unknown = null;
950
+ try {
951
+ parsed = JSON.parse(result.stdout);
952
+ } catch {
953
+ parsed = null;
954
+ }
955
+ const commentId = (parsed as { id?: unknown } | null)?.id;
956
+ if (typeof commentId !== "number") {
957
+ throw new CliError(
958
+ `gh api ${action} a PR comment but returned no comment id: ` +
959
+ result.stdout.slice(0, 120),
960
+ );
961
+ }
962
+ return { action, commentId };
963
+ }
964
+
965
+ // The CI skip notice's channel (pr/admission.ts's publishCiSkip). It used to
966
+ // go through postPrComment's find-and-update, which PATCHed the previous
967
+ // notice on every push. GitHub neither notifies on an edit nor moves the
968
+ // comment down the timeline, so a later skip was invisible: on #315 the
969
+ // budget notice was created at 01:48 and silently re-edited at 02:48.
970
+ //
971
+ // Repost instead: POST the fresh notice at the bottom FIRST, then list the
972
+ // comments and DELETE the older ones under the same marker. That order is
973
+ // the point. A failed POST throws before anything is deleted, so the old
974
+ // notice survives. Listing AFTER the POST also catches a notice a concurrent
975
+ // run created in between. Everything after the POST is best-effort cleanup:
976
+ // a failed, rejected or hung listing or DELETE is logged and never fails the
977
+ // run, because the fresh notice already landed and one stale duplicate is
978
+ // the safe direction of error (the next skip removes it).
979
+ //
980
+ // Every call is bounded. gh() arms its watchdog only when given a timeout,
981
+ // and an accepted-but-unanswered request would otherwise park publishCiSkip
982
+ // before the step summary and CI outputs are written.
983
+ //
984
+ // Deletes only what this identity wrote: the body must START WITH the marker
985
+ // (findMarkedCommentId's rule, so a quoted marker or the summary is never
986
+ // touched) AND the author must be the one GitHub returned for the new
987
+ // notice. A PATCH on someone else's comment fails on its own; a DELETE with
988
+ // a write-scoped token does not, so a collaborator who pastes the notice's
989
+ // source would otherwise lose their comment. Unknown author → delete nothing.
990
+ const SKIP_NOTICE_GH_TIMEOUT_MS = 30_000;
991
+
992
+ export async function repostMarkedPrComment(input: {
993
+ operatorRoot: string;
994
+ pr: number;
995
+ body: string;
996
+ markerPrefix: string;
997
+ spawnFn?: typeof Bun.spawn;
998
+ // Test-only seam, like spawnFn.
999
+ timeoutMs?: number;
1000
+ }): Promise<{ commentId: number; deletedIds: number[] }> {
1001
+ const { operatorRoot, pr, spawnFn } = input;
1002
+ const timeoutMs = input.timeoutMs ?? SKIP_NOTICE_GH_TIMEOUT_MS;
1003
+ const created = await gh(
1004
+ operatorRoot,
1005
+ [
1006
+ "api",
1007
+ "--method",
1008
+ "POST",
1009
+ `repos/{owner}/{repo}/issues/${pr}/comments`,
1010
+ "-F",
1011
+ "body=@-",
1012
+ ],
1013
+ input.body,
1014
+ spawnFn,
1015
+ timeoutMs,
1016
+ );
1017
+ if (!created.ok) {
1018
+ throw new CliError(
1019
+ `gh api (post PR comment) failed: ${created.stderr.trim()}`,
1020
+ );
1021
+ }
1022
+ const commentId = parsePostedCommentId(created.stdout, "PR comment");
1023
+ const deletedIds: number[] = [];
1024
+ const author = postedCommentAuthor(created.stdout);
1025
+ if (author === undefined) {
1026
+ log(
1027
+ "could not tell who posted the new notice — older notices left in place",
1028
+ );
1029
+ return { commentId, deletedIds };
1030
+ }
1031
+ let previous: number[];
1032
+ try {
1033
+ previous = (await fetchPrComments(operatorRoot, pr, { spawnFn, timeoutMs }))
1034
+ .filter(
1035
+ (c) =>
1036
+ c.id !== commentId &&
1037
+ c.user === author &&
1038
+ typeof c.body === "string" &&
1039
+ matchMarkerPrefix(c.body, input.markerPrefix) !== undefined,
1040
+ )
1041
+ .map((c) => c.id);
1042
+ } catch (error) {
1043
+ log(
1044
+ "could not list older notices " +
1045
+ `(${error instanceof Error ? error.message : String(error)}) — the new one was posted`,
1046
+ );
1047
+ return { commentId, deletedIds };
1048
+ }
1049
+ for (const id of previous) {
1050
+ try {
1051
+ const deleted = await gh(
1052
+ operatorRoot,
1053
+ [
1054
+ "api",
1055
+ "--method",
1056
+ "DELETE",
1057
+ `repos/{owner}/{repo}/issues/comments/${id}`,
1058
+ ],
1059
+ undefined,
1060
+ spawnFn,
1061
+ timeoutMs,
1062
+ );
1063
+ if (deleted.ok) {
1064
+ deletedIds.push(id);
1065
+ } else {
1066
+ log(
1067
+ `could not delete the previous notice ${id} ` +
1068
+ `(${deleted.stderr.trim()}) — the new one was posted`,
1069
+ );
1070
+ }
1071
+ } catch (error) {
1072
+ log(
1073
+ `could not delete the previous notice ${id} ` +
1074
+ `(${error instanceof Error ? error.message : String(error)}) — the new one was posted`,
1075
+ );
1076
+ }
1077
+ }
1078
+ return { commentId, deletedIds };
1079
+ }
1080
+
1081
+ function postedCommentAuthor(stdout: string): string | undefined {
1082
+ try {
1083
+ const login = (JSON.parse(stdout) as { user?: { login?: unknown } } | null)
1084
+ ?.user?.login;
1085
+ return typeof login === "string" && login !== "" ? login : undefined;
1086
+ } catch {
1087
+ return undefined;
1088
+ }
1089
+ }
1090
+
1091
+ // --paginate matters: a busy PR accumulates enough comments to push the
1092
+ // pr-hero marker comments off page 1, and a missing comment looks identical
1093
+ // to "nothing declared". API order is preserved verbatim (no sort, no reverse).
1094
+ //
1095
+ // Exported since B3: the watch guard reads the same comments to learn which
1096
+ // heads a pr-hero marker already declares (watch/watch.ts imports this one-way;
1097
+ // pr.ts never imports watch/watch.ts, so the no-mutual-shells rule holds).
1098
+ export async function fetchPrComments(
1099
+ operatorRoot: string,
1100
+ pr: number,
1101
+ options?: { spawnFn?: typeof Bun.spawn; timeoutMs?: number },
1102
+ ): Promise<
1103
+ {
1104
+ id: number;
1105
+ user: string;
1106
+ body: string;
1107
+ created_at?: string;
1108
+ updated_at?: string;
1109
+ }[]
1110
+ > {
1111
+ const result = await gh(
1112
+ operatorRoot,
1113
+ [
1114
+ "api",
1115
+ "--paginate",
1116
+ `repos/{owner}/{repo}/issues/${pr}/comments`,
1117
+ "--jq",
1118
+ ".[] | {id: .id, user: .user.login, body: .body, created_at: .created_at, updated_at: .updated_at}",
1119
+ ],
1120
+ undefined,
1121
+ options?.spawnFn,
1122
+ options?.timeoutMs,
1123
+ );
1124
+ if (!result.ok) {
1125
+ // Live evidence on MusiveTech/musive 2026-08-17: REST GET on
1126
+ // issues/<n>/comments can 404 while POST on the same path and GraphQL
1127
+ // both succeed — posting dies at the pre-flight fetch with no review
1128
+ // published. Fall back to GraphQL so listing tracks the write path.
1129
+ if (is404(result.stderr)) {
1130
+ return fetchPrCommentsGraphql(
1131
+ operatorRoot,
1132
+ pr,
1133
+ options?.spawnFn,
1134
+ options?.timeoutMs,
1135
+ );
1136
+ }
1137
+ throw new CliError(
1138
+ `gh api issues/${pr}/comments failed: ${result.stderr.trim()}`,
1139
+ );
1140
+ }
1141
+ // `--jq` streams one JSON object per line.
1142
+ const comments: {
1143
+ id: number;
1144
+ user: string;
1145
+ body: string;
1146
+ created_at?: string;
1147
+ updated_at?: string;
1148
+ }[] = [];
1149
+ for (const line of result.stdout.split("\n")) {
1150
+ if (line.trim() === "") continue;
1151
+ try {
1152
+ const parsed = JSON.parse(line) as {
1153
+ id: number;
1154
+ user: string;
1155
+ body: string;
1156
+ created_at?: unknown;
1157
+ updated_at?: unknown;
1158
+ };
1159
+ comments.push({
1160
+ id: parsed.id,
1161
+ user: parsed.user,
1162
+ body: parsed.body,
1163
+ ...(typeof parsed.created_at === "string"
1164
+ ? { created_at: parsed.created_at }
1165
+ : {}),
1166
+ ...(typeof parsed.updated_at === "string"
1167
+ ? { updated_at: parsed.updated_at }
1168
+ : {}),
1169
+ });
1170
+ } catch {
1171
+ throw new CliError(`unparseable line from gh api: ${line.slice(0, 120)}`);
1172
+ }
1173
+ }
1174
+ return comments;
1175
+ }
1176
+
1177
+ // ---------------------------------------------------------------------------
1178
+ // Inline review surface (ROADMAP B6, WU4/WU5) — the fetcher, the atomic
1179
+ // review submission with its 422 recovery, and the per-finding issue
1180
+ // comment. pr/inline.ts plans WHAT to post (pure); everything below executes
1181
+ // that plan and is the only place in the engine allowed to.
1182
+
1183
+ // Review-level (inline) comments, as opposed to fetchPrComments's top-level
1184
+ // issue comments — a DIFFERENT GitHub endpoint (`pulls/<n>/comments`, not
1185
+ // `issues/<n>/comments`). Shape-identical to fetchPrComments on purpose
1186
+ // (same --paginate + --jq style, same loud parse failure): the two fetchers
1187
+ // read two different comment streams the same way, so a bug in one parsing
1188
+ // discipline is not a bug the other could hide.
1189
+ //
1190
+ // `in_reply_to_id` is what `pr-hero triage reply` uses to bind a triage
1191
+ // response to its finding thread (W1). The finder still only needs
1192
+ // `path`/`line` plus the marker; projecting the reply-to id here costs
1193
+ // nothing and means the bind path does not make a second fetch shape.
1194
+ export interface PrReviewComment {
1195
+ id: number;
1196
+ user: string;
1197
+ body: string;
1198
+ path: string;
1199
+ line: number | null;
1200
+ original_line: number | null;
1201
+ in_reply_to_id: number | null;
1202
+ created_at?: string;
1203
+ }
1204
+
1205
+ export async function fetchPrReviewComments(
1206
+ operatorRoot: string,
1207
+ pr: number,
1208
+ options?: { spawnFn?: typeof Bun.spawn; timeoutMs?: number },
1209
+ ): Promise<PrReviewComment[]> {
1210
+ const result = await gh(
1211
+ operatorRoot,
1212
+ [
1213
+ "api",
1214
+ "--paginate",
1215
+ `repos/{owner}/{repo}/pulls/${pr}/comments`,
1216
+ "--jq",
1217
+ ".[] | {id: .id, user: .user.login, body: .body, path: .path, " +
1218
+ "line: .line, original_line: .original_line, " +
1219
+ "in_reply_to_id: .in_reply_to_id, created_at: .created_at}",
1220
+ ],
1221
+ undefined,
1222
+ options?.spawnFn,
1223
+ options?.timeoutMs,
1224
+ );
1225
+ if (!result.ok) {
1226
+ if (is404(result.stderr)) {
1227
+ return fetchPrReviewCommentsGraphql(
1228
+ operatorRoot,
1229
+ pr,
1230
+ options?.spawnFn,
1231
+ options?.timeoutMs,
1232
+ );
1233
+ }
1234
+ throw new CliError(
1235
+ `gh api pulls/${pr}/comments failed: ${result.stderr.trim()}`,
1236
+ );
1237
+ }
1238
+ const comments: PrReviewComment[] = [];
1239
+ for (const line of result.stdout.split("\n")) {
1240
+ if (line.trim() === "") continue;
1241
+ try {
1242
+ comments.push(JSON.parse(line) as PrReviewComment);
1243
+ } catch {
1244
+ throw new CliError(`unparseable line from gh api: ${line.slice(0, 120)}`);
1245
+ }
1246
+ }
1247
+ return comments;
1248
+ }
1249
+
1250
+ // The tier a posted finding comment states on its visible badge line, or
1251
+ // nothing. The marker carries no tier, so this is the only record of it.
1252
+ // parseFindingCommentBadge is all-or-nothing: a body it cannot read yields
1253
+ // no key at all, which the matcher treats as unknown (today's behavior),
1254
+ // never as a guessed tier.
1255
+ function postedTier(body: string): { tier?: "blocking" | "advisory" } {
1256
+ const tier = parseFindingCommentBadge(body)?.tier;
1257
+ return tier === undefined ? {} : { tier };
1258
+ }
1259
+
1260
+ // Both channels pr-hero's own per-finding comments can live in, reduced to
1261
+ // pr/inline.ts's PostedFindingComment shape. A comment that does not parse as a
1262
+ // finding marker is silently excluded — this is where the two marker
1263
+ // prefixes' disjointness (pr/preflight.ts) actually pays for itself: the
1264
+ // summary comment's `<!-- pr-hero-report ` marker never parses as a
1265
+ // `<!-- pr-hero-finding ` one, so it drops out of this list without any
1266
+ // special-casing, and a human's reply (any shape) drops out the same way.
1267
+ export async function fetchPostedFindingComments(
1268
+ operatorRoot: string,
1269
+ pr: number,
1270
+ options?: { spawnFn?: typeof Bun.spawn; timeoutMs?: number },
1271
+ ): Promise<PostedFindingComment[]> {
1272
+ const [reviewComments, issueComments] = await Promise.all([
1273
+ fetchPrReviewComments(operatorRoot, pr, options),
1274
+ fetchPrComments(operatorRoot, pr, options),
1275
+ ]);
1276
+ const out: PostedFindingComment[] = [];
1277
+ for (const comment of reviewComments) {
1278
+ const marker = parseFindingMarker(comment.body);
1279
+ if (marker === null) continue;
1280
+ out.push({
1281
+ id: comment.id,
1282
+ channel: "review",
1283
+ marker,
1284
+ livePath: comment.path,
1285
+ liveLine: comment.line ?? undefined,
1286
+ ...postedTier(comment.body),
1287
+ ...(comment.created_at === undefined
1288
+ ? {}
1289
+ : { created_at: comment.created_at }),
1290
+ });
1291
+ }
1292
+ for (const comment of issueComments) {
1293
+ const marker = parseFindingMarker(comment.body);
1294
+ if (marker === null) continue;
1295
+ out.push({
1296
+ id: comment.id,
1297
+ channel: "issue",
1298
+ marker,
1299
+ ...postedTier(comment.body),
1300
+ ...(comment.created_at === undefined
1301
+ ? {}
1302
+ : { created_at: comment.created_at }),
1303
+ });
1304
+ }
1305
+ return out;
1306
+ }
1307
+
1308
+ // gh api prints "<message> (HTTP <code>)" on stderr for any non-2xx
1309
+ // response. Matching only the status code — never the message, which
1310
+ // GitHub varies by cause ("Unprocessable Entity", or a specific field
1311
+ // error) — is what lets the SAME recovery apply whether the rejection is
1312
+ // "this comment could not anchor" or "you already have a pending review"
1313
+ // (a leftover from a prior crashed run): the spec explicitly rules out
1314
+ // reason-string special-casing (design D1), because GitHub's 422 body does
1315
+ // not reliably name which comment failed.
1316
+ function is422(stderr: string): boolean {
1317
+ return /\(HTTP 422\)/.test(stderr);
1318
+ }
1319
+
1320
+ function is404(stderr: string): boolean {
1321
+ return /\(HTTP 404\)/.test(stderr);
1322
+ }
1323
+
1324
+ // GraphQL fallback for fetchPrComments — same shape the REST --jq path
1325
+ // produces. Variable names are repoOwner/repoName so they cannot collide
1326
+ // with gh -f name= interpolating $name inside the query document.
1327
+ const PR_ISSUE_COMMENTS_QUERY =
1328
+ "query($repoOwner:String!,$repoName:String!,$number:Int!,$cursor:String){" +
1329
+ "repository(owner:$repoOwner,name:$repoName){pullRequest(number:$number){" +
1330
+ "comments(first:100,after:$cursor){" +
1331
+ "pageInfo{endCursor hasNextPage}" +
1332
+ "nodes{databaseId body createdAt updatedAt author{login}}}}}}";
1333
+
1334
+ const PR_REVIEW_COMMENTS_QUERY =
1335
+ "query($repoOwner:String!,$repoName:String!,$number:Int!,$cursor:String){" +
1336
+ "repository(owner:$repoOwner,name:$repoName){pullRequest(number:$number){" +
1337
+ `reviewThreads(first:${THREAD_PAGE_SIZE},after:$cursor){` +
1338
+ "pageInfo{endCursor hasNextPage}" +
1339
+ "nodes{comments(first:100){nodes{" +
1340
+ "fullDatabaseId body createdAt author{login __typename} path line originalLine " +
1341
+ "replyTo{fullDatabaseId}}}}}}}}";
1342
+
1343
+ // Parses `gh api repos/.../compare/{base}...{head}` — filenames only.
1344
+ export function parseCompareChangedFiles(stdout: string): string[] {
1345
+ return parseCompareChangedFilesWithStatus(stdout).map((entry) => entry.path);
1346
+ }
1347
+
1348
+ export type CompareChangedFileStatus =
1349
+ | "added"
1350
+ | "modified"
1351
+ | "removed"
1352
+ | "renamed";
1353
+
1354
+ export interface CompareChangedFile {
1355
+ path: string;
1356
+ status: CompareChangedFileStatus;
1357
+ }
1358
+
1359
+ const COMPARE_CHANGED_FILE_STATUSES = new Set<CompareChangedFileStatus>([
1360
+ "added",
1361
+ "modified",
1362
+ "removed",
1363
+ "renamed",
1364
+ ]);
1365
+
1366
+ function asCompareChangedFileStatus(
1367
+ value: unknown,
1368
+ ): CompareChangedFileStatus | null {
1369
+ if (typeof value !== "string") return null;
1370
+ return (COMPARE_CHANGED_FILE_STATUSES as ReadonlySet<string>).has(value)
1371
+ ? (value as CompareChangedFileStatus)
1372
+ : null;
1373
+ }
1374
+
1375
+ // Parses `gh api repos/.../compare/{base}...{head}` — filenames and status.
1376
+ export function parseCompareChangedFilesWithStatus(
1377
+ stdout: string,
1378
+ ): CompareChangedFile[] {
1379
+ let parsed: unknown;
1380
+ try {
1381
+ parsed = JSON.parse(stdout);
1382
+ } catch {
1383
+ throw new CliError(
1384
+ `gh api compare returned invalid JSON: ${stdout.slice(0, 120)}`,
1385
+ );
1386
+ }
1387
+ if (typeof parsed !== "object" || parsed === null) {
1388
+ throw new CliError("gh api compare returned no object");
1389
+ }
1390
+ const files = (parsed as { files?: unknown }).files;
1391
+ if (!Array.isArray(files)) {
1392
+ throw new CliError("gh api compare returned no files list");
1393
+ }
1394
+ const paths: CompareChangedFile[] = [];
1395
+ for (const entry of files) {
1396
+ if (typeof entry !== "object" || entry === null) continue;
1397
+ const record = entry as { filename?: unknown; status?: unknown };
1398
+ const filename = record.filename;
1399
+ const status = asCompareChangedFileStatus(record.status) ?? "modified";
1400
+ if (typeof filename === "string" && filename.length > 0) {
1401
+ paths.push({ path: filename, status });
1402
+ }
1403
+ }
1404
+ return paths;
1405
+ }
1406
+
1407
+ export async function ghCompareChangedFiles(
1408
+ operatorRoot: string,
1409
+ base: string,
1410
+ head: string,
1411
+ options?: { spawnFn?: typeof Bun.spawn },
1412
+ ): Promise<string[]> {
1413
+ const files = await ghCompareChangedFilesWithStatus(
1414
+ operatorRoot,
1415
+ base,
1416
+ head,
1417
+ options,
1418
+ );
1419
+ return files.map((entry) => entry.path);
1420
+ }
1421
+
1422
+ export async function ghCompareChangedFilesWithStatus(
1423
+ operatorRoot: string,
1424
+ base: string,
1425
+ head: string,
1426
+ options?: { spawnFn?: typeof Bun.spawn },
1427
+ ): Promise<CompareChangedFile[]> {
1428
+ const repo = await ghRepoOwnerName(operatorRoot, options?.spawnFn);
1429
+ const result = await gh(
1430
+ operatorRoot,
1431
+ ["api", `repos/${repo.owner}/${repo.name}/compare/${base}...${head}`],
1432
+ undefined,
1433
+ options?.spawnFn,
1434
+ );
1435
+ if (!result.ok) {
1436
+ throw new CliError(`gh api compare failed: ${result.stderr.trim()}`);
1437
+ }
1438
+ return parseCompareChangedFilesWithStatus(result.stdout);
1439
+ }
1440
+
1441
+ // The login's permission on the checkout's repository, or null when gh could
1442
+ // not answer (5xx, rate limit, no network). A 404 is GitHub's answer for a
1443
+ // login that is not a collaborator, so it is "none", not null. Callers that
1444
+ // let a permission withhold a review treat null as "no permission".
1445
+ export async function ghCollaboratorPermission(
1446
+ operatorRoot: string,
1447
+ login: string,
1448
+ options?: { spawnFn?: typeof Bun.spawn; timeoutMs?: number },
1449
+ ): Promise<string | null> {
1450
+ const result = await gh(
1451
+ operatorRoot,
1452
+ [
1453
+ "api",
1454
+ `repos/{owner}/{repo}/collaborators/${encodeURIComponent(login)}/permission`,
1455
+ "--jq",
1456
+ ".permission",
1457
+ ],
1458
+ undefined,
1459
+ options?.spawnFn,
1460
+ options?.timeoutMs,
1461
+ );
1462
+ if (!result.ok) {
1463
+ return result.stderr.includes("HTTP 404") ? "none" : null;
1464
+ }
1465
+ const permission = result.stdout.trim();
1466
+ return permission === "" ? null : permission;
1467
+ }
1468
+
1469
+ const COMPLETED_WORKFLOW_CONCLUSIONS = new Set(["success", "failure"]);
1470
+
1471
+ // Distinct head SHAs from completed pr-hero workflow runs on a branch.
1472
+ export function parsePrHeroWorkflowRunHeads(stdout: string): Set<string> {
1473
+ let parsed: unknown;
1474
+ try {
1475
+ parsed = JSON.parse(stdout);
1476
+ } catch {
1477
+ throw new CliError(
1478
+ `gh run list returned invalid JSON: ${stdout.slice(0, 120)}`,
1479
+ );
1480
+ }
1481
+ if (!Array.isArray(parsed)) {
1482
+ throw new CliError("gh run list must return a JSON array");
1483
+ }
1484
+ const heads = new Set<string>();
1485
+ for (const entry of parsed) {
1486
+ if (typeof entry !== "object" || entry === null) continue;
1487
+ const record = entry as { headSha?: unknown; conclusion?: unknown };
1488
+ const conclusion = record.conclusion;
1489
+ if (
1490
+ typeof conclusion !== "string" ||
1491
+ !COMPLETED_WORKFLOW_CONCLUSIONS.has(conclusion)
1492
+ ) {
1493
+ continue;
1494
+ }
1495
+ const headSha = record.headSha;
1496
+ if (typeof headSha === "string" && isFullCommitId(headSha)) {
1497
+ heads.add(headSha);
1498
+ }
1499
+ }
1500
+ return heads;
1501
+ }
1502
+
1503
+ // The workflow file this run belongs to, from GITHUB_WORKFLOW_REF
1504
+ // (`owner/repo/.github/workflows/<file>@<ref>`), so a repo that renamed or kept
1505
+ // its file is asked about its own file. The legacy dispatch-only force workflow
1506
+ // is not the review workflow: its runs are not the review runs the gate counts,
1507
+ // so a run started from it falls through to the lookup by name.
1508
+ export function workflowFileFromRef(
1509
+ ref: string | undefined,
1510
+ ): string | undefined {
1511
+ if (ref === undefined) return undefined;
1512
+ const match = /\/\.github\/workflows\/([^/@]+\.ya?ml)@/.exec(ref);
1513
+ const file = match?.[1];
1514
+ if (file === undefined || file === CI_FORCE_WORKFLOW_FILE) return undefined;
1515
+ return file;
1516
+ }
1517
+
1518
+ // `gh run list --workflow <file>` for a file the repository does not have.
1519
+ function isWorkflowNotFound(stderr: string): boolean {
1520
+ return /could not find any workflows named|workflow .* not found|HTTP 404/i.test(
1521
+ stderr,
1522
+ );
1523
+ }
1524
+
1525
+ export async function ghPrHeroWorkflowRunHeads(
1526
+ operatorRoot: string,
1527
+ branch: string,
1528
+ options?: { spawnFn?: typeof Bun.spawn },
1529
+ ): Promise<Set<string>> {
1530
+ // Inside the action the run knows its own workflow file. Anywhere else the
1531
+ // new name is asked first and the pre-rename one only when the repository
1532
+ // has no such workflow; any other failure keeps its error.
1533
+ const derived = workflowFileFromRef(process.env.GITHUB_WORKFLOW_REF);
1534
+ const candidates =
1535
+ derived === undefined
1536
+ ? [WORKFLOW_FILE_NAME, LEGACY_WORKFLOW_FILE_NAME]
1537
+ : [derived];
1538
+ let failure = "";
1539
+ for (const [index, file] of candidates.entries()) {
1540
+ const result = await gh(
1541
+ operatorRoot,
1542
+ [
1543
+ "run",
1544
+ "list",
1545
+ "--workflow",
1546
+ file,
1547
+ "--branch",
1548
+ branch,
1549
+ "--json",
1550
+ "headSha,conclusion",
1551
+ ],
1552
+ undefined,
1553
+ options?.spawnFn,
1554
+ );
1555
+ if (result.ok) return parsePrHeroWorkflowRunHeads(result.stdout);
1556
+ failure = result.stderr.trim();
1557
+ const hasNext = index < candidates.length - 1;
1558
+ if (!hasNext || !isWorkflowNotFound(result.stderr)) break;
1559
+ }
1560
+ throw new CliError(`gh run list failed: ${failure}`);
1561
+ }
1562
+
1563
+ async function ghGraphql(
1564
+ operatorRoot: string,
1565
+ query: string,
1566
+ variables: Record<string, string | number>,
1567
+ what: string,
1568
+ spawnFn?: typeof Bun.spawn,
1569
+ timeoutMs?: number,
1570
+ ): Promise<string> {
1571
+ assertBalancedGraphql(query, what);
1572
+ const args = ["api", "graphql", "-f", `query=${query}`];
1573
+ for (const [key, value] of Object.entries(variables)) {
1574
+ const flag = typeof value === "number" ? "-F" : "-f";
1575
+ args.push(flag, `${key}=${value}`);
1576
+ }
1577
+ const result = await gh(operatorRoot, args, undefined, spawnFn, timeoutMs);
1578
+ if (!result.ok) {
1579
+ throw new CliError(
1580
+ `gh api graphql (${what}) failed: ${result.stderr.trim()}`,
1581
+ );
1582
+ }
1583
+ return result.stdout;
1584
+ }
1585
+
1586
+ function graphqlLogin(value: unknown): string {
1587
+ if (typeof value !== "object" || value === null) return "";
1588
+ const login = (value as { login?: unknown }).login;
1589
+ return typeof login === "string" ? login : "";
1590
+ }
1591
+
1592
+ // WHY a bot gets the REST spelling: REST reports a GitHub App as
1593
+ // `github-actions[bot]`, while GraphQL reports the bare login. Without this the
1594
+ // CI adjudicator's login would differ between the two read paths.
1595
+ function graphqlReviewLogin(value: unknown): string {
1596
+ const login = graphqlLogin(value);
1597
+ const typename =
1598
+ typeof value === "object" && value !== null
1599
+ ? (value as { __typename?: unknown }).__typename
1600
+ : undefined;
1601
+ return typename === "Bot" && login !== "" ? `${login}[bot]` : login;
1602
+ }
1603
+
1604
+ function issueCommentsFromNodes(nodes: unknown[]): {
1605
+ id: number;
1606
+ user: string;
1607
+ body: string;
1608
+ created_at?: string;
1609
+ updated_at?: string;
1610
+ }[] {
1611
+ const comments: {
1612
+ id: number;
1613
+ user: string;
1614
+ body: string;
1615
+ created_at?: string;
1616
+ updated_at?: string;
1617
+ }[] = [];
1618
+ for (const node of nodes) {
1619
+ if (typeof node !== "object" || node === null) continue;
1620
+ const record = node as {
1621
+ databaseId?: unknown;
1622
+ body?: unknown;
1623
+ createdAt?: unknown;
1624
+ updatedAt?: unknown;
1625
+ author?: unknown;
1626
+ };
1627
+ const id = graphqlDatabaseId(record.databaseId);
1628
+ if (id === null) continue;
1629
+ comments.push({
1630
+ id,
1631
+ user: graphqlLogin(record.author),
1632
+ body: typeof record.body === "string" ? record.body : "",
1633
+ ...(typeof record.createdAt === "string"
1634
+ ? { created_at: record.createdAt }
1635
+ : {}),
1636
+ ...(typeof record.updatedAt === "string"
1637
+ ? { updated_at: record.updatedAt }
1638
+ : {}),
1639
+ });
1640
+ }
1641
+ return comments;
1642
+ }
1643
+
1644
+ interface IssueCommentsGraphqlPage {
1645
+ nodes: unknown[];
1646
+ hasNextPage: boolean;
1647
+ endCursor: string | null;
1648
+ }
1649
+
1650
+ function parseIssueCommentsGraphqlPage(
1651
+ stdout: string,
1652
+ ): IssueCommentsGraphqlPage {
1653
+ let parsed: unknown = null;
1654
+ try {
1655
+ parsed = JSON.parse(stdout);
1656
+ } catch {
1657
+ throw new CliError(
1658
+ "gh api graphql (issueComments) returned invalid JSON: " +
1659
+ stdout.slice(0, 120),
1660
+ );
1661
+ }
1662
+ const connection = (
1663
+ parsed as {
1664
+ data?: {
1665
+ repository?: {
1666
+ pullRequest?: { comments?: unknown };
1667
+ };
1668
+ };
1669
+ } | null
1670
+ )?.data?.repository?.pullRequest?.comments;
1671
+ if (typeof connection !== "object" || connection === null) {
1672
+ throw new CliError(
1673
+ "gh api graphql (issueComments) returned no comment list",
1674
+ );
1675
+ }
1676
+ const record = connection as Record<string, unknown>;
1677
+ const nodes = record.nodes;
1678
+ if (!Array.isArray(nodes)) {
1679
+ throw new CliError(
1680
+ "gh api graphql (issueComments) returned no comment list",
1681
+ );
1682
+ }
1683
+ const pageInfo = record.pageInfo;
1684
+ if (typeof pageInfo !== "object" || pageInfo === null) {
1685
+ throw new CliError("gh api graphql (issueComments) returned no pageInfo");
1686
+ }
1687
+ const hasNextPage =
1688
+ (pageInfo as { hasNextPage?: unknown }).hasNextPage === true;
1689
+ const endCursorRaw = (pageInfo as { endCursor?: unknown }).endCursor;
1690
+ const endCursor =
1691
+ typeof endCursorRaw === "string" && endCursorRaw.length > 0
1692
+ ? endCursorRaw
1693
+ : null;
1694
+ if (hasNextPage && endCursor === null) {
1695
+ throw new CliError(
1696
+ "gh api graphql (issueComments) hasNextPage is true but endCursor is missing",
1697
+ );
1698
+ }
1699
+ return { nodes, hasNextPage, endCursor };
1700
+ }
1701
+
1702
+ async function fetchPrCommentsGraphql(
1703
+ operatorRoot: string,
1704
+ pr: number,
1705
+ spawnFn?: typeof Bun.spawn,
1706
+ timeoutMs?: number,
1707
+ ): Promise<
1708
+ {
1709
+ id: number;
1710
+ user: string;
1711
+ body: string;
1712
+ created_at?: string;
1713
+ updated_at?: string;
1714
+ }[]
1715
+ > {
1716
+ assertBalancedGraphql(PR_ISSUE_COMMENTS_QUERY, "issueComments");
1717
+ const repo = await ghRepoOwnerName(operatorRoot, spawnFn, timeoutMs);
1718
+ const comments: {
1719
+ id: number;
1720
+ user: string;
1721
+ body: string;
1722
+ created_at?: string;
1723
+ updated_at?: string;
1724
+ }[] = [];
1725
+ let cursor: string | null = null;
1726
+ let hasNextPage = true;
1727
+ let pageCount = 0;
1728
+ while (hasNextPage) {
1729
+ pageCount++;
1730
+ const variables: Record<string, string | number> = {
1731
+ repoOwner: repo.owner,
1732
+ repoName: repo.name,
1733
+ number: pr,
1734
+ };
1735
+ if (cursor !== null) {
1736
+ variables.cursor = cursor;
1737
+ }
1738
+ const stdout = await ghGraphql(
1739
+ operatorRoot,
1740
+ PR_ISSUE_COMMENTS_QUERY,
1741
+ variables,
1742
+ "issueComments",
1743
+ spawnFn,
1744
+ timeoutMs,
1745
+ );
1746
+ const page = parseIssueCommentsGraphqlPage(stdout);
1747
+ comments.push(...issueCommentsFromNodes(page.nodes));
1748
+ hasNextPage = page.hasNextPage;
1749
+ cursor = page.endCursor;
1750
+ if (hasNextPage && pageCount >= GRAPHQL_COMMENT_MAX_PAGES) {
1751
+ throw new CommentsTruncatedError(
1752
+ `gh api graphql (issueComments) exceeded ${GRAPHQL_COMMENT_MAX_PAGES} pages`,
1753
+ );
1754
+ }
1755
+ }
1756
+ return comments;
1757
+ }
1758
+
1759
+ interface ReviewCommentsGraphqlPage {
1760
+ nodes: unknown[];
1761
+ hasNextPage: boolean;
1762
+ endCursor: string | null;
1763
+ }
1764
+
1765
+ function parseReviewCommentsGraphqlPage(
1766
+ stdout: string,
1767
+ ): ReviewCommentsGraphqlPage {
1768
+ let parsed: unknown = null;
1769
+ try {
1770
+ parsed = JSON.parse(stdout);
1771
+ } catch {
1772
+ throw new CliError(
1773
+ "gh api graphql (reviewComments) returned invalid JSON: " +
1774
+ stdout.slice(0, 120),
1775
+ );
1776
+ }
1777
+ const connection = (
1778
+ parsed as {
1779
+ data?: {
1780
+ repository?: {
1781
+ pullRequest?: { reviewThreads?: unknown };
1782
+ };
1783
+ };
1784
+ } | null
1785
+ )?.data?.repository?.pullRequest?.reviewThreads;
1786
+ if (typeof connection !== "object" || connection === null) {
1787
+ throw new CliError(
1788
+ "gh api graphql (reviewComments) returned no thread list",
1789
+ );
1790
+ }
1791
+ const record = connection as Record<string, unknown>;
1792
+ const nodes = record.nodes;
1793
+ if (!Array.isArray(nodes)) {
1794
+ throw new CliError(
1795
+ "gh api graphql (reviewComments) returned no thread list",
1796
+ );
1797
+ }
1798
+ const pageInfo = record.pageInfo;
1799
+ if (typeof pageInfo !== "object" || pageInfo === null) {
1800
+ throw new CliError("gh api graphql (reviewComments) returned no pageInfo");
1801
+ }
1802
+ const hasNextPage =
1803
+ (pageInfo as { hasNextPage?: unknown }).hasNextPage === true;
1804
+ const endCursorRaw = (pageInfo as { endCursor?: unknown }).endCursor;
1805
+ const endCursor =
1806
+ typeof endCursorRaw === "string" && endCursorRaw.length > 0
1807
+ ? endCursorRaw
1808
+ : null;
1809
+ if (hasNextPage && endCursor === null) {
1810
+ throw new CliError(
1811
+ "gh api graphql (reviewComments) hasNextPage is true but endCursor is missing",
1812
+ );
1813
+ }
1814
+ return { nodes, hasNextPage, endCursor };
1815
+ }
1816
+
1817
+ function reviewCommentsFromThreadNodes(
1818
+ threadNodes: unknown[],
1819
+ ): PrReviewComment[] {
1820
+ const comments: PrReviewComment[] = [];
1821
+ for (const thread of threadNodes) {
1822
+ if (typeof thread !== "object" || thread === null) continue;
1823
+ const commentNodes = (thread as { comments?: { nodes?: unknown } }).comments
1824
+ ?.nodes;
1825
+ if (!Array.isArray(commentNodes)) continue;
1826
+ for (const node of commentNodes) {
1827
+ if (typeof node !== "object" || node === null) continue;
1828
+ const record = node as {
1829
+ fullDatabaseId?: unknown;
1830
+ body?: unknown;
1831
+ createdAt?: unknown;
1832
+ author?: unknown;
1833
+ path?: unknown;
1834
+ line?: unknown;
1835
+ originalLine?: unknown;
1836
+ replyTo?: { fullDatabaseId?: unknown } | null;
1837
+ };
1838
+ const id = graphqlDatabaseId(record.fullDatabaseId);
1839
+ if (id === null) continue;
1840
+ const line =
1841
+ typeof record.line === "number" && Number.isInteger(record.line)
1842
+ ? record.line
1843
+ : null;
1844
+ const originalLine =
1845
+ typeof record.originalLine === "number" &&
1846
+ Number.isInteger(record.originalLine)
1847
+ ? record.originalLine
1848
+ : null;
1849
+ const replyToId = graphqlDatabaseId(record.replyTo?.fullDatabaseId);
1850
+ comments.push({
1851
+ id,
1852
+ user: graphqlReviewLogin(record.author),
1853
+ body: typeof record.body === "string" ? record.body : "",
1854
+ path: typeof record.path === "string" ? record.path : "",
1855
+ line,
1856
+ original_line: originalLine,
1857
+ in_reply_to_id: replyToId,
1858
+ ...(typeof record.createdAt === "string"
1859
+ ? { created_at: record.createdAt }
1860
+ : {}),
1861
+ });
1862
+ }
1863
+ }
1864
+ return comments;
1865
+ }
1866
+
1867
+ async function fetchPrReviewCommentsGraphql(
1868
+ operatorRoot: string,
1869
+ pr: number,
1870
+ spawnFn?: typeof Bun.spawn,
1871
+ timeoutMs?: number,
1872
+ ): Promise<PrReviewComment[]> {
1873
+ assertBalancedGraphql(PR_REVIEW_COMMENTS_QUERY, "reviewComments");
1874
+ const repo = await ghRepoOwnerName(operatorRoot, spawnFn, timeoutMs);
1875
+ const comments: PrReviewComment[] = [];
1876
+ let cursor: string | null = null;
1877
+ let hasNextPage = true;
1878
+ let pageCount = 0;
1879
+ while (hasNextPage) {
1880
+ pageCount++;
1881
+ const variables: Record<string, string | number> = {
1882
+ repoOwner: repo.owner,
1883
+ repoName: repo.name,
1884
+ number: pr,
1885
+ };
1886
+ if (cursor !== null) {
1887
+ variables.cursor = cursor;
1888
+ }
1889
+ const stdout = await ghGraphql(
1890
+ operatorRoot,
1891
+ PR_REVIEW_COMMENTS_QUERY,
1892
+ variables,
1893
+ "reviewComments",
1894
+ spawnFn,
1895
+ timeoutMs,
1896
+ );
1897
+ const page = parseReviewCommentsGraphqlPage(stdout);
1898
+ comments.push(...reviewCommentsFromThreadNodes(page.nodes));
1899
+ hasNextPage = page.hasNextPage;
1900
+ cursor = page.endCursor;
1901
+ if (hasNextPage && pageCount >= GRAPHQL_COMMENT_MAX_PAGES) {
1902
+ throw new CommentsTruncatedError(
1903
+ `gh api graphql (reviewComments) exceeded ${GRAPHQL_COMMENT_MAX_PAGES} pages`,
1904
+ );
1905
+ }
1906
+ }
1907
+ return comments;
1908
+ }
1909
+
1910
+ export interface ReviewSubmissionOutcome {
1911
+ // "posted": every finding in `findings` is now in the one review.
1912
+ // "demoted": the review was rejected (422); `findings` is the subset of
1913
+ // the ORIGINAL submission still classified fresh after a FULL re-match —
1914
+ // the caller puts these in the summary Outside Diff bucket (issues
1915
+ // #16/#17) instead of posting them as issue comments.
1916
+ //
1917
+ // WHY a full re-match, not a re-match over `findings` alone (CRIT-A,
1918
+ // verify-report-pr3 #3305 — the bug the previous `consumedCommentIds`
1919
+ // design left in place): matchPostedFindings is one-to-one only across the
1920
+ // finding list it is handed. Re-running it over `findings` — a SUBSET of
1921
+ // what buildPostPlan matched in the first place — can DISSOLVE A TIE: a
1922
+ // comment the full plan adjudicated to some OTHER, already-persisting
1923
+ // finding becomes the sole remaining candidate here and silently swallows
1924
+ // a genuinely new finding, even though the plan itself resolved that exact
1925
+ // tie by posting fresh. Re-matching the FULL finding list (`allFindings`,
1926
+ // the exact set the plan matched) against the fresh fetch reproduces the
1927
+ // plan's own adjudication byte-for-byte whenever GitHub created nothing —
1928
+ // the common case, since a 422 means the review was never persisted — and
1929
+ // diverges from it only where GitHub genuinely created something between
1930
+ // the plan and this call, which is the only case the recovery should
1931
+ // differ in at all. Tie- and order-independent by construction: unlike the
1932
+ // old subset-and-exclude approach, nothing here depends on which findings
1933
+ // happened to be excluded first.
1934
+ outcome: "posted" | "demoted";
1935
+ findings: Finding[];
1936
+ }
1937
+
1938
+ // The one atomic review submission (spec "One review submission for
1939
+ // anchorable findings"), plus its 422 recovery (spec "GitHub is the anchor
1940
+ // authority", design D1). `findings` is the plan's `reviewComments` — the
1941
+ // set pr/inline.ts already classified anchorable AND unmatched to a prior
1942
+ // comment; an empty set never reaches gh at all (spec "Zero anchorable
1943
+ // findings": an empty `comments[]` review is never sent).
1944
+ //
1945
+ // WHY re-fetch-and-rematch, not fail-loud, not parse-and-retry-the-offender,
1946
+ // not N separate POSTs (design D1, rejected alternatives kept here because
1947
+ // they will keep sounding reasonable to the next person who reads this):
1948
+ // fail-loud means a review that already cost real hunter/refuter money says
1949
+ // NOTHING on the PR — the worst outcome available. Parsing the 422 to retry
1950
+ // only the offending comment assumes GitHub's error body names it reliably;
1951
+ // it does not (verified against `gh api` 2026-08-10 — the response is a
1952
+ // generic "Unprocessable Entity" with, at best, a field-level error array
1953
+ // that does not carry the comments[] index). N separate
1954
+ // `POST pulls/<n>/comments` calls trade the one atomicity problem for a
1955
+ // worse one: N GitHub notifications instead of one review, and a partial
1956
+ // failure midway leaves some findings posted and others not, with no single
1957
+ // state to reconcile against. Re-fetching and re-running matchPostedFindings
1958
+ // — the SAME function an ordinary second run already uses for cross-run
1959
+ // identity — means the recovery is not a special code path at all: whatever
1960
+ // the live PR already carries is `persist`, whatever it does not is
1961
+ // `fresh`, and only `fresh` reaches the caller, this time for the summary
1962
+ // Outside Diff bucket (issues #16/#17) rather than a second review attempt.
1963
+ // The matcher doubles as the recovery mechanism.
1964
+ export async function postPrReview(input: {
1965
+ operatorRoot: string;
1966
+ pr: number;
1967
+ headSha: string;
1968
+ findings: Finding[];
1969
+ // The FULL finding list this run is considering — the exact set
1970
+ // buildPostPlan matched against `posted` to produce the plan in the first
1971
+ // place (not just `findings`, the anchorable-fresh subset). REQUIRED, not
1972
+ // optional, so a caller cannot silently narrow it and reintroduce CRIT-A —
1973
+ // see ReviewSubmissionOutcome's WHY above for the failure this closes.
1974
+ allFindings: PrHeroFindingRef[];
1975
+ webUrl?: string;
1976
+ spawnFn?: typeof Bun.spawn;
1977
+ // Bounds the submission and its 422 recovery reads (F004). Defaults to the
1978
+ // posting bound; a timeout is NOT retried, because the submission may already
1979
+ // have landed and a second POST would duplicate the review.
1980
+ timeoutMs?: number;
1981
+ }): Promise<ReviewSubmissionOutcome> {
1982
+ if (input.findings.length === 0) {
1983
+ return { outcome: "posted", findings: [] };
1984
+ }
1985
+ const body = {
1986
+ // GitHub #39 (ROADMAP-DOORDASH M1). WITHOUT this, `POST
1987
+ // .../pulls/<n>/reviews` resolves every `line` against the PR's LATEST
1988
+ // commit at post time — not the commit the lines were computed on. A
1989
+ // review takes minutes; an author who pushes while it runs gets one of
1990
+ // two outcomes, and the silent one is the reason this line exists: a
1991
+ // finding's line that still EXISTS in the newer diff but now means
1992
+ // something else anchors cleanly to code the finding was never about.
1993
+ // No error, no signal, nothing a reader could tell apart from a real
1994
+ // finding. Pinned, GitHub anchors to the reviewed commit and marks the
1995
+ // comment outdated ITSELF once the lines move — the reconciliation the
1996
+ // engine would otherwise have to invent.
1997
+ //
1998
+ // The pin also creates a NEW 422 class, and that is the pin working
1999
+ // rather than a regression: if `headSha` is rewritten out of the PR
2000
+ // mid-run (a force-push), GitHub rejects the whole submission because
2001
+ // the commit is no longer part of it, where the unpinned code would
2002
+ // have silently posted against whatever replaced it. The recovery below
2003
+ // is exactly right for that — re-fetch, re-match, demote the survivors
2004
+ // into the summary's Comments Outside Diff bucket. Degraded, honest,
2005
+ // and never a hard failure.
2006
+ commit_id: input.headSha,
2007
+ event: "COMMENT",
2008
+ comments: input.findings.map((finding) => ({
2009
+ path: finding.path,
2010
+ line: finding.line,
2011
+ body: renderInlineComment(finding, input.headSha, input.webUrl),
2012
+ })),
2013
+ };
2014
+ // `--input -`, not `-F`: gh's `-F`/`-f` field composition has no way to
2015
+ // express an ARRAY of objects, and comments[] is exactly that. The whole
2016
+ // request body travels on stdin as one JSON document — same ARG_MAX/no-
2017
+ // shell reasoning as postPrComment's `-F body=@-`, just for a body gh
2018
+ // cannot compose from flags at all.
2019
+ const result = await gh(
2020
+ input.operatorRoot,
2021
+ [
2022
+ "api",
2023
+ "--method",
2024
+ "POST",
2025
+ `repos/{owner}/{repo}/pulls/${input.pr}/reviews`,
2026
+ "--input",
2027
+ "-",
2028
+ ],
2029
+ JSON.stringify(body),
2030
+ input.spawnFn,
2031
+ input.timeoutMs ?? POSTING_GH_TIMEOUT_MS,
2032
+ );
2033
+ if (result.ok) {
2034
+ return { outcome: "posted", findings: input.findings };
2035
+ }
2036
+ if (!is422(result.stderr)) {
2037
+ throw new CliError(
2038
+ `gh api (post PR review) failed: ${result.stderr.trim()}`,
2039
+ );
2040
+ }
2041
+ const posted = await fetchPostedFindingComments(
2042
+ input.operatorRoot,
2043
+ input.pr,
2044
+ {
2045
+ spawnFn: input.spawnFn,
2046
+ timeoutMs: input.timeoutMs ?? POSTING_GH_TIMEOUT_MS,
2047
+ },
2048
+ );
2049
+ const match = matchPostedFindings({
2050
+ findings: input.allFindings,
2051
+ posted,
2052
+ headSha: input.headSha,
2053
+ });
2054
+ const stillFreshIds = new Set(match.fresh.map((finding) => finding.id));
2055
+ return {
2056
+ outcome: "demoted",
2057
+ findings: input.findings.filter((finding) => stillFreshIds.has(finding.id)),
2058
+ };
2059
+ }
2060
+
2061
+ // One un-anchorable (or 422-demoted) finding, posted as its own top-level
2062
+ // issue comment (spec "One issue comment per un-anchorable finding": never
2063
+ // pooled). Always a fresh POST, never a PATCH — unlike postPrComment's
2064
+ // single summary comment, there is no "the" prior comment to update; a
2065
+ // finding either already has one (the caller's plan already excluded it,
2066
+ // via pr/inline.ts's matcher) or it does not.
2067
+ export async function postIssueComment(
2068
+ operatorRoot: string,
2069
+ pr: number,
2070
+ finding: Finding,
2071
+ headSha: string,
2072
+ webUrl?: string,
2073
+ spawnFn?: typeof Bun.spawn,
2074
+ ): Promise<number> {
2075
+ const body = renderIssueFindingComment(finding, headSha, webUrl);
2076
+ const result = await gh(
2077
+ operatorRoot,
2078
+ [
2079
+ "api",
2080
+ "--method",
2081
+ "POST",
2082
+ `repos/{owner}/{repo}/issues/${pr}/comments`,
2083
+ "-F",
2084
+ "body=@-",
2085
+ ],
2086
+ body,
2087
+ spawnFn,
2088
+ );
2089
+ if (!result.ok) {
2090
+ throw new CliError(
2091
+ `gh api (post finding issue comment) failed: ${result.stderr.trim()}`,
2092
+ );
2093
+ }
2094
+ let parsed: unknown = null;
2095
+ try {
2096
+ parsed = JSON.parse(result.stdout);
2097
+ } catch {
2098
+ parsed = null;
2099
+ }
2100
+ const commentId = (parsed as { id?: unknown } | null)?.id;
2101
+ if (typeof commentId !== "number") {
2102
+ throw new CliError(
2103
+ "gh api posted a finding issue comment but returned no comment id: " +
2104
+ result.stdout.slice(0, 120),
2105
+ );
2106
+ }
2107
+ return commentId;
2108
+ }
2109
+
2110
+ // A fresh top-level issue comment with a pre-rendered body. Always a POST,
2111
+ // never find-and-update: unlike the summary, every re-review's closing
2112
+ // comment is its own entry in the timeline on purpose.
2113
+ async function postIssueCommentBody(
2114
+ operatorRoot: string,
2115
+ pr: number,
2116
+ body: string,
2117
+ spawnFn?: typeof Bun.spawn,
2118
+ timeoutMs?: number,
2119
+ ): Promise<number> {
2120
+ const result = await gh(
2121
+ operatorRoot,
2122
+ [
2123
+ "api",
2124
+ "--method",
2125
+ "POST",
2126
+ `repos/{owner}/{repo}/issues/${pr}/comments`,
2127
+ "-F",
2128
+ "body=@-",
2129
+ ],
2130
+ body,
2131
+ spawnFn,
2132
+ timeoutMs,
2133
+ );
2134
+ if (!result.ok) {
2135
+ throw new CliError(
2136
+ `gh api (post issue comment) failed: ${result.stderr.trim()}`,
2137
+ );
2138
+ }
2139
+ return parsePostedCommentId(result.stdout, "issue comment");
2140
+ }
2141
+
2142
+ function parsePostedCommentId(stdout: string, what: string): number {
2143
+ let parsed: unknown = null;
2144
+ try {
2145
+ parsed = JSON.parse(stdout);
2146
+ } catch {
2147
+ parsed = null;
2148
+ }
2149
+ const commentId = (parsed as { id?: unknown } | null)?.id;
2150
+ if (typeof commentId !== "number") {
2151
+ throw new CliError(
2152
+ `gh api posted a ${what} but returned no comment id: ` +
2153
+ stdout.slice(0, 120),
2154
+ );
2155
+ }
2156
+ return commentId;
2157
+ }
2158
+
2159
+ // Inline triage reply: POST pulls/<n>/comments with in_reply_to set to the
2160
+ // finding's own review-comment id. The parent id is resolved by the caller
2161
+ // from fetchPostedFindingComments + matchPostedFindingExact — this function
2162
+ // never looks at path/line. Body on stdin (ARG_MAX / no-shell, same as
2163
+ // postIssueComment).
2164
+ export async function postReviewCommentReply(input: {
2165
+ operatorRoot: string;
2166
+ pr: number;
2167
+ inReplyTo: number;
2168
+ body: string;
2169
+ spawnFn?: typeof Bun.spawn;
2170
+ // Optional per-call watchdog. Absent keeps the historical unbounded wait
2171
+ // for the interactive triage path (a human is watching); the verified-gone
2172
+ // collapse loop passes one, because nothing is watching an unattended run.
2173
+ timeoutMs?: number;
2174
+ }): Promise<number> {
2175
+ const result = await gh(
2176
+ input.operatorRoot,
2177
+ [
2178
+ "api",
2179
+ "--method",
2180
+ "POST",
2181
+ `repos/{owner}/{repo}/pulls/${input.pr}/comments`,
2182
+ "-F",
2183
+ "body=@-",
2184
+ "-F",
2185
+ `in_reply_to=${input.inReplyTo}`,
2186
+ ],
2187
+ input.body,
2188
+ input.spawnFn,
2189
+ input.timeoutMs,
2190
+ );
2191
+ if (!result.ok) {
2192
+ throw new CliError(
2193
+ `gh api (post triage review reply) failed: ${result.stderr.trim()}`,
2194
+ );
2195
+ }
2196
+ return parsePostedCommentId(result.stdout, "triage review reply");
2197
+ }
2198
+
2199
+ // Un-anchorable finding (#17 channel): GitHub issue comments have no
2200
+ // native thread, so the reply is another top-level issue comment. The
2201
+ // caller puts the permalink in the body; this function does not guess one.
2202
+ export async function postIssueTriageComment(input: {
2203
+ operatorRoot: string;
2204
+ pr: number;
2205
+ body: string;
2206
+ spawnFn?: typeof Bun.spawn;
2207
+ }): Promise<number> {
2208
+ const result = await gh(
2209
+ input.operatorRoot,
2210
+ [
2211
+ "api",
2212
+ "--method",
2213
+ "POST",
2214
+ `repos/{owner}/{repo}/issues/${input.pr}/comments`,
2215
+ "-F",
2216
+ "body=@-",
2217
+ ],
2218
+ input.body,
2219
+ input.spawnFn,
2220
+ );
2221
+ if (!result.ok) {
2222
+ throw new CliError(
2223
+ `gh api (post triage issue comment) failed: ${result.stderr.trim()}`,
2224
+ );
2225
+ }
2226
+ return parsePostedCommentId(result.stdout, "triage issue comment");
2227
+ }
2228
+
2229
+ export type ResolveThreadOutcome =
2230
+ | "resolved"
2231
+ | "already-resolved"
2232
+ | "not-found";
2233
+
2234
+ // One more `}` than the first live query: 7 opens (query / repository /
2235
+ // pullRequest / reviewThreads / nodes / comments / nodes) need 7 closes.
2236
+ // Live W1 triage on pr-hero #34 failed with
2237
+ // `Expected NAME, actual: (none) ("") at [1, 202]` — GraphQL reaching EOF
2238
+ // on the last brace, which was one short. Variable names are `repoOwner` /
2239
+ // `repoName` so they cannot collide with `gh -f name=` interpolating `$name`
2240
+ // inside the query document.
2241
+ const REVIEW_THREADS_QUERY =
2242
+ "query($repoOwner:String!,$repoName:String!,$number:Int!){" +
2243
+ "repository(owner:$repoOwner,name:$repoName){pullRequest(number:$number){" +
2244
+ "reviewThreads(first:100){nodes{id isResolved comments(first:1){" +
2245
+ "nodes{fullDatabaseId}}}}}}}";
2246
+
2247
+ const RESOLVE_THREAD_MUTATION =
2248
+ "mutation($id:ID!){resolveReviewThread(input:{threadId:$id}){" +
2249
+ "thread{isResolved}}}";
2250
+
2251
+ // Fake-gh tests never send the document to GitHub, so they cannot catch a
2252
+ // truncated query. Live W1 on #34 failed with GraphQL EOF
2253
+ // (`Expected NAME, actual: (none) ("")`) because REVIEW_THREADS_QUERY was
2254
+ // one `}` short. Count here, before spawn.
2255
+ function assertBalancedGraphql(document: string, what: string): void {
2256
+ const opens = (document.match(/{/g) ?? []).length;
2257
+ const closes = (document.match(/}/g) ?? []).length;
2258
+ if (opens !== closes) {
2259
+ throw new CliError(
2260
+ `gh api graphql (${what}) query is unbalanced: ${opens} { vs ${closes} }`,
2261
+ );
2262
+ }
2263
+ }
2264
+
2265
+ interface RepoOwnerName {
2266
+ owner: string;
2267
+ name: string;
2268
+ }
2269
+
2270
+ async function ghRepoOwnerName(
2271
+ operatorRoot: string,
2272
+ spawnFn?: typeof Bun.spawn,
2273
+ timeoutMs?: number,
2274
+ ): Promise<RepoOwnerName> {
2275
+ const result = await gh(
2276
+ operatorRoot,
2277
+ ["repo", "view", "--json", "owner,name"],
2278
+ undefined,
2279
+ spawnFn,
2280
+ timeoutMs,
2281
+ );
2282
+ if (!result.ok) {
2283
+ throw new CliError(`gh repo view failed: ${result.stderr.trim()}`);
2284
+ }
2285
+ let parsed: unknown = null;
2286
+ try {
2287
+ parsed = JSON.parse(result.stdout);
2288
+ } catch {
2289
+ parsed = null;
2290
+ }
2291
+ if (typeof parsed !== "object" || parsed === null) {
2292
+ throw new CliError(
2293
+ "gh repo view --json owner,name returned invalid JSON: " +
2294
+ result.stdout.slice(0, 120),
2295
+ );
2296
+ }
2297
+ const record = parsed as { name?: unknown; owner?: unknown };
2298
+ const name = record.name;
2299
+ const owner =
2300
+ typeof record.owner === "object" && record.owner !== null
2301
+ ? (record.owner as { login?: unknown }).login
2302
+ : undefined;
2303
+ if (typeof name !== "string" || name.length === 0) {
2304
+ throw new CliError("gh repo view returned no repository name");
2305
+ }
2306
+ if (typeof owner !== "string" || owner.length === 0) {
2307
+ throw new CliError("gh repo view returned no repository owner");
2308
+ }
2309
+ return { owner, name };
2310
+ }
2311
+
2312
+ function graphqlDatabaseId(value: unknown): number | null {
2313
+ if (typeof value === "number" && Number.isInteger(value)) return value;
2314
+ if (typeof value === "string" && /^\d+$/.test(value)) return Number(value);
2315
+ return null;
2316
+ }
2317
+
2318
+ interface GraphQlThread {
2319
+ id: string;
2320
+ isResolved: boolean;
2321
+ comments: { nodes: { fullDatabaseId: unknown }[] };
2322
+ }
2323
+
2324
+ function parseReviewThreads(stdout: string): GraphQlThread[] {
2325
+ let parsed: unknown = null;
2326
+ try {
2327
+ parsed = JSON.parse(stdout);
2328
+ } catch {
2329
+ throw new CliError(
2330
+ "gh api graphql (reviewThreads) returned invalid JSON: " +
2331
+ stdout.slice(0, 120),
2332
+ );
2333
+ }
2334
+ const nodes = (
2335
+ parsed as {
2336
+ data?: {
2337
+ repository?: {
2338
+ pullRequest?: { reviewThreads?: { nodes?: unknown } };
2339
+ };
2340
+ };
2341
+ } | null
2342
+ )?.data?.repository?.pullRequest?.reviewThreads?.nodes;
2343
+ if (!Array.isArray(nodes)) {
2344
+ throw new CliError(
2345
+ "gh api graphql (reviewThreads) returned no thread list",
2346
+ );
2347
+ }
2348
+ return nodes as GraphQlThread[];
2349
+ }
2350
+
2351
+ // The GitHub message for a token without the permission to resolve review threads.
2352
+ const WORKFLOW_TOKEN_CANNOT_RESOLVE = "Resource not accessible by integration";
2353
+
2354
+ // Map a REST review-comment id to its GraphQL review thread and resolve it.
2355
+ // Idempotent: an already-resolved thread is a skip, not an error. A comment
2356
+ // with no thread (deleted, or outside the first 100 threads) is not-found
2357
+ // — the caller logs and still treats the reply post as success.
2358
+ export async function resolveReviewThreadForComment(input: {
2359
+ operatorRoot: string;
2360
+ pr: number;
2361
+ commentId: number;
2362
+ spawnFn?: typeof Bun.spawn;
2363
+ // Applied to EVERY gh call this function makes — the repo lookup and both
2364
+ // graphql round trips. A bound on two of three still hangs on the third.
2365
+ timeoutMs?: number;
2366
+ }): Promise<ResolveThreadOutcome> {
2367
+ assertBalancedGraphql(REVIEW_THREADS_QUERY, "reviewThreads");
2368
+ assertBalancedGraphql(RESOLVE_THREAD_MUTATION, "resolveReviewThread");
2369
+ const repo = await ghRepoOwnerName(
2370
+ input.operatorRoot,
2371
+ input.spawnFn,
2372
+ input.timeoutMs,
2373
+ );
2374
+ const listed = await gh(
2375
+ input.operatorRoot,
2376
+ [
2377
+ "api",
2378
+ "graphql",
2379
+ "-f",
2380
+ `query=${REVIEW_THREADS_QUERY}`,
2381
+ "-f",
2382
+ `repoOwner=${repo.owner}`,
2383
+ "-f",
2384
+ `repoName=${repo.name}`,
2385
+ "-F",
2386
+ `number=${input.pr}`,
2387
+ ],
2388
+ undefined,
2389
+ input.spawnFn,
2390
+ input.timeoutMs,
2391
+ );
2392
+ if (!listed.ok) {
2393
+ throw new CliError(
2394
+ `gh api graphql (reviewThreads) failed: ${listed.stderr.trim()}`,
2395
+ );
2396
+ }
2397
+ const thread = parseReviewThreads(listed.stdout).find((candidate) => {
2398
+ const first = candidate.comments?.nodes?.[0]?.fullDatabaseId;
2399
+ return graphqlDatabaseId(first) === input.commentId;
2400
+ });
2401
+ if (thread === undefined) return "not-found";
2402
+ if (thread.isResolved) return "already-resolved";
2403
+ const mutated = await gh(
2404
+ input.operatorRoot,
2405
+ [
2406
+ "api",
2407
+ "graphql",
2408
+ "-f",
2409
+ `query=${RESOLVE_THREAD_MUTATION}`,
2410
+ "-f",
2411
+ `id=${thread.id}`,
2412
+ ],
2413
+ undefined,
2414
+ input.spawnFn,
2415
+ input.timeoutMs,
2416
+ );
2417
+ if (!mutated.ok) {
2418
+ throw new CliError(
2419
+ `gh api graphql (resolveReviewThread) failed: ${mutated.stderr.trim()}`,
2420
+ );
2421
+ }
2422
+ return "resolved";
2423
+ }
2424
+
2425
+ // Re-export for callers that already import check-run constants from pr.ts.
2426
+ export { ADMISSION_CHECK_RUN_NAME };
2427
+
2428
+ const ADMISSION_CHECK_RUN_TIMEOUT_MS = 15_000;
2429
+
2430
+ // The jq condition that matches the ledger's check runs under either name, so a
2431
+ // head first reviewed by an older release keeps its attempt count.
2432
+ function admissionCheckRunNameJq(): string {
2433
+ return [ADMISSION_CHECK_RUN_NAME, LEGACY_ADMISSION_CHECK_RUN_NAME]
2434
+ .map((name) => `.name == "${name}"`)
2435
+ .join(" or ");
2436
+ }
2437
+
2438
+ function admissionCheckRunConclusion(
2439
+ status: AdmissionAttemptStatus,
2440
+ ): "success" | "failure" | "neutral" | "cancelled" | "skipped" {
2441
+ switch (status) {
2442
+ case "completed":
2443
+ return "success";
2444
+ case "failed":
2445
+ return "failure";
2446
+ case "cancelled":
2447
+ return "cancelled";
2448
+ case "skipped":
2449
+ return "skipped";
2450
+ // Explicit, never left to `default`: standing down for a review already
2451
+ // in flight is not a failure, and GitHub renders `skipped` as grey rather
2452
+ // than red on the PR (musive #1935 showed a red check for exactly this).
2453
+ case "yielded":
2454
+ return "skipped";
2455
+ // #326: a size or budget gate skip. It was `skipped` (grey) before the
2456
+ // status split, so it stays grey; `neutral` would change how the PR reads.
2457
+ case "gate-skipped":
2458
+ return "skipped";
2459
+ default:
2460
+ return "neutral";
2461
+ }
2462
+ }
2463
+
2464
+ function admissionCheckRunStatus(
2465
+ status: AdmissionAttemptStatus,
2466
+ ): "queued" | "in_progress" | "completed" {
2467
+ if (
2468
+ status === "reserved" ||
2469
+ status === "provider-started" ||
2470
+ status === "unknown"
2471
+ ) {
2472
+ return "in_progress";
2473
+ }
2474
+ return "completed";
2475
+ }
2476
+
2477
+ function parseAdmissionCheckRunRow(
2478
+ line: string,
2479
+ ): { id: number; record: AdmissionRecord } | null {
2480
+ if (line.trim() === "") return null;
2481
+ try {
2482
+ const row = JSON.parse(line) as {
2483
+ id?: number;
2484
+ name?: string;
2485
+ status?: string;
2486
+ output?: { text?: string | null };
2487
+ };
2488
+ if (row.name === undefined || !isAdmissionCheckRunName(row.name))
2489
+ return null;
2490
+ const text = row.output?.text;
2491
+ if (typeof text !== "string") return null;
2492
+ const record = parseAdmissionRecord(text);
2493
+ return record === null ? null : { id: row.id ?? 0, record };
2494
+ } catch {
2495
+ return null;
2496
+ }
2497
+ }
2498
+
2499
+ // Authoritative durable ledger for CI admission attempts on a ref. Fail-open:
2500
+ // a missing `checks: read` scope must not abort a review that already passed
2501
+ // the pure admission gate — an empty read underestimates attempts (more spend,
2502
+ // never silent skip).
2503
+ //
2504
+ // `includeHistory` adds `filter=all`. GitHub's check-runs endpoint defaults to
2505
+ // `filter=latest`, which returns only the newest check run per name. Every
2506
+ // admission attempt on a head is its own check run with the same name, so the
2507
+ // default hides all earlier attempts on that head. A per-head read that decides
2508
+ // whether a workflow run spent (countableWorkflowHeads) needs that history: a head
2509
+ // with `[completed, gate-skipped]` would otherwise look like `[gate-skipped]` and
2510
+ // be dropped. Leave it off for a read that wants current state. The request stays
2511
+ // paginated (`--paginate`), so every page of history is read.
2512
+ export async function listAdmissionCheckRuns(
2513
+ operatorRoot: string,
2514
+ ref: string,
2515
+ options?: { spawnFn?: typeof Bun.spawn; includeHistory?: boolean },
2516
+ ): Promise<AdmissionRecord[]> {
2517
+ if (!isFullCommitId(ref) && ref.trim().length === 0) return [];
2518
+ const historyQuery = options?.includeHistory === true ? "?filter=all" : "";
2519
+ try {
2520
+ const result = await gh(
2521
+ operatorRoot,
2522
+ [
2523
+ "api",
2524
+ `repos/{owner}/{repo}/commits/${ref}/check-runs${historyQuery}`,
2525
+ "--paginate",
2526
+ "--jq",
2527
+ `.check_runs[] | select(${admissionCheckRunNameJq()}) | {id: .id, name: .name, status: .status, output: {text: .output.text}}`,
2528
+ ],
2529
+ undefined,
2530
+ options?.spawnFn,
2531
+ ADMISSION_CHECK_RUN_TIMEOUT_MS,
2532
+ );
2533
+ if (!result.ok) return [];
2534
+ const rows: { id: number; record: AdmissionRecord }[] = [];
2535
+ for (const line of result.stdout.split("\n")) {
2536
+ const row = parseAdmissionCheckRunRow(line);
2537
+ if (row !== null) rows.push(row);
2538
+ }
2539
+ if (options?.includeHistory === true || rows.length < 2) {
2540
+ return rows.map((row) => row.record);
2541
+ }
2542
+ // filter=latest is per NAME, so a head admitted both before and after the
2543
+ // rename returns one row under each name. The current state is the newest
2544
+ // check run (ids only grow); returning both would count an extra attempt.
2545
+ const newest = rows.reduce((a, b) => (b.id > a.id ? b : a));
2546
+ return [newest.record];
2547
+ } catch {
2548
+ return [];
2549
+ }
2550
+ }
2551
+
2552
+ // W3-RESERVE: a POST that failed may still have created the run (gh timed out
2553
+ // after GitHub accepted it). Look it up by external_id AND by the attempt and
2554
+ // createdAt of the record being posted: external_id is the reservation
2555
+ // fingerprint, shared by every attempt on this head and policy, so it alone
2556
+ // would adopt an earlier attempt's run. Any failure of the lookup reads as "no
2557
+ // match", which keeps the POST retry exactly as it was.
2558
+ //
2559
+ // The POST nonce is what names this call's run. A reused record shares its
2560
+ // external_id, attempt and createdAt with a run another workflow run wrote
2561
+ // (review #360 F001), so those three can never tell the two apart; only the
2562
+ // nonce this call wrote into its own record can. A run without a nonce never
2563
+ // matches.
2564
+ async function findAdmissionCheckRunForAttempt(
2565
+ operatorRoot: string,
2566
+ headSha: string,
2567
+ record: AdmissionRecord,
2568
+ postNonce: string,
2569
+ spawnFn?: typeof Bun.spawn,
2570
+ ): Promise<{ id: number; status: string | undefined } | null> {
2571
+ try {
2572
+ const result = await gh(
2573
+ operatorRoot,
2574
+ [
2575
+ "api",
2576
+ `repos/{owner}/{repo}/commits/${headSha}/check-runs?check_name=${ADMISSION_CHECK_RUN_NAME}&filter=all`,
2577
+ "--paginate",
2578
+ "--jq",
2579
+ `.check_runs[] | select(.name == "${ADMISSION_CHECK_RUN_NAME}") | {id: .id, name: .name, status: .status, external_id: .external_id, output: {text: .output.text}}`,
2580
+ ],
2581
+ undefined,
2582
+ spawnFn,
2583
+ ADMISSION_CHECK_RUN_TIMEOUT_MS,
2584
+ );
2585
+ if (!result.ok) return null;
2586
+ for (const line of result.stdout.split("\n")) {
2587
+ const parsedRecord = parseAdmissionCheckRunRow(line)?.record ?? null;
2588
+ if (parsedRecord === null) continue;
2589
+ const row = JSON.parse(line) as {
2590
+ id?: number;
2591
+ status?: string;
2592
+ external_id?: string;
2593
+ };
2594
+ if (
2595
+ typeof row.id === "number" &&
2596
+ row.external_id === record.reservationId &&
2597
+ parsedRecord.attemptNumber === record.attemptNumber &&
2598
+ parsedRecord.createdAt === record.createdAt &&
2599
+ parsedRecord.postNonce === postNonce
2600
+ ) {
2601
+ return { id: row.id, status: row.status };
2602
+ }
2603
+ }
2604
+ return null;
2605
+ } catch {
2606
+ return null;
2607
+ }
2608
+ }
2609
+
2610
+ export async function upsertAdmissionCheckRun(
2611
+ operatorRoot: string,
2612
+ input: {
2613
+ headSha: string;
2614
+ record: AdmissionRecord;
2615
+ checkRunId?: number;
2616
+ },
2617
+ options?: { spawnFn?: typeof Bun.spawn },
2618
+ ): Promise<number> {
2619
+ if (!isFullCommitId(input.headSha)) {
2620
+ throw new CliError(
2621
+ `admission check run: head sha is not a full 40-char id: ${input.headSha.slice(0, 16)}`,
2622
+ );
2623
+ }
2624
+ // WHY one nonce per call, minted before the retry loop: the POST writes it
2625
+ // into the run's record, and a failed POST's lookup adopts only a run carrying
2626
+ // it. That is why adoption is safe for a reused record too: a sibling run from
2627
+ // another workflow run can never carry this call's nonce.
2628
+ const postNonce = randomUUID();
2629
+ const serialized = serializeAdmissionRecord({
2630
+ ...input.record,
2631
+ postNonce,
2632
+ });
2633
+ const checkStatus = admissionCheckRunStatus(input.record.status);
2634
+ const args = [
2635
+ "api",
2636
+ "--method",
2637
+ input.checkRunId === undefined ? "POST" : "PATCH",
2638
+ input.checkRunId === undefined
2639
+ ? "repos/{owner}/{repo}/check-runs"
2640
+ : `repos/{owner}/{repo}/check-runs/${input.checkRunId}`,
2641
+ "-f",
2642
+ `name=${ADMISSION_CHECK_RUN_NAME}`,
2643
+ "-f",
2644
+ `head_sha=${input.headSha}`,
2645
+ "-f",
2646
+ `external_id=${input.record.reservationId}`,
2647
+ "-f",
2648
+ `status=${checkStatus}`,
2649
+ "-f",
2650
+ "output[title]=crysk CI admission",
2651
+ "-f",
2652
+ `output[summary]=${input.record.status} (attempt ${input.record.attemptNumber})`,
2653
+ "-f",
2654
+ `output[text]=${serialized}`,
2655
+ ];
2656
+ if (checkStatus === "completed") {
2657
+ args.push(
2658
+ "-f",
2659
+ `conclusion=${admissionCheckRunConclusion(input.record.status)}`,
2660
+ );
2661
+ }
2662
+ let lastStderr = "";
2663
+ for (let attempt = 0; attempt < 2; attempt++) {
2664
+ const result = await gh(
2665
+ operatorRoot,
2666
+ args,
2667
+ undefined,
2668
+ options?.spawnFn,
2669
+ ADMISSION_CHECK_RUN_TIMEOUT_MS,
2670
+ );
2671
+ if (result.ok) {
2672
+ try {
2673
+ const parsed = JSON.parse(result.stdout) as { id?: number };
2674
+ if (typeof parsed.id === "number") return parsed.id;
2675
+ } catch {
2676
+ if (input.checkRunId !== undefined) return input.checkRunId;
2677
+ }
2678
+ throw new CliError(
2679
+ "gh api upserted an admission check run but returned no check run id",
2680
+ );
2681
+ }
2682
+ lastStderr = result.stderr.trim();
2683
+ // Only a POST can have created a run the caller does not know about; a
2684
+ // PATCH already names its run. A match is adopted instead of retried.
2685
+ if (input.checkRunId === undefined) {
2686
+ const existing = await findAdmissionCheckRunForAttempt(
2687
+ operatorRoot,
2688
+ input.headSha,
2689
+ input.record,
2690
+ postNonce,
2691
+ options?.spawnFn,
2692
+ );
2693
+ if (existing !== null) {
2694
+ if (existing.status === checkStatus) return existing.id;
2695
+ return upsertAdmissionCheckRun(
2696
+ operatorRoot,
2697
+ { ...input, checkRunId: existing.id },
2698
+ options,
2699
+ );
2700
+ }
2701
+ }
2702
+ }
2703
+ throw new CliError(`gh api (admission check run) failed: ${lastStderr}`);
2704
+ }
2705
+
2706
+ // ---------------------------------------------------------------------------
2707
+ // Inline review surface orchestration (ROADMAP B6, WU6) — the ONLY place
2708
+ // that composes pr/inline.ts's pure plan with this module's own I/O
2709
+ // primitives into the actual post sequence. Shared verbatim by reviewPr's
2710
+ // step 14 (a review that just finished) and postCommand (a review read off
2711
+ // disk, src/commands/post.ts): the SAME code posts either way, because a finding does not
2712
+ // know or care whether it came from a fresh run or a `--from <run-dir>`
2713
+ // replay. Extracted from cli.ts (cli-decomp S2, Cluster C).
2714
+ //
2715
+ // `spawnFn` is the same invisible-to-production seam this module's other B6
2716
+ // functions already use (see gh()'s WHY comment above) — threaded through
2717
+ // here so test/pr/inline-post.test.ts can drive the WHOLE sequence, including
2718
+ // the summary PATCH, through one shared fake gh.
2719
+ // ---------------------------------------------------------------------------
2720
+
2721
+ // Fetch + anchor + plan, with NO posting — the exact subset `post --dry-run`
2722
+ // needs (spec "Dry-run from a prior run directory": a read-only comment
2723
+ // fetch, zero mutating HTTP calls) and the first half of postInlineFindings,
2724
+ // factored out so the two never compute two different plans for the same
2725
+ // state.
2726
+ export async function resolveInlinePostPlan(input: {
2727
+ operatorRoot: string;
2728
+ pr: number;
2729
+ headSha: string;
2730
+ doc: FindingsDocument;
2731
+ diffPatch: string;
2732
+ spawnFn?: typeof Bun.spawn;
2733
+ }): Promise<{
2734
+ plan: PostPlan;
2735
+ previousHeadSha: string | undefined;
2736
+ // Whether a marked summary comment already exists on the PR — threaded
2737
+ // through so postInlineFindings knows whether to CREATE the summary up
2738
+ // front (design rework: create-first fixes the summary's position in the
2739
+ // timeline; see postInlineFindings's own WHY) or leave a pre-existing one
2740
+ // alone until the closing PATCH.
2741
+ existingSummaryId: number | null;
2742
+ summaryBody: string | null;
2743
+ // The FULL finding list the plan matched against — threaded through to
2744
+ // postPrReview's 422 recovery so it can re-match with the SAME finding
2745
+ // set the plan used, never a narrower one (CRIT-A, verify-report-pr3
2746
+ // #3305: re-matching a subset can dissolve a tie the plan already
2747
+ // resolved). See ReviewSubmissionOutcome's WHY in pr/pr.ts.
2748
+ findingRefs: PrHeroFindingRef[];
2749
+ posted: PostedFindingComment[];
2750
+ }> {
2751
+ const issueComments = await fetchPrComments(input.operatorRoot, input.pr, {
2752
+ spawnFn: input.spawnFn,
2753
+ timeoutMs: POSTING_GH_TIMEOUT_MS,
2754
+ });
2755
+ const existingSummaryId = findMarkedCommentId(issueComments);
2756
+ const summaryBody = summaryBodyForId(issueComments, existingSummaryId);
2757
+ const previousHeadSha =
2758
+ summaryBody === null
2759
+ ? undefined
2760
+ : (parseMarkerHead(summaryBody) ?? undefined);
2761
+ const posted = await fetchPostedFindingComments(
2762
+ input.operatorRoot,
2763
+ input.pr,
2764
+ { spawnFn: input.spawnFn, timeoutMs: POSTING_GH_TIMEOUT_MS },
2765
+ );
2766
+ const anchors = parseHunkAnchors(input.diffPatch);
2767
+ const findingRefs: PrHeroFindingRef[] = input.doc.findings.map((f) => {
2768
+ const ref = {
2769
+ id: f.id,
2770
+ path: f.path,
2771
+ line: f.line,
2772
+ claim: f.claim,
2773
+ tier: f.tier,
2774
+ proof_refs: f.proof_refs,
2775
+ };
2776
+ // Resolve here, not only inside buildPostPlan: postPrReview's 422
2777
+ // rematch uses this same list as `allFindings`, and CRIT-A requires
2778
+ // that rematch to see the SAME lines the plan matched against. A
2779
+ // re-anchored 544→938 finding compared at 544 against a comment stored
2780
+ // at 938 would miss the persist and duplicate. Original order is
2781
+ // load-bearing (a persist-first reorder dissolves the CRIT-A tie).
2782
+ const postLine = resolvePostLine(ref, anchors);
2783
+ return postLine === undefined ? ref : { ...ref, line: postLine };
2784
+ });
2785
+ const plan = buildPostPlan({
2786
+ findings: findingRefs,
2787
+ anchors,
2788
+ posted,
2789
+ headSha: input.headSha,
2790
+ });
2791
+ return {
2792
+ plan,
2793
+ previousHeadSha,
2794
+ existingSummaryId,
2795
+ summaryBody,
2796
+ findingRefs,
2797
+ posted,
2798
+ };
2799
+ }
2800
+
2801
+ function summaryBodyForId(
2802
+ comments: { id: number; body: string }[],
2803
+ summaryId: number | null,
2804
+ ): string | null {
2805
+ if (summaryId === null) return null;
2806
+ return comments.find((c) => c.id === summaryId)?.body ?? null;
2807
+ }
2808
+
2809
+ // A finding's own posted comment, as a clickable link for the summary's
2810
+ // index (Juanma's PR #2 feedback: each index line links to its own
2811
+ // comment). GitHub's fragment conventions for the two comment families
2812
+ // differ — a REVIEW (inline) comment anchors on `#discussion_r<id>`, a
2813
+ // top-level issue comment on `#issuecomment-<id>` — so the channel the
2814
+ // comment actually landed in decides the shape, never guessed from one.
2815
+ function findingCommentUrl(
2816
+ webUrl: string,
2817
+ pr: number,
2818
+ channel: "review" | "issue",
2819
+ id: number,
2820
+ ): string {
2821
+ const fragment =
2822
+ channel === "review" ? `discussion_r${id}` : `issuecomment-${id}`;
2823
+ return `${webUrl}/pull/${pr}#${fragment}`;
2824
+ }
2825
+
2826
+ // Watchdog for the verified-gone collapse loop's `gh` calls. Every LLM step
2827
+ // in the pipeline is bounded by `stepTimeoutMs`; the collapse loop's two gh
2828
+ // calls were the only awaits on the `--post` path with no bound at all, and
2829
+ // an accepted-but-unanswered GitHub request there hangs `review --pr --post`
2830
+ // forever — including an unattended `--yes` run launched by the watcher,
2831
+ // where nothing is present to notice or ^C it. Two minutes is generous for a
2832
+ // single REST/graphql round trip and still finite; the failure it converts is
2833
+ // "hangs until someone kills it" → "one logged line, thread left open".
2834
+ const COLLAPSE_GH_TIMEOUT_MS = 120_000;
2835
+
2836
+ // The bound on every gh call the findings POST makes: the summary create and
2837
+ // PATCH, the review submission and its 422 recovery reads, the pre-POST head
2838
+ // re-read, and the reads around them. WHY 120 s: the POST runs after the review
2839
+ // has already finished, so a slow GitHub answer for a large review still lands
2840
+ // well inside it. WHY a bound at all (F004, PR #330): an accepted-but-unanswered
2841
+ // call parked publishRunOutcome forever, and the pending commit status with it.
2842
+ // A timeout fails exactly like a non-zero gh exit, so the posting catch records
2843
+ // the step error and the publisher reports it. WHY no retry: a timed-out POST
2844
+ // may already have landed, and a retry would duplicate the review. A local
2845
+ // `pr-hero review --pr N --post` runs this same code, so it now also fails after
2846
+ // 120 s instead of hanging. That is intended.
2847
+ export const POSTING_GH_TIMEOUT_MS = 120_000;
2848
+
2849
+ // The actual post sequence (design D6, reordered per Juanma's PR #2
2850
+ // feedback item 2; W2 issues #16/#17 retire the issue-comment loop):
2851
+ // summary CREATED FIRST when none exists yet → review submission (with
2852
+ // 422 recovery into the summary Outside Diff bucket) → summary PATCHED
2853
+ // LAST with the final delta, comment links, and the Outside Diff union.
2854
+ // NO `sessionFailed` awareness here — same contract as this module's own
2855
+ // primitives (see postPrReview's own WHY): the guard belongs to the
2856
+ // caller that decides whether to invoke this at all (postInlineIfEligible,
2857
+ // below).
2858
+ //
2859
+ // WHY create-first: the summary was landing BELOW every finding in the
2860
+ // Conversation timeline (real posted evidence: review comments 13:12:43,
2861
+ // summary 13:12:45) because it was created LAST. Creation order fixes a
2862
+ // comment's position; a PATCH never moves it. So on a PR with no summary
2863
+ // yet, this posts a placeholder summary — the full index, the PLANNED
2864
+ // Outside Diff bucket (known before any write), and the PLANNED delta,
2865
+ // just without per-finding review-comment links (they do not exist yet)
2866
+ // — as the FIRST write of the run, then patches it again at the end with
2867
+ // the ACTUAL delta, the links, and any 422-demoted findings that joined
2868
+ // the bucket. On a re-run (a summary already exists), the early create is
2869
+ // skipped entirely: that comment's position was already fixed by a
2870
+ // PREVIOUS run, and creating again would either duplicate it or waste an
2871
+ // API call patching it twice.
2872
+ // The final PATCH's delta-must-describe-what-was-posted invariant (PR2
2873
+ // verification, WARN-3) is unchanged — the placeholder is provisional, the
2874
+ // closing PATCH is authoritative, same as before this rework.
2875
+
2876
+ // One wording PER refusal, each said by both the post sequence's precondition
2877
+ // and `post --dry-run`'s preview of it. The preview and the post disagreeing
2878
+ // about whether a run dir may be published is the failure the whole $0-gate
2879
+ // suite exists to prevent, and two hand-written messages is how that starts.
2880
+ export function missingRereviewBlockMessage(
2881
+ pr: number,
2882
+ summaryId: number,
2883
+ ): string {
2884
+ return (
2885
+ `PR #${pr} already carries a Crysk summary (comment ${summaryId}), so ` +
2886
+ "this post is a re-review — but the run directory carries no `rereview` " +
2887
+ "block in its pipeline.json, so the summary would report the old " +
2888
+ 'absence matcher\'s "N resolved" and write no state block. Re-run ' +
2889
+ `\`crysk review --pr ${pr} --post\` instead.`
2890
+ );
2891
+ }
2892
+
2893
+ // The same rule read in the other direction. Same shared-wording reason, and
2894
+ // it names the mismatch specifically: the run dir describes a re-review of a
2895
+ // summary the PR no longer has.
2896
+ export function vanishedPriorSummaryMessage(pr: number): string {
2897
+ return (
2898
+ "The run directory carries a `rereview` block in its pipeline.json, so " +
2899
+ `this post is a re-review — but PR #${pr} no longer carries a Crysk ` +
2900
+ "summary comment for it to be a re-review OF. Its `live[]` rows, " +
2901
+ "`resolved_ids` and `R###` numbering all name review threads the PR has " +
2902
+ "no record of, so this would publish a brand new summary claiming a " +
2903
+ `delta against a review that is not there. Re-run \`crysk review --pr ` +
2904
+ `${pr} --post\` instead.`
2905
+ );
2906
+ }
2907
+
2908
+ // The `--pr --post` half of the same state (see the guard's WHY below): that
2909
+ // caller does not refuse, it drops the re-review framing and says so. Loud on
2910
+ // purpose — an operator who sees a first-review comment where a delta was
2911
+ // expected must be able to read WHY off the run log instead of suspecting the
2912
+ // re-review silently broke. A silent downgrade would be the same class of
2913
+ // defect as a guard that never fires.
2914
+ function vanishedPriorSummaryDegradedMessage(pr: number): string {
2915
+ return (
2916
+ "warning: the Crysk summary comment this re-review was computed " +
2917
+ `against is gone from PR #${pr} — deleted, or never re-findable, while ` +
2918
+ "the review ran. Its `live[]` rows and `R###` ids name review threads " +
2919
+ "the PR has no record of, so this post drops the re-review framing: no " +
2920
+ "`Δ since` delta, no `Still live:` list and no state block. The findings " +
2921
+ "themselves are published, as the first review of what the PR carries " +
2922
+ `now. Re-run \`crysk review --pr ${pr} --post\` if you want a full ` +
2923
+ "re-review against the PR's current state."
2924
+ );
2925
+ }
2926
+
2927
+ export async function postInlineFindings(input: {
2928
+ operatorRoot: string;
2929
+ pr: number;
2930
+ headSha: string;
2931
+ doc: FindingsDocument;
2932
+ diffPatch: string;
2933
+ webUrl: string | undefined;
2934
+ spawnFn?: typeof Bun.spawn;
2935
+ rereview?: RereviewProvenance;
2936
+ rereviewPriors?: readonly {
2937
+ id: string;
2938
+ claim: string;
2939
+ locs: readonly string[];
2940
+ }[];
2941
+ // Watchdog for the collapse loop's gh calls. A seam, like `spawnFn`: no
2942
+ // production caller sets it, the tests drive the timeout path with it.
2943
+ ghTimeoutMs?: number;
2944
+ // S4: the CI mode the summary comment's disclaimer follows. Omitted is
2945
+ // advisory: the local `post` command, and every caller that never sets it.
2946
+ ciMode?: CiMode;
2947
+ // Set ONLY by `post --from` (`runPostCommand`). A PR that already carries a
2948
+ // pr-hero summary is by definition a re-review, so publishing it without a
2949
+ // `rereview` block renders the absence-matcher delta ("N resolved") and no
2950
+ // state block — the PR 1759 shape, observed live on PR #49. That caller
2951
+ // reconstructs the block from the run's `pipeline.json` and cannot see the
2952
+ // PR, so it asks the sequence owner — which has just read the comments — to
2953
+ // enforce the precondition and refuse before any write.
2954
+ //
2955
+ // A flag rather than an unconditional invariant, for two reasons that are
2956
+ // not stylistic — and BOTH of them are about this direction only, a
2957
+ // `rereview` block that is ABSENT. The `--pr --post` path computes its own
2958
+ // case from the same comments and reaches `rereview === undefined` only in
2959
+ // case A (no summary head AND no finding markers), so the check is
2960
+ // structurally dead there — except in one race, a summary created by a
2961
+ // concurrent run between this run's phase-B fetch and this one, where
2962
+ // aborting a review that has already been paid for would be the wrong
2963
+ // direction of error. And the existing postInlineFindings suites script
2964
+ // prior summaries with no block on purpose; the flag keeps this a
2965
+ // `post --from` rule, not a rewrite of what a first-review post means.
2966
+ //
2967
+ // Neither reason survives the trip to the OPPOSITE direction — a `rereview`
2968
+ // block whose summary has vanished — which is why that case carries its own
2969
+ // flag below instead of riding on this one. Gating it here is precisely
2970
+ // what left it structurally dead on `--pr --post`, the primary path.
2971
+ requireRereviewOnPriorSummary?: boolean;
2972
+ // Also set ONLY by `post --from` (`runPostCommand`), and deliberately NOT
2973
+ // the mirror of the flag above: unset, the vanished-summary case degrades
2974
+ // rather than passing. The two callers meet the same state having paid very
2975
+ // different prices for it — see the guard's own WHY below.
2976
+ refuseOnVanishedPriorSummary?: boolean;
2977
+ // The run was a comment-triggered (forced) run. It leaves the summary counter
2978
+ // where it was: the budget bounds automatic reviews (see nextStateReviewCount).
2979
+ force?: boolean;
2980
+ }): Promise<InlinePostOutcome> {
2981
+ const { operatorRoot, pr, headSha, doc, webUrl, spawnFn } = input;
2982
+ const ghTimeoutMs = input.ghTimeoutMs ?? COLLAPSE_GH_TIMEOUT_MS;
2983
+ const {
2984
+ plan,
2985
+ previousHeadSha,
2986
+ existingSummaryId,
2987
+ summaryBody,
2988
+ findingRefs,
2989
+ posted,
2990
+ } = await resolveInlinePostPlan(input);
2991
+ const previousState =
2992
+ summaryBody === null ? null : parseStateBlock(summaryBody);
2993
+ const postedReviewCount = nextStateReviewCount({
2994
+ existingSummaryId,
2995
+ state: previousState,
2996
+ summaryBody,
2997
+ force: input.force,
2998
+ });
2999
+
3000
+ // Before the create-first POST and before the review submission — the last
3001
+ // point at which refusing costs nothing. Keyed on `existingSummaryId`, not
3002
+ // on `previousHeadSha`: a summary whose `head=` will not parse is still a
3003
+ // prior review, and rendering the matcher delta over it is still the lie.
3004
+ if (
3005
+ input.requireRereviewOnPriorSummary === true &&
3006
+ input.rereview === undefined &&
3007
+ existingSummaryId !== null
3008
+ ) {
3009
+ throw new CliError(missingRereviewBlockMessage(pr, existingSummaryId));
3010
+ }
3011
+
3012
+ // The mirror STATE, at the same point — and deliberately NOT the mirror
3013
+ // ANSWER. The run dir CAN carry a valid `rereview` block while the summary
3014
+ // it was computed against is gone from the PR: deleted mid-run (the window
3015
+ // is real — the comments are read in phase B, the pipeline then runs 8-25
3016
+ // minutes), or `post --from` run long after `review`, which this seam
3017
+ // deliberately allows. Then `existingSummaryId === null` falls into the
3018
+ // create-first branch below and, left alone, `renderBody`/`overlayDelta`
3019
+ // publish a BRAND NEW comment full of re-review vocabulary sourced from a
3020
+ // stale directory: a delta counted in `unconfirmed`/`carried`, a `Still
3021
+ // live:` list of `R###` ids, a state block — none of it naming a thread
3022
+ // that exists.
3023
+ //
3024
+ // The two callers meet that state having paid very different prices, so
3025
+ // they answer it differently ON PURPOSE. Only `post --from` sets
3026
+ // `refuseOnVanishedPriorSummary`:
3027
+ // - `post --from` REFUSES. Nothing has been spent; the operator re-runs
3028
+ // `review --pr <n> --post` and gets a correct result for free.
3029
+ // - `--pr --post` has ALREADY paid for a full review ($2.49-$6.34 on this
3030
+ // repo). Throwing that away to avoid a stale framing is the wrong
3031
+ // direction of error — the very rule the flag above cites. So it posts,
3032
+ // with the re-review framing DROPPED (`framing` below): no delta
3033
+ // overlay, no `Still live:`, no state block. That is not a downgrade of
3034
+ // the findings, it is an accurate description of what the run now is —
3035
+ // the review this one was a re-review OF is no longer on the PR, so
3036
+ // what remains is a first review of the current state, and the findings
3037
+ // are as valid as they were a minute ago. The degradation is LOGGED,
3038
+ // never silent: a quiet downgrade would be the same class of defect as
3039
+ // a guard that never fires, which is exactly what this one was while it
3040
+ // hung off `requireRereviewOnPriorSummary`.
3041
+ //
3042
+ // Narrowed to `summary_marker` on purpose: a block whose L came from
3043
+ // `finding_markers` was ALREADY computed with no summary in sight, so a
3044
+ // missing summary at post time is agreement, not drift — and its R### ids
3045
+ // name finding threads that do still exist. Refusing OR degrading there
3046
+ // would break obligation S-A ("with the summary comment absent, L is
3047
+ // recovered from per-finding markers and the run does NOT fall to
3048
+ // first-review semantics"), which is a case the design supports rather
3049
+ // than a hazard.
3050
+ const priorSummaryVanished =
3051
+ input.rereview?.last_head_source === "summary_marker" &&
3052
+ existingSummaryId === null;
3053
+ if (priorSummaryVanished && input.refuseOnVanishedPriorSummary === true) {
3054
+ throw new CliError(vanishedPriorSummaryMessage(pr));
3055
+ }
3056
+ if (priorSummaryVanished) log(vanishedPriorSummaryDegradedMessage(pr));
3057
+
3058
+ // Every re-review-framed surface reads off THIS, never `input.rereview`
3059
+ // directly — the delta overlay, the `Still live:` list it carries, and the
3060
+ // state block appended after the report marker. The collapse loop at the
3061
+ // bottom deliberately does NOT: a verified-gone prior's ✅ reply and thread
3062
+ // resolve are bound to per-finding REVIEW threads, which the summary
3063
+ // comment's disappearance says nothing about, and `--pr --post` binds them
3064
+ // through priors it is still holding in memory. Suppressing those would
3065
+ // leave a thread that IS gone sitting open on the PR.
3066
+ const framing = priorSummaryVanished ? undefined : input.rereview;
3067
+ const rereviewDelta =
3068
+ framing === undefined
3069
+ ? undefined
3070
+ : rereviewDeltaFromProvenance(framing, doc.findings.length);
3071
+ const overlayDelta = (delta: PrCommentDelta): PrCommentDelta =>
3072
+ rereviewDelta === undefined ? delta : { ...delta, rereview: rereviewDelta };
3073
+ const byId = new Map(doc.findings.map((f) => [f.id, f]));
3074
+ const findingsFor = (refs: PrHeroFindingRef[]): Finding[] =>
3075
+ refs
3076
+ .map((ref) => {
3077
+ const found = byId.get(ref.id);
3078
+ if (found === undefined) return undefined;
3079
+ // The planner may have moved `line` onto a hunter-cited in-diff
3080
+ // proof_ref (Musive #1727). GitHub's `line` and the finding marker
3081
+ // must share that post line or a re-run duplicates. findings.json
3082
+ // keeps the original line; only the posted comment is overlaid.
3083
+ return found.line === ref.line ? found : { ...found, line: ref.line };
3084
+ })
3085
+ .filter((f): f is Finding => f !== undefined);
3086
+
3087
+ // Initial Outside Diff set: plan.issueComments stays the un-anchorable
3088
+ // bucket (field name unchanged this slice). Known before any write, so
3089
+ // the create-first POST already includes it — after the review, the
3090
+ // closing PATCH may grow it with 422-demoted findings.
3091
+ const plannedOutsideDiff = findingsFor(plan.issueComments);
3092
+
3093
+ // The state block is merged ONCE, here, and both writes append the same
3094
+ // string, so the create-first POST and the closing PATCH cannot disagree
3095
+ // about which rows exist or what their ids are. Its budget is derived from
3096
+ // the POST-shaped body, the one body known before any write (see
3097
+ // stateBlockBudget). The findings are read off the same resolved refs the
3098
+ // plan posted from, so a fresh row's locs name the line the comment sits on.
3099
+ const lineById = new Map(findingRefs.map((ref) => [ref.id, ref.line]));
3100
+ const freshChannel = (id: string): FindingChannel =>
3101
+ plan.issueComments.some((f) => f.id === id) ||
3102
+ plan.persisting.some(
3103
+ (match) => match.finding.id === id && match.posted.channel === "issue",
3104
+ )
3105
+ ? "outside"
3106
+ : "inline";
3107
+ const freshFindings: FreshStateFinding[] = doc.findings.map((f) => ({
3108
+ path: f.path,
3109
+ line: lineById.get(f.id) ?? f.line,
3110
+ proof_refs: f.proof_refs,
3111
+ tier: f.tier,
3112
+ severity: f.severity,
3113
+ claim: f.claim,
3114
+ channel: freshChannel(f.id),
3115
+ }));
3116
+ const referenceBody = renderPrComment(
3117
+ doc,
3118
+ webUrl,
3119
+ overlayDelta({ ...plan.delta, previousHeadSha }),
3120
+ plannedOutsideDiff,
3121
+ undefined,
3122
+ undefined,
3123
+ input.ciMode,
3124
+ );
3125
+ // WHY one merge function for both writes: the S1 re-merge reruns it with a
3126
+ // PATCH-sized budget and the SAME inputs, so the kept ids and hw cannot
3127
+ // drift between the POST and the PATCH.
3128
+ const mergeStateWithBudget = (
3129
+ stateBudget: number,
3130
+ ): MergedState | undefined =>
3131
+ framing === undefined
3132
+ ? undefined
3133
+ : mergeStateFindings({
3134
+ headSha: doc.head_sha,
3135
+ reviews: postedReviewCount,
3136
+ live: framing.live,
3137
+ previous: previousState,
3138
+ previousHead: previousState?.headSha ?? null,
3139
+ retiredIds: [
3140
+ ...(framing.resolved_ids ?? []),
3141
+ ...(framing.worsened ?? []).map((w) => w.priorId),
3142
+ ],
3143
+ fresh: freshFindings,
3144
+ stateBudget,
3145
+ });
3146
+ const merged = mergeStateWithBudget(stateBlockBudget(referenceBody.length));
3147
+
3148
+ const renderWithState = (
3149
+ delta: PrCommentDelta,
3150
+ outside: readonly Finding[],
3151
+ moved: string | undefined,
3152
+ urls: ReadonlyMap<string, string> | undefined,
3153
+ state: MergedState | undefined,
3154
+ compactFrom?: number,
3155
+ ): string => {
3156
+ const body = renderPrComment(
3157
+ doc,
3158
+ webUrl,
3159
+ overlayDelta(delta),
3160
+ outside,
3161
+ moved,
3162
+ urls,
3163
+ input.ciMode,
3164
+ compactFrom,
3165
+ );
3166
+ // WHY the admission block is written on BOTH paths: its `reviews` is the
3167
+ // only count a summary keeps when the count is 0. renderStateBlock omits 0
3168
+ // (parseStateBlock rejects < 1 on purpose), so a forced re-review rendered
3169
+ // through the state block would read back as "a summary exists, so one
3170
+ // review", charging an attempt that never happened. Its blocking/advisory
3171
+ // counts are only read when the state block has no findings (see
3172
+ // priorScoreForAdmission), and the first-review path already writes them
3173
+ // this way.
3174
+ const counts = tierCountsFromFindings(
3175
+ canonicalAdmissionFindings(doc.findings),
3176
+ );
3177
+ const admissionBlock = renderCiAdmissionBlock(
3178
+ doc.head_sha,
3179
+ counts,
3180
+ postedReviewCount,
3181
+ );
3182
+ if (state === undefined) {
3183
+ return `${body}${admissionBlock}`;
3184
+ }
3185
+ // The drop line sits right above the state block it accounts for. Empty
3186
+ // when the cap dropped nothing.
3187
+ const note = droppedStateNote(state.dropped);
3188
+ const noteLine = note === "" ? "" : `${note}\n`;
3189
+ return `${body}${admissionBlock}${noteLine}${renderStateBlock(doc.head_sha, state.rows, postedReviewCount, state.hw)}`;
3190
+ };
3191
+ const renderBody = (
3192
+ delta: PrCommentDelta,
3193
+ outside: readonly Finding[],
3194
+ moved: string | undefined,
3195
+ urls?: ReadonlyMap<string, string>,
3196
+ ): string => renderWithState(delta, outside, moved, urls, merged);
3197
+
3198
+ // The id this run's own creation just returned, if any — threaded to the
3199
+ // closing PATCH below so it updates THIS comment directly rather than
3200
+ // re-discovering it by marker (postPrComment's `knownCommentId`; see its
3201
+ // own WHY).
3202
+ let summaryCommentId = existingSummaryId;
3203
+ if (existingSummaryId === null) {
3204
+ const plannedDelta: PrCommentDelta = { ...plan.delta, previousHeadSha };
3205
+ const created = await postPrComment(
3206
+ operatorRoot,
3207
+ pr,
3208
+ // `movedHeadSha: undefined` — the re-read has not happened yet, and it
3209
+ // deliberately does not happen before this write. Same shape as the
3210
+ // absent link map above: the placeholder is provisional, the closing
3211
+ // PATCH is authoritative, and the re-read belongs as close to the
3212
+ // ANCHOR-BEARING call as it can get, not one write earlier.
3213
+ renderBody(plannedDelta, plannedOutsideDiff, undefined),
3214
+ spawnFn,
3215
+ );
3216
+ summaryCommentId = created.commentId;
3217
+ }
3218
+
3219
+ const reviewFindings = findingsFor(plan.reviewComments);
3220
+ const reachedIds = new Set<string>();
3221
+
3222
+ // GitHub #39 — the head re-read, HERE and not inside postPrReview, for one
3223
+ // reason that is not stylistic: postPrReview returns early on zero
3224
+ // anchorable findings without touching gh at all (spec "Zero anchorable
3225
+ // findings"), and a run with nothing to anchor STILL publishes a summary
3226
+ // comment — the ✅ clean bill included. That summary read against a head
3227
+ // the PR has since moved past is the same undisclosed staleness the issue
3228
+ // is about, so the check belongs to the sequence owner, which posts on
3229
+ // every path, rather than to the primitive that sometimes does not.
3230
+ //
3231
+ // Immediately before the review submission: this is the tightest window
3232
+ // available around the anchor-bearing call, and the window is the whole
3233
+ // point — a check run minutes earlier would answer a question about a
3234
+ // different moment. The comparison happens exactly ONCE, here, and both
3235
+ // surfaces render the same answer; deriving it twice is how two surfaces
3236
+ // start disagreeing about whether the PR moved.
3237
+ //
3238
+ // Never aborts, never filters, never re-runs anything. What a re-review
3239
+ // should DO about findings computed on a stale head is ROADMAP item 7's
3240
+ // design work, and with `commit_id` pinned (pr/pr.ts) the answer here
3241
+ // collapses to a sentence: post, pinned, and say which commit this is
3242
+ // about. Silently dropping the post would be the invisible loss this
3243
+ // project's direction-of-error rule ranks worst.
3244
+ const liveHeadSha = await ghPrHeadSha(operatorRoot, pr, { spawnFn });
3245
+ const movedHeadSha =
3246
+ liveHeadSha !== undefined && liveHeadSha !== headSha
3247
+ ? liveHeadSha
3248
+ : undefined;
3249
+
3250
+ const reviewResult = await postPrReview({
3251
+ operatorRoot,
3252
+ pr,
3253
+ headSha,
3254
+ findings: reviewFindings,
3255
+ // The FULL finding list, not just `reviewFindings` — see
3256
+ // ReviewSubmissionOutcome's WHY in pr/pr.ts (CRIT-A, verify-report-pr3
3257
+ // #3305). This is exactly the line a caller could silently narrow and
3258
+ // reintroduce the tie-dissolution bug; test/cli.test.ts's tie-repro
3259
+ // fails if this is ever swapped back to `reviewFindings`.
3260
+ allFindings: findingRefs,
3261
+ webUrl,
3262
+ spawnFn,
3263
+ });
3264
+ // On 422, reviewResult.findings JOIN the Outside Diff set instead of
3265
+ // posting as issue comments (issues #16/#17). Dedupe by id so a finding
3266
+ // cannot appear twice if it somehow sat in both buckets.
3267
+ let outsideDiff = plannedOutsideDiff;
3268
+ if (reviewResult.outcome === "posted") {
3269
+ for (const finding of reviewFindings) reachedIds.add(finding.id);
3270
+ } else {
3271
+ const stillUnmatched = new Set(
3272
+ reviewResult.findings.map((finding) => finding.id),
3273
+ );
3274
+ for (const finding of reviewFindings) {
3275
+ if (!stillUnmatched.has(finding.id)) reachedIds.add(finding.id);
3276
+ }
3277
+ const already = new Set(outsideDiff.map((finding) => finding.id));
3278
+ outsideDiff = [
3279
+ ...outsideDiff,
3280
+ ...reviewResult.findings.filter((finding) => !already.has(finding.id)),
3281
+ ];
3282
+ }
3283
+
3284
+ // Outside Diff findings reached the summary — they must not fire
3285
+ // droppedFindingIds. No rematch-before-POST: that block existed only to
3286
+ // prevent duplicate issue comments, and this slice posts none. Re-review
3287
+ // identity for the bucket is the next slice.
3288
+ for (const finding of outsideDiff) reachedIds.add(finding.id);
3289
+
3290
+ // Receipt shape unchanged this slice: issue_comment_ids stays [].
3291
+ const issueCommentIds: number[] = [];
3292
+
3293
+ const droppedFindingIds = computeDroppedFindingIds(
3294
+ [...plan.reviewComments, ...plan.issueComments],
3295
+ reachedIds,
3296
+ );
3297
+
3298
+ const commentUrlByFindingId = await buildCommentUrlMap({
3299
+ operatorRoot,
3300
+ pr,
3301
+ headSha,
3302
+ webUrl,
3303
+ spawnFn,
3304
+ persisting: plan.persisting,
3305
+ issueIdByFindingId: new Map(),
3306
+ freshlyPostedReview:
3307
+ reviewResult.outcome === "posted" ? reviewFindings : [],
3308
+ });
3309
+
3310
+ const delta: PrCommentDelta = { ...plan.delta, previousHeadSha };
3311
+ // S1 — the 422 demotion grew the Outside Diff after the POST-shaped merge,
3312
+ // so the PATCH body can be longer than the budget was sized for. Compact
3313
+ // first, with the POST merge's state: the demoted entries shrink from the
3314
+ // last one backwards (location and link only) and the first fit wins. WHY
3315
+ // compaction before re-merging: a re-merge sized from the uncompacted body
3316
+ // can leave no room for the advisory rows, and those rows are then evicted
3317
+ // for good even though compaction would have made room. Without a demotion
3318
+ // the body stays byte-identical to today's, whatever its length. The PATCH
3319
+ // is never knowingly sent above the limit.
3320
+ const grew = outsideDiff.length > plannedOutsideDiff.length;
3321
+ const renderPatch = (
3322
+ state: MergedState | undefined,
3323
+ compactFrom?: number,
3324
+ ): string =>
3325
+ renderWithState(
3326
+ delta,
3327
+ outsideDiff,
3328
+ movedHeadSha,
3329
+ commentUrlByFindingId,
3330
+ state,
3331
+ compactFrom,
3332
+ );
3333
+ let patchBody = renderPatch(merged);
3334
+ if (grew && patchBody.length > GITHUB_ISSUE_COMMENT_MAX) {
3335
+ for (let from = outsideDiff.length - 1; from >= 0; from--) {
3336
+ patchBody = renderPatch(merged, from);
3337
+ if (patchBody.length <= GITHUB_ISSUE_COMMENT_MAX) break;
3338
+ }
3339
+ // S1b — only when every entry is compacted and the body still does not
3340
+ // fit does the state shrink: re-merge with the same inputs and a budget
3341
+ // sized from the fully compacted body without its state block. The ids
3342
+ // and hw are budget-independent, and only advisory rows can be dropped.
3343
+ if (patchBody.length > GITHUB_ISSUE_COMMENT_MAX) {
3344
+ const bodyWithoutState = renderPatch(undefined, 0);
3345
+ const reMerged = mergeStateWithBudget(
3346
+ stateBlockBudget(bodyWithoutState.length),
3347
+ );
3348
+ patchBody = renderPatch(reMerged, 0);
3349
+ }
3350
+ if (patchBody.length > GITHUB_ISSUE_COMMENT_MAX) {
3351
+ process.stdout.write(
3352
+ `::warning::crysk: the summary is ${patchBody.length} characters, over GitHub's ${GITHUB_ISSUE_COMMENT_MAX}-character comment limit even with every Outside Diff entry compacted; sending it as is\n`,
3353
+ );
3354
+ }
3355
+ }
3356
+ const patched = await postPrComment(
3357
+ operatorRoot,
3358
+ pr,
3359
+ patchBody,
3360
+ spawnFn,
3361
+ summaryCommentId ?? undefined,
3362
+ );
3363
+ // `patched.action` is always "updated" once the create-first branch above
3364
+ // ran (this call PATCHes the comment it just created), which would report
3365
+ // a first-EVER run as "updated" — misleading to a human reading the log
3366
+ // or post.json. The outward-facing action names whether THIS RUN created
3367
+ // the summary at all (existingSummaryId was null before this run), not
3368
+ // which HTTP verb the LAST of its two calls happened to use.
3369
+ const summary = {
3370
+ action: existingSummaryId === null ? ("created" as const) : patched.action,
3371
+ commentId: patched.commentId,
3372
+ };
3373
+
3374
+ if (input.rereview !== undefined) {
3375
+ const targets = collapseTargets({
3376
+ verifiedGoneIds: input.rereview.resolved_ids ?? [],
3377
+ priors: input.rereviewPriors ?? [],
3378
+ posted,
3379
+ });
3380
+ // WHY one notice per run: a token that cannot resolve threads cannot do it
3381
+ // for any prior, so one line says so instead of one failure per prior.
3382
+ let threadResolveNoticeLogged = false;
3383
+ for (const target of targets) {
3384
+ if (target.channel !== "review") continue;
3385
+ // The reply is bounded AND caught, and a failure `continue`s past the
3386
+ // resolve on purpose. Resolving a thread whose ✅ reply never landed
3387
+ // closes the conversation with no explanation of why — a silent
3388
+ // resolve, which is the same false `resolved` the whole verified-gone
3389
+ // path is built to never produce. Degrading to "thread left open" is
3390
+ // always the safe direction: the finding stays visible on the PR.
3391
+ try {
3392
+ await postReviewCommentReply({
3393
+ operatorRoot,
3394
+ pr,
3395
+ inReplyTo: target.commentId,
3396
+ body:
3397
+ "✅ **RESOLVED** · verified gone\n\n" +
3398
+ "This finding was checked at the current head and is no longer present.\n",
3399
+ spawnFn,
3400
+ timeoutMs: ghTimeoutMs,
3401
+ });
3402
+ } catch (error) {
3403
+ log(
3404
+ `collapse skipped for ${target.priorId}: the verified-gone reply did ` +
3405
+ `not post (${error instanceof Error ? error.message : String(error)}) ` +
3406
+ "— thread left open",
3407
+ );
3408
+ continue;
3409
+ }
3410
+ try {
3411
+ const resolveOutcome = await resolveReviewThreadForComment({
3412
+ operatorRoot,
3413
+ pr,
3414
+ commentId: target.commentId,
3415
+ spawnFn,
3416
+ timeoutMs: ghTimeoutMs,
3417
+ });
3418
+ if (resolveOutcome === "resolved") {
3419
+ log(`resolved: review thread for ${target.priorId} (verified-gone)`);
3420
+ } else if (resolveOutcome === "already-resolved") {
3421
+ log(`resolved: thread already closed for ${target.priorId}`);
3422
+ } else {
3423
+ log(
3424
+ `resolve skipped: no review thread found for comment ${target.commentId}`,
3425
+ );
3426
+ }
3427
+ } catch (error) {
3428
+ const message = error instanceof Error ? error.message : String(error);
3429
+ // WHY a notice, not a failure: the reply is posted and the gate does not
3430
+ // depend on the resolve, so the run continues as designed.
3431
+ if (message.includes(WORKFLOW_TOKEN_CANNOT_RESOLVE)) {
3432
+ if (!threadResolveNoticeLogged) {
3433
+ threadResolveNoticeLogged = true;
3434
+ log(
3435
+ "resolve skipped: the workflow token cannot resolve review threads " +
3436
+ `(${WORKFLOW_TOKEN_CANNOT_RESOLVE}); the verified-gone replies are posted`,
3437
+ );
3438
+ }
3439
+ continue;
3440
+ }
3441
+ log(
3442
+ `resolve failed for ${target.priorId} after the verified-gone reply posted: ` +
3443
+ message,
3444
+ );
3445
+ }
3446
+ }
3447
+ }
3448
+
3449
+ // Closes a RE-review with a visible comment. Everything above only PATCHed
3450
+ // the existing summary, and an edit is invisible on GitHub: no
3451
+ // notification, no move down the timeline. With zero new findings no
3452
+ // review is submitted either, so the PR looked untouched and a reader could
3453
+ // not tell "ran and found nothing" from "never ran". A first review needs
3454
+ // none: the summary it just created is already the new comment.
3455
+ //
3456
+ // Last, after the collapse loop, so it really is the closing word. Caught
3457
+ // AND bounded, like the collapse loop's reply: the review is already paid
3458
+ // for and published, so losing the receipt must never fail the run, and a
3459
+ // catch alone cannot stop a request that is accepted but never answered.
3460
+ // As the last await here, a hang would park the caller's receipt write
3461
+ // and teardown forever.
3462
+ let closingCommentId: number | undefined;
3463
+ if (existingSummaryId !== null) {
3464
+ try {
3465
+ closingCommentId = await postIssueCommentBody(
3466
+ operatorRoot,
3467
+ pr,
3468
+ renderRereviewClosedComment({
3469
+ headSha,
3470
+ delta: overlayDelta(delta),
3471
+ newPosted: reachedIds.size,
3472
+ totalFindings: doc.findings.length,
3473
+ runStatus: doc.run_status,
3474
+ summaryUrl:
3475
+ webUrl === undefined
3476
+ ? undefined
3477
+ : findingCommentUrl(webUrl, pr, "issue", existingSummaryId),
3478
+ }),
3479
+ spawnFn,
3480
+ ghTimeoutMs,
3481
+ );
3482
+ log(`posted: re-review closing comment ${closingCommentId}`);
3483
+ } catch (error) {
3484
+ log(
3485
+ "re-review closing comment did not post " +
3486
+ `(${error instanceof Error ? error.message : String(error)}) ` +
3487
+ "— the summary was still updated",
3488
+ );
3489
+ }
3490
+ }
3491
+
3492
+ return {
3493
+ reviewOutcome: reviewResult.outcome,
3494
+ reviewFindingCount: reviewFindings.length,
3495
+ issueCommentIds,
3496
+ outsideDiffCount: outsideDiff.length,
3497
+ summary,
3498
+ delta: overlayDelta(plan.delta),
3499
+ droppedFindingIds,
3500
+ commentUrls: commentUrlByFindingId,
3501
+ movedHeadSha,
3502
+ ...(closingCommentId === undefined ? {} : { closingCommentId }),
3503
+ };
3504
+ }
3505
+
3506
+ // Maps every CURRENTLY-live finding (persisting from a prior run, or
3507
+ // freshly posted this run) to its own comment's URL, for the summary's
3508
+ // closing PATCH (Juanma's PR #2 feedback: each index line links to its own
3509
+ // comment). Two sources, none of which can be read off the plan alone:
3510
+ // - persisting matches already carry the prior comment's id/channel
3511
+ // (`plan.persisting`, from pr/inline.ts's matcher) — free, no extra fetch;
3512
+ // leftover W1 issue-comment orphans still resolve here via channel
3513
+ // "issue";
3514
+ // - fresh REVIEW comments' ids are NOT returned by `POST .../reviews` at
3515
+ // all (GitHub's response is the review object, not its comments[]), so
3516
+ // the only way to learn them is a follow-up read-only fetch, matched
3517
+ // back to a finding by the SAME marker fields the identity contract
3518
+ // already uses (path, line, this run's headSha, and the claim
3519
+ // fingerprint) — deterministic here because this run posted them
3520
+ // moments ago with exactly those fields.
3521
+ // Fresh un-anchorable findings have no per-finding comment (issues #16/#17:
3522
+ // they land in the summary Outside Diff section), so they contribute no
3523
+ // url; the index line stays unlinked. `issueIdByFindingId` is kept so a
3524
+ // leftover caller can still hand ids through; postInlineFindings passes
3525
+ // an empty map.
3526
+ // `webUrl === undefined` skips all of it: no repo web url means no comment
3527
+ // URL is buildable, and renderPrComment already degrades to plain text when
3528
+ // a finding's id is absent from the map, never a broken link.
3529
+ async function buildCommentUrlMap(input: {
3530
+ operatorRoot: string;
3531
+ pr: number;
3532
+ headSha: string;
3533
+ webUrl: string | undefined;
3534
+ spawnFn?: typeof Bun.spawn;
3535
+ persisting: PostPlan["persisting"];
3536
+ issueIdByFindingId: Map<string, number>;
3537
+ freshlyPostedReview: Finding[];
3538
+ }): Promise<Map<string, string>> {
3539
+ const { operatorRoot, pr, headSha, webUrl, spawnFn } = input;
3540
+ const urls = new Map<string, string>();
3541
+ if (webUrl === undefined) return urls;
3542
+ for (const match of input.persisting) {
3543
+ urls.set(
3544
+ match.finding.id,
3545
+ findingCommentUrl(webUrl, pr, match.posted.channel, match.posted.id),
3546
+ );
3547
+ }
3548
+ for (const [findingId, id] of input.issueIdByFindingId) {
3549
+ urls.set(findingId, findingCommentUrl(webUrl, pr, "issue", id));
3550
+ }
3551
+ if (input.freshlyPostedReview.length > 0) {
3552
+ const freshReview = await fetchPrReviewComments(operatorRoot, pr, {
3553
+ spawnFn,
3554
+ timeoutMs: POSTING_GH_TIMEOUT_MS,
3555
+ });
3556
+ for (const finding of input.freshlyPostedReview) {
3557
+ const fingerprint = claimFingerprint(finding.claim);
3558
+ const match = freshReview.find((c) => {
3559
+ const marker = parseFindingMarker(c.body);
3560
+ return (
3561
+ marker !== null &&
3562
+ marker.path === finding.path &&
3563
+ marker.line === finding.line &&
3564
+ marker.headSha === headSha &&
3565
+ marker.c === fingerprint
3566
+ );
3567
+ });
3568
+ if (match) {
3569
+ urls.set(finding.id, findingCommentUrl(webUrl, pr, "review", match.id));
3570
+ }
3571
+ }
3572
+ }
3573
+ return urls;
3574
+ }
3575
+
3576
+ // The `sessionFailed` guard (spec "sessionFailed suppresses all posting"):
3577
+ // the single decision point for BOTH callers on whether to invoke
3578
+ // postInlineFindings at all. `null` means "skipped, nothing was posted, zero
3579
+ // HTTP calls were made" — the exact shape the spec's scenario asserts.
3580
+ //
3581
+ // Neither `requireRereviewOnPriorSummary` nor `refuseOnVanishedPriorSummary`
3582
+ // is declared here, and that absence is the contract, not an oversight: this
3583
+ // is the `--pr --post` entry point, the one that has already paid for a full
3584
+ // review, and both flags exist to make `post --from` refuse where refusing is
3585
+ // free. See their WHYs on postInlineFindings.
3586
+ export async function postInlineIfEligible(input: {
3587
+ sessionFailed: boolean;
3588
+ skippedReason: string;
3589
+ operatorRoot: string;
3590
+ pr: number;
3591
+ headSha: string;
3592
+ doc: FindingsDocument;
3593
+ diffPatch: string;
3594
+ webUrl: string | undefined;
3595
+ spawnFn?: typeof Bun.spawn;
3596
+ rereview?: RereviewProvenance;
3597
+ rereviewPriors?: readonly {
3598
+ id: string;
3599
+ claim: string;
3600
+ locs: readonly string[];
3601
+ }[];
3602
+ // S4: the CI mode the summary's footer names. Omitted is advisory, which is
3603
+ // what the local `post` command gets.
3604
+ ciMode?: CiMode;
3605
+ // Forwarded to postInlineFindings: a forced run leaves the summary counter alone.
3606
+ force?: boolean;
3607
+ }): Promise<InlinePostOutcome | null> {
3608
+ if (input.sessionFailed) {
3609
+ log(input.skippedReason);
3610
+ return null;
3611
+ }
3612
+ return postInlineFindings(input);
3613
+ }
3614
+
3615
+ // post.json — the receipt (design's File Changes table): channel, comment
3616
+ // ids, demotions, mirroring pipeline.json's provenance role so the
3617
+ // idempotency proof (WU7/4.4) can read back exactly what a run posted
3618
+ // without re-deriving it from GitHub.
3619
+ export async function writePostReceipt(
3620
+ runDir: string,
3621
+ pr: number,
3622
+ headSha: string,
3623
+ outcome: InlinePostOutcome,
3624
+ ): Promise<void> {
3625
+ const receipt = {
3626
+ pr,
3627
+ head_sha: headSha,
3628
+ generated_at: new Date().toISOString(),
3629
+ review: {
3630
+ outcome: outcome.reviewOutcome,
3631
+ finding_count: outcome.reviewFindingCount,
3632
+ },
3633
+ issue_comment_ids: outcome.issueCommentIds,
3634
+ summary_comment: outcome.summary,
3635
+ delta: outcome.delta,
3636
+ dropped_finding_ids: outcome.droppedFindingIds,
3637
+ };
3638
+ await Bun.write(
3639
+ path.join(runDir, "post.json"),
3640
+ `${JSON.stringify(receipt, null, 2)}\n`,
3641
+ );
3642
+ }