crysk 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +610 -2
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/adjudicator-dtg2axnh.md +86 -0
  10. package/dist/admission-config.example-a9vqmmad.json +9 -0
  11. package/dist/ci-admission-camfbx2b.md +122 -0
  12. package/dist/cli.js +42292 -0
  13. package/dist/consolidate-ac0mnfyj.md +24 -0
  14. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  15. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  16. package/dist/deep-review-parity-0ec904db.md +120 -0
  17. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  18. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  19. package/dist/index.js +20190 -0
  20. package/dist/opencode-ci-7b0be64p.md +141 -0
  21. package/dist/review-refuter-j4e9gezy.md +71 -0
  22. package/dist/scout-yvp153q7.md +140 -0
  23. package/dist/summarizer-zca44nxa.md +18 -0
  24. package/dist/workflow-w1g9szna.yml +151 -0
  25. package/package.json +82 -4
  26. package/prompts/consolidate.md +24 -0
  27. package/prompts/default/PROVENANCE.md +18 -0
  28. package/prompts/default/deep-review-lifecycle.md +362 -0
  29. package/prompts/default/deep-review-logic.md +156 -0
  30. package/prompts/default/deep-review-parity.md +120 -0
  31. package/prompts/default/deep-review-reliability.md +125 -0
  32. package/prompts/default/deep-review-resilience.md +118 -0
  33. package/prompts/default/review-refuter.md +71 -0
  34. package/prompts/scout.md +140 -0
  35. package/prompts/summarizer.md +18 -0
  36. package/skills/crysk/SKILL.md +74 -0
  37. package/skills/crysk-ci-setup/SKILL.md +134 -0
  38. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  39. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  40. package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
  41. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  42. package/skills/crysk-loop/SKILL.md +496 -0
  43. package/skills/crysk-loop/adjudicator.md +86 -0
  44. package/skills/crysk-pr/SKILL.md +66 -0
  45. package/src/agent-env.ts +1084 -0
  46. package/src/asset-manifest.ts +83 -0
  47. package/src/assets.d.ts +6 -0
  48. package/src/assets.ts +183 -0
  49. package/src/brand-paths.ts +155 -0
  50. package/src/brand.ts +255 -0
  51. package/src/ci/admission-ledger.ts +350 -0
  52. package/src/ci/classify-error.ts +73 -0
  53. package/src/ci/cli-record.ts +271 -0
  54. package/src/ci/force-comment.ts +39 -0
  55. package/src/ci/gates.ts +923 -0
  56. package/src/ci/outcome.ts +2181 -0
  57. package/src/ci/override.ts +187 -0
  58. package/src/ci/publish.ts +1639 -0
  59. package/src/ci/reporter.ts +626 -0
  60. package/src/ci/review-admission.ts +901 -0
  61. package/src/ci/review-levels.ts +310 -0
  62. package/src/ci/review-policy.ts +18 -0
  63. package/src/ci/review-risk.ts +184 -0
  64. package/src/ci/setup.ts +844 -0
  65. package/src/ci/trigger.ts +1353 -0
  66. package/src/cli.ts +348 -0
  67. package/src/commands/activity.ts +67 -0
  68. package/src/commands/ci-setup-questions.ts +397 -0
  69. package/src/commands/ci-setup.ts +381 -0
  70. package/src/commands/config.ts +99 -0
  71. package/src/commands/doctor.ts +108 -0
  72. package/src/commands/init.ts +139 -0
  73. package/src/commands/mcp.ts +10 -0
  74. package/src/commands/menu.ts +129 -0
  75. package/src/commands/post.ts +302 -0
  76. package/src/commands/skills.ts +83 -0
  77. package/src/commands/status.ts +173 -0
  78. package/src/commands/triage.ts +342 -0
  79. package/src/commands/uninstall.ts +37 -0
  80. package/src/commands/upgrade.ts +214 -0
  81. package/src/commands/usage.ts +98 -0
  82. package/src/compare/compare.ts +28 -0
  83. package/src/compare/floor-test.ts +471 -0
  84. package/src/compare/martian-adapter.ts +80 -0
  85. package/src/config/config.ts +267 -0
  86. package/src/corpus/corpus.ts +1094 -0
  87. package/src/corpus/preflight.ts +1789 -0
  88. package/src/diversity/accounting.ts +90 -0
  89. package/src/diversity/adjudication.ts +145 -0
  90. package/src/diversity/admission.ts +60 -0
  91. package/src/diversity/benchmark.ts +195 -0
  92. package/src/diversity/clustering.ts +285 -0
  93. package/src/diversity/errors.ts +7 -0
  94. package/src/diversity/identity.ts +285 -0
  95. package/src/diversity/index.ts +11 -0
  96. package/src/diversity/pipeline-integration.ts +448 -0
  97. package/src/diversity/projection.ts +57 -0
  98. package/src/diversity/self-contained.ts +68 -0
  99. package/src/diversity/target-validation.ts +179 -0
  100. package/src/doctor-migration.ts +209 -0
  101. package/src/doctor.ts +723 -0
  102. package/src/errors.ts +83 -0
  103. package/src/execution/admission.ts +75 -0
  104. package/src/execution/atomic-write.ts +35 -0
  105. package/src/execution/attempt-evidence.ts +415 -0
  106. package/src/execution/bucket-id.ts +136 -0
  107. package/src/execution/concurrency-limiter.ts +175 -0
  108. package/src/execution/contracts.ts +443 -0
  109. package/src/execution/failure-classification.ts +42 -0
  110. package/src/execution/failure-policy.ts +240 -0
  111. package/src/execution/harness.ts +2548 -0
  112. package/src/execution/settlement.ts +348 -0
  113. package/src/execution/spawned-process.ts +66 -0
  114. package/src/execution/spend-limiter.ts +424 -0
  115. package/src/execution/step-artifacts.ts +55 -0
  116. package/src/execution/usage-normalized.ts +469 -0
  117. package/src/git/git.ts +396 -0
  118. package/src/git/identity.ts +64 -0
  119. package/src/git/refs.ts +140 -0
  120. package/src/home-preflight.ts +443 -0
  121. package/src/home.ts +243 -0
  122. package/src/ignore-file.ts +336 -0
  123. package/src/ignore-read.ts +118 -0
  124. package/src/index.ts +34 -0
  125. package/src/legacy-launchd.ts +29 -0
  126. package/src/mcp/mcp.ts +150 -0
  127. package/src/mcp/preflight.ts +407 -0
  128. package/src/menu-context.ts +192 -0
  129. package/src/model/catalog.ts +251 -0
  130. package/src/model/exec-snapshots.ts +390 -0
  131. package/src/model/free-discovery.ts +302 -0
  132. package/src/model/provider-capabilities.ts +814 -0
  133. package/src/model/routing.ts +600 -0
  134. package/src/pr/admission.ts +847 -0
  135. package/src/pr/ci-admission-gate.ts +665 -0
  136. package/src/pr/ci-publish.ts +76 -0
  137. package/src/pr/discovery.ts +432 -0
  138. package/src/pr/inline.ts +507 -0
  139. package/src/pr/plan.ts +366 -0
  140. package/src/pr/posting.ts +115 -0
  141. package/src/pr/pr-status.ts +787 -0
  142. package/src/pr/pr.ts +3642 -0
  143. package/src/pr/preflight.ts +1031 -0
  144. package/src/pr/publish-outcome.ts +361 -0
  145. package/src/pr/range.ts +119 -0
  146. package/src/pr/reverts-preflight.ts +606 -0
  147. package/src/pr/reverts.ts +377 -0
  148. package/src/pr/review-pr.ts +927 -0
  149. package/src/pr/status.ts +154 -0
  150. package/src/pr/target.ts +388 -0
  151. package/src/pr/teardown.ts +437 -0
  152. package/src/pr/worktree-setup.ts +60 -0
  153. package/src/production-runtime.ts +1877 -0
  154. package/src/progress.ts +487 -0
  155. package/src/rereview/adjudicate.ts +89 -0
  156. package/src/rereview/classify.ts +362 -0
  157. package/src/rereview/identity.ts +211 -0
  158. package/src/rereview/plan.ts +308 -0
  159. package/src/rereview/prepare.ts +1025 -0
  160. package/src/rereview/state.ts +767 -0
  161. package/src/rereview/verify.ts +241 -0
  162. package/src/review/boundary.ts +105 -0
  163. package/src/review/consolidate.ts +246 -0
  164. package/src/review/dedupe.ts +368 -0
  165. package/src/review/drafts.ts +448 -0
  166. package/src/review/findings-conformance.ts +120 -0
  167. package/src/review/findings.ts +714 -0
  168. package/src/review/pipeline.ts +3977 -0
  169. package/src/review/preflight.ts +3575 -0
  170. package/src/review/prompt-set.ts +177 -0
  171. package/src/review/proof-refs.ts +187 -0
  172. package/src/review/report.ts +1821 -0
  173. package/src/review/review.ts +490 -0
  174. package/src/review/root-cause.ts +120 -0
  175. package/src/review/route-preflight.ts +289 -0
  176. package/src/review/run.ts +601 -0
  177. package/src/review/scout.ts +323 -0
  178. package/src/review/size-gate.ts +595 -0
  179. package/src/review/spec.ts +235 -0
  180. package/src/review/step-runner.ts +233 -0
  181. package/src/runner-authority.ts +596 -0
  182. package/src/security/binding-policy.ts +115 -0
  183. package/src/security/credential-broker.ts +773 -0
  184. package/src/security/evidence-redaction.ts +62 -0
  185. package/src/security/execution-authority.ts +27 -0
  186. package/src/security/redact.ts +71 -0
  187. package/src/security/workspace-read-broker.ts +466 -0
  188. package/src/server/client.ts +190 -0
  189. package/src/server/preflight.ts +217 -0
  190. package/src/server/server.ts +327 -0
  191. package/src/signal-handler.ts +50 -0
  192. package/src/store/activity.ts +413 -0
  193. package/src/store/backfill-preflight.ts +49 -0
  194. package/src/store/backfill.ts +141 -0
  195. package/src/store/gc-preflight.ts +206 -0
  196. package/src/store/gc.ts +424 -0
  197. package/src/store/metrics-preflight.ts +229 -0
  198. package/src/store/metrics.ts +236 -0
  199. package/src/store/preflight.ts +748 -0
  200. package/src/store/store.ts +693 -0
  201. package/src/system-tools.ts +355 -0
  202. package/src/transport-registry.ts +1124 -0
  203. package/src/transports/claude-code-cli.ts +1348 -0
  204. package/src/transports/opencode-admission.ts +515 -0
  205. package/src/transports/opencode-client.ts +3328 -0
  206. package/src/transports/opencode-evidence.ts +557 -0
  207. package/src/transports/opencode-mcp.ts +248 -0
  208. package/src/transports/opencode-sdk.ts +2294 -0
  209. package/src/transports/opencode-server.ts +535 -0
  210. package/src/triage/adjudication.ts +113 -0
  211. package/src/triage/reply.ts +125 -0
  212. package/src/triage/triage.ts +255 -0
  213. package/src/ui/activity.ts +173 -0
  214. package/src/ui/config-edit.ts +816 -0
  215. package/src/ui/config.ts +462 -0
  216. package/src/ui/menu.ts +1325 -0
  217. package/src/ui/plan.ts +1039 -0
  218. package/src/ui/primitives.ts +300 -0
  219. package/src/ui/progress.ts +298 -0
  220. package/src/ui/result.ts +552 -0
  221. package/src/ui/review-menu.ts +312 -0
  222. package/src/ui/select.ts +528 -0
  223. package/src/ui/tree.ts +178 -0
  224. package/src/uninstaller.ts +479 -0
  225. package/src/updater.ts +836 -0
  226. package/src/usage.ts +77 -0
  227. package/src/watch/preflight.ts +1389 -0
  228. package/src/watch/watch.ts +1235 -0
  229. package/src/wizard.ts +877 -0
@@ -0,0 +1,361 @@
1
+ // PR mode's post-pipeline tail (ROADMAP B1): the artifact writes, the
2
+ // the canonical store, posting, the terminal summary,
3
+ // CI publishing, and the CI admission ledger's terminal settlement — all of
4
+ // it runs once `runPipeline` has returned. Extracted out of reviewPr()
5
+ // (src/pr/review-pr.ts, cli-decomp/review-pr-publish-outcome): identifiers
6
+ // moved onto explicit parameters, control flow otherwise unchanged. The WHY
7
+ // comments below move with the code they explain, including their original
8
+ // step numbers (12-16) from reviewPr()'s own numbered sequence.
9
+ //
10
+ // The hazard this split has to preserve: reviewPr() declares `let result`
11
+ // and `let posted` OUTSIDE its try block because BOTH of its finally blocks
12
+ // (settleCommitStatusAndLedger, finalizePrReviewRun) read them on every exit
13
+ // path, including a throw partway through this tail. `result` is only ever
14
+ // READ here — it is assigned earlier, by the pipeline call this module never
15
+ // touches — so it stays a plain input, guarded the same way reviewPr() used
16
+ // to guard it. `posted` is WRITTEN here, the instant `postFindingsIfEnabled`
17
+ // resolves; a function that only RETURNED it at the end would lose that
18
+ // write on a later throw (e.g. from publishCiReviewIfEligible or a
19
+ // settleCiAdmissionLedger call), leaving the commit-status finally believing
20
+ // nothing was posted when it actually was. `onPosted` is the sink:
21
+ // reviewPr()'s own callback assigns its outer `posted` the moment this
22
+ // module does, so a throw one line later still leaves the right value
23
+ // behind. `ciAdmissionLedger` needs no equivalent sink — settleCiAdmissionLedger
24
+ // mutates `state.record` on the SAME object reviewPr() already holds, never
25
+ // reassigning the binding itself, so passing the reference through is enough.
26
+
27
+ import path from "node:path";
28
+ import { classifyCliError } from "#ci/classify-error";
29
+ import { recordReviewDelivered, writeCliRecord } from "#ci/cli-record";
30
+ import { ciExitCode } from "#ci/gates";
31
+ import {
32
+ ingestReviewMetrics,
33
+ notionalCostInput,
34
+ persistCanonicalReview,
35
+ } from "#config/config";
36
+ import { gitRemoteWebUrl } from "#git/git";
37
+ import { engineIdentity } from "#git/identity";
38
+ import type { FreeRouteBilling } from "#model/free-discovery";
39
+ import {
40
+ type CiAdmissionLedgerState,
41
+ settleCiAdmissionLedger,
42
+ } from "#pr/admission";
43
+ import { publishCiReviewIfEligible } from "#pr/ci-publish";
44
+ import type { PrDiscoveryResult } from "#pr/discovery";
45
+ import { type InlinePostOutcome, postingExitCode } from "#pr/inline";
46
+ import { type PostingStageResult, postFindingsIfEnabled } from "#pr/posting";
47
+ import type { CiMode } from "#pr/preflight";
48
+ import { unresolvedBlockingCount } from "#rereview/state";
49
+ import type { Telemetry } from "#review/findings";
50
+ import type { PipelineResult } from "#review/pipeline";
51
+ import type { CliOptions } from "#review/preflight";
52
+ import type { ParsedAgent, PromptSetIdentity } from "#review/prompt-set";
53
+ import {
54
+ type DiffStat,
55
+ envelopeModel,
56
+ type estimateCost,
57
+ incompleteReviewAnnotation,
58
+ } from "#review/report";
59
+ import { buildTelemetry, writeRunFindings, writeRunReport } from "#review/run";
60
+ import { log, styleEnabled } from "#ui/primitives";
61
+ import { type ResultLinks, renderResult } from "#ui/result";
62
+ import { freeBillingMode } from "#ui/select";
63
+ import { CliError } from "../errors";
64
+ import { prheroLayout } from "../home-preflight";
65
+
66
+ export interface PublishRunOutcomeInput {
67
+ result: PipelineResult | undefined;
68
+ started: number;
69
+ indexMs: number;
70
+ runDir: string;
71
+ prNumber: number;
72
+ diffFromSha: string;
73
+ headSha: string;
74
+ options: CliOptions;
75
+ agentFiles: Map<string, ParsedAgent>;
76
+ promptSet: PromptSetIdentity;
77
+ operatorRoot: string;
78
+ baseRef: string;
79
+ diffStat: DiffStat;
80
+ droppedPaths: string[];
81
+ diffPatch: string;
82
+ home: string;
83
+ repoId: string | null;
84
+ postEnabled: boolean;
85
+ rereview: PrDiscoveryResult["rereview"];
86
+ phaseB: PrDiscoveryResult["phaseB"];
87
+ gitDirOwner: string;
88
+ worktreePath: string;
89
+ isCi: boolean;
90
+ // The run's one resolved CI mode (resolveCiMode, reviewPr). The report, the
91
+ // summary comment and the step summary all name it; nothing re-resolves it.
92
+ ciMode: CiMode;
93
+ estimate: ReturnType<typeof estimateCost>;
94
+ // W3-FOOTER: the plan's free-route count. Absent means no free share, and the
95
+ // footer keeps its subscription wording.
96
+ freeRoute?: FreeRouteBilling;
97
+ ciAdmissionLedger: CiAdmissionLedgerState | null;
98
+ // Fired the instant `posted` would have been assigned inside reviewPr()
99
+ // itself — see the header above.
100
+ onPosted: (posted: InlinePostOutcome | null) => void;
101
+ // S4's sibling sink, for the same reason as onPosted: the commit status
102
+ // (settleCommitStatusAndLedger) reads this count in reviewPr()'s finally,
103
+ // and a throw later in this tail must not leave it unknown. The count is the
104
+ // gate's UNRESOLVED blocking count (rereview/state.ts), not this run's survivors.
105
+ onBlockingCount: (count: number) => void;
106
+ // Test-only seam (default: the real postFindingsIfEnabled). The posting stage
107
+ // reaches gh with no offline seam of its own, so the suite passes a fake that
108
+ // rejects or resolves, the way it drives the throw and the delivery point.
109
+ postFindings?: typeof postFindingsIfEnabled;
110
+ }
111
+
112
+ export async function publishRunOutcome(
113
+ input: PublishRunOutcomeInput,
114
+ ): Promise<number> {
115
+ if (input.result === undefined) {
116
+ // An engine invariant, not the reader's configuration: the record names it as
117
+ // the pr-hero defect class (T2d-1).
118
+ throw new CliError("internal: pipeline returned no result", {
119
+ cls: { kind: "invariant" },
120
+ });
121
+ }
122
+ const result = input.result;
123
+ const wallMs = Math.round(performance.now() - input.started);
124
+
125
+ // 12 — the artifact and the report, exactly as local mode writes them.
126
+ // Unlike local mode's hardcoded 0, PR mode BUILDS the worktree's index
127
+ // when it is missing, so the init cost is real and measured. Disk stays
128
+ // unreported, and the mode is the same synchronous build.
129
+ const telemetry: Telemetry = buildTelemetry(result, wallMs, input.indexMs);
130
+ const { doc, findingsPath } = await writeRunFindings({
131
+ runDir: input.runDir,
132
+ result,
133
+ pr: input.prNumber,
134
+ baseSha: input.diffFromSha,
135
+ headSha: input.headSha,
136
+ options: input.options,
137
+ agentFiles: input.agentFiles,
138
+ promptSet: input.promptSet,
139
+ engine: await engineIdentity(),
140
+ telemetry,
141
+ });
142
+ // S4: the gate's unresolved count, read by the commit status in teardown.
143
+ // It is this run's blocking survivors PLUS every live blocking prior that no
144
+ // verifier verdict and no deletion cleared (rereview/state.ts owns the rule and
145
+ // its dedupe key). Counting only this run's survivors read green on a
146
+ // same-head forced re-review and on any re-review that carried a blocking
147
+ // prior. Computed once here, and fired the moment the doc exists, so a later
148
+ // throw still leaves the gate a count to read.
149
+ const blockingCount = unresolvedBlockingCount(
150
+ doc.findings,
151
+ result.gatePriors ?? [],
152
+ );
153
+ input.onBlockingCount(blockingCount);
154
+ const reportPath = await writeRunReport({
155
+ runDir: input.runDir,
156
+ doc,
157
+ repo: path.basename(input.operatorRoot),
158
+ base: input.baseRef,
159
+ head: `PR #${input.prNumber}`,
160
+ diffStat: input.diffStat,
161
+ droppedPaths: input.droppedPaths,
162
+ result,
163
+ wallMs,
164
+ ciMode: input.ciMode,
165
+ });
166
+ // The delivery point when posting is off: nothing is posted, so the written
167
+ // artifacts are the delivery. Written after writeRunReport, never before, so a
168
+ // failed artifact write leaves no record of a delivery. A failed session keeps the
169
+ // hunters-failed record that reviewPr wrote when the pipeline returned.
170
+ if (!input.postEnabled && !result.sessionFailed) {
171
+ recordReviewDelivered(input.headSha);
172
+ }
173
+
174
+ // 13 — canonical product store & observability metrics.
175
+ persistCanonicalReview({
176
+ home: input.home,
177
+ repoId: input.repoId,
178
+ runDir: input.runDir,
179
+ checkoutPath: input.operatorRoot,
180
+ doc,
181
+ perAgent: result.perAgent,
182
+ diffFromSha: input.diffFromSha,
183
+ log,
184
+ });
185
+ ingestReviewMetrics({
186
+ dbPath: prheroLayout(input.home).metricsDbPath,
187
+ repoId: input.repoId,
188
+ runDir: input.runDir,
189
+ checkoutPath: input.operatorRoot,
190
+ doc,
191
+ perAgent: result.perAgent,
192
+ log,
193
+ });
194
+
195
+ // 14 — the posting, only when asked. Hoisted `postedWebUrl` out of the
196
+ // stage ONLY so step 15 can reuse it: when posting ran, the terminal's
197
+ // links must be built from the SAME web url the comments were
198
+ // published against. See postFindingsIfEnabled (src/pr/posting.ts) for
199
+ // the full rationale.
200
+ // Only the posting call is wrapped. A throw before the delivery point is the
201
+ // posting's own failure, so its record names the step and the publisher can say
202
+ // the review stopped while posting. A throw after it keeps reviewed (see
203
+ // onDelivered below), so no posting record replaces it.
204
+ // The error is rethrown unchanged, and no stage around this call is wrapped.
205
+ let postingResult: PostingStageResult;
206
+ let delivered = false;
207
+ try {
208
+ postingResult = await (input.postFindings ?? postFindingsIfEnabled)({
209
+ postEnabled: input.postEnabled,
210
+ sessionFailed: result.sessionFailed,
211
+ operatorRoot: input.operatorRoot,
212
+ pr: input.prNumber,
213
+ headSha: input.headSha,
214
+ doc,
215
+ diffPatch: input.diffPatch,
216
+ runDir: input.runDir,
217
+ rereview: input.rereview,
218
+ rereviewPriors: input.phaseB?.priors,
219
+ // A comment-triggered run: its summary counter stays where it was.
220
+ force: input.options.force === true,
221
+ // THE delivery point when posting is on: the findings POST has resolved, so
222
+ // the review is delivered. It fires before the local receipt is written, so a
223
+ // receipt write that throws is a failure after delivery. A failed session never
224
+ // reaches it.
225
+ onDelivered: () => {
226
+ recordReviewDelivered(input.headSha);
227
+ delivered = true;
228
+ },
229
+ ciMode: input.ciMode,
230
+ });
231
+ } catch (error) {
232
+ if (!delivered) {
233
+ writeCliRecord({
234
+ v: 1,
235
+ outcome: "error",
236
+ cls: classifyCliError(error),
237
+ params: { step: "posting the review" },
238
+ });
239
+ }
240
+ throw error;
241
+ }
242
+ // The hazard this whole module exists for: fire the sink IMMEDIATELY, at
243
+ // the exact point reviewPr() used to assign its own `posted` variable —
244
+ // not at the end of this function, and not via the return value — so a
245
+ // throw from anything below (publishCiReviewIfEligible, a
246
+ // settleCiAdmissionLedger call) still leaves reviewPr()'s outer `posted`
247
+ // correct for its finally block.
248
+ const posted = postingResult.posted;
249
+ input.onPosted(posted);
250
+ const postedWebUrl = postingResult.postedWebUrl;
251
+
252
+ // 15 — the summary. One shared renderer with local mode; the mode-specific parts
253
+ // (the worktree hint) ride in as optional inputs. The `posted:` line that
254
+ // used to sit here is GONE on purpose: step 14 already printed a richer one
255
+ // at the moment it happened, and two differently-worded reports of the same
256
+ // POST read as two postings. What this block keeps is the durable trace —
257
+ // post.json in the artifact list below.
258
+ //
259
+ // The links, in the order that keeps them honest: `gh`'s answer when posting
260
+ // already paid for it, otherwise the free git-remote derivation — so a run
261
+ // WITHOUT --post still prints a clickable url for every finding, which is
262
+ // the whole reason repoWebUrlFromRemote exists. No pushed-ness check here
263
+ // (unlike local mode): a PR head came out of `refs/pull/<n>/head`, so origin
264
+ // has it by construction.
265
+ const webUrl = postedWebUrl ?? (await gitRemoteWebUrl(input.operatorRoot));
266
+ const links: ResultLinks | undefined =
267
+ webUrl === undefined
268
+ ? undefined
269
+ : {
270
+ webUrl,
271
+ headSha: input.headSha,
272
+ pr: input.prNumber,
273
+ // Only when this run actually posted: a comment url for a comment
274
+ // that does not exist is the dead link the whole degradation rule
275
+ // exists to prevent. Absent ids fall through to a blob link.
276
+ ...(posted ? { commentUrls: posted.commentUrls } : {}),
277
+ };
278
+ for (const line of renderResult({
279
+ doc,
280
+ costUsd: result.usage.cost_usd_est,
281
+ ...notionalCostInput(result),
282
+ ...(input.freeRoute === undefined
283
+ ? {}
284
+ : { billing: freeBillingMode(input.freeRoute) }),
285
+ wallMs,
286
+ estimate: { low: input.estimate.low, high: input.estimate.high },
287
+ runDir: input.runDir,
288
+ artifacts: [
289
+ path.basename(reportPath),
290
+ path.basename(findingsPath),
291
+ ...(posted ? ["post.json"] : []),
292
+ ],
293
+ worktree: {
294
+ gitDirOwner: input.gitDirOwner,
295
+ worktreePath: input.worktreePath,
296
+ },
297
+ ...(links === undefined ? {} : { links }),
298
+ // GitHub #39. Only a run that actually POSTED can know this — the
299
+ // re-read lives in the posting sequence — so a run without --post
300
+ // never claims the head moved, which is correct: it published nothing
301
+ // that could go stale.
302
+ ...(posted?.movedHeadSha === undefined
303
+ ? {}
304
+ : { movedHeadSha: posted.movedHeadSha }),
305
+ sessionFailed: result.sessionFailed,
306
+ ...(result.unresolved.length > 0 ? { unresolved: result.unresolved } : {}),
307
+ styles: styleEnabled(),
308
+ })) {
309
+ log(line);
310
+ }
311
+ // An incomplete review, or a step that failed on a complete one, is announced where the
312
+ // Actions UI lists it, with the provider's words for each failed agent. Only under CI: a
313
+ // local run already prints the same sentence in the result block above.
314
+ if (input.isCi) {
315
+ const annotation = incompleteReviewAnnotation(doc);
316
+ if (annotation !== undefined) process.stdout.write(`${annotation}\n`);
317
+ }
318
+ // 16 — CI headless publishing (ROADMAP Pillar 3). `posted?.delta`
319
+ // reuses postInlineFindings' own re-review delta — no separate
320
+ // computation. See publishCiReviewIfEligible (src/pr/ci-publish.ts)
321
+ // for the full rationale.
322
+ await publishCiReviewIfEligible({
323
+ isCi: input.isCi,
324
+ sessionFailed: result.sessionFailed,
325
+ prNumber: input.prNumber,
326
+ headSha: input.headSha,
327
+ findings: doc.findings,
328
+ costUsdEst: result.usage.cost_usd_est,
329
+ wallMs,
330
+ model: envelopeModel(input.options, input.agentFiles),
331
+ webUrl,
332
+ delta: posted?.delta,
333
+ runDir: input.runDir,
334
+ stepSummaryFlag: input.options.stepSummary,
335
+ ciMode: input.ciMode,
336
+ });
337
+ if (result.sessionFailed) {
338
+ await settleCiAdmissionLedger(
339
+ input.ciAdmissionLedger,
340
+ "failed",
341
+ "every hunter failed",
342
+ );
343
+ return 1;
344
+ }
345
+ await settleCiAdmissionLedger(
346
+ input.ciAdmissionLedger,
347
+ "completed",
348
+ "review complete",
349
+ );
350
+ // Assistant posture (spec 2.1): in CI mode, exit 0 even with blocking
351
+ // findings — ciExitCode only fails on a fatal session failure (already
352
+ // returned above) or a genuine posting drop (design D6). Outside CI,
353
+ // postingExitCode keeps its existing behavior unchanged.
354
+ return input.isCi
355
+ ? ciExitCode({
356
+ sessionFailed: result.sessionFailed,
357
+ droppedFindingIds: posted?.droppedFindingIds.length ?? 0,
358
+ blockingCount,
359
+ })
360
+ : postingExitCode(posted);
361
+ }
@@ -0,0 +1,119 @@
1
+ // PR mode's fetch + range resolution (step 4 of reviewPr(), plus the eager
2
+ // non-CI `.prheroignore` read from step 1). Relocated out of reviewPr()
3
+ // (src/pr/review-pr.ts): identifiers moved onto explicit parameters, control
4
+ // flow and WHY comments unchanged.
5
+ //
6
+ // Two roots run through this module, matching reviewPr()'s own header:
7
+ // `operatorRoot` (the eager local ignore read, O-8) and `gitDirOwner` (the
8
+ // fetch and every object-db read below it, W3).
9
+
10
+ import {
11
+ type GitRunner,
12
+ readBaseRefIgnoreRules,
13
+ resolveCommit,
14
+ resolveDiffFrom,
15
+ } from "#git/git";
16
+ import { fetchPrRefs } from "#pr/pr";
17
+ import type { PrTarget } from "#pr/preflight";
18
+ import { assertDistinctRange } from "#review/run";
19
+ import type { IgnoreFileReadResult } from "../ignore-read";
20
+
21
+ // Invariant 7 (O-8): the PR author must never be able to choose which
22
+ // `.prheroignore` governs their own review, so this read is ALWAYS
23
+ // `operatorRoot` — the operator's own checkout — never `worktreePath` (the
24
+ // PR's own tree, which does not even exist yet at the point this runs).
25
+ // `readLocal` is injectable so a test can prove which root's rules actually
26
+ // come back, rather than only asserting the call site names the right
27
+ // symbol. `undefined` under CI on purpose: the CI read instead needs the
28
+ // RESOLVED base sha (see resolveBaseRefIgnore below), which is not known
29
+ // yet here.
30
+ export async function resolveEagerLocalIgnore(params: {
31
+ isCi: boolean;
32
+ operatorRoot: string;
33
+ readLocal: (root: string) => Promise<IgnoreFileReadResult>;
34
+ }): Promise<IgnoreFileReadResult | undefined> {
35
+ return params.isCi ? undefined : await params.readLocal(params.operatorRoot);
36
+ }
37
+
38
+ // Invariant 8 (design D1): CI reads the ignore file at the RESOLVED base
39
+ // sha, never `target.baseRef`/`target.baseRefName` directly — a merged PR's
40
+ // baseRef is a `<sha>^1` EXPRESSION, and only a resolved sha is a valid
41
+ // `ls-tree` argument. Non-CI reuses the eager `localIgnore` read above
42
+ // rather than re-reading — the same value must decide the dry-run estimate
43
+ // and the real run.
44
+ export async function resolveBaseRefIgnore(params: {
45
+ isCi: boolean;
46
+ localIgnore: IgnoreFileReadResult | undefined;
47
+ runGit: GitRunner;
48
+ gitDirOwner: string;
49
+ baseSha: string;
50
+ }): Promise<IgnoreFileReadResult> {
51
+ return params.isCi
52
+ ? await readBaseRefIgnoreRules(
53
+ params.runGit,
54
+ params.gitDirOwner,
55
+ params.baseSha,
56
+ )
57
+ : // isCi is false on this branch, so `localIgnore` above is defined.
58
+ (params.localIgnore as IgnoreFileReadResult);
59
+ }
60
+
61
+ export interface ResolvedPrFetchAndRange {
62
+ headSha: string;
63
+ baseSha: string;
64
+ diffFromSha: string;
65
+ prIgnore: IgnoreFileReadResult;
66
+ headLabel: string;
67
+ }
68
+
69
+ // Fetch, then canonicalize, then the base-ref `.prheroignore` read. Object-db
70
+ // git runs against the git-dir OWNER, not the operator cwd: the worktree is
71
+ // registered there (W3).
72
+ //
73
+ // NOTE (recorded, not fixed — see design's Open Questions): the ignore read
74
+ // cannot precede fetchPrRefs, so a lookup failure there burns one CI
75
+ // admission attempt already reserved by the caller. A persistent misconfig
76
+ // therefore exhausts `ci_max_attempts` into manual-required — the correct
77
+ // outcome for a repo-level misconfig, not a reason to reorder a settled CI
78
+ // mechanism.
79
+ export async function resolvePrFetchAndRange(params: {
80
+ gitDirOwner: string;
81
+ prNumber: number;
82
+ target: PrTarget;
83
+ isCi: boolean;
84
+ localIgnore: IgnoreFileReadResult | undefined;
85
+ runGit: GitRunner;
86
+ }): Promise<ResolvedPrFetchAndRange> {
87
+ await fetchPrRefs(
88
+ params.gitDirOwner,
89
+ params.prNumber,
90
+ params.target.baseRefName,
91
+ );
92
+ const headSha = await resolveCommit(
93
+ params.gitDirOwner,
94
+ params.target.headSha,
95
+ );
96
+ // baseRef may be a `<sha>^1` expression (merged PR); rev-parse settles it.
97
+ const baseSha = await resolveCommit(
98
+ params.gitDirOwner,
99
+ params.target.baseRef,
100
+ );
101
+ assertDistinctRange(baseSha, headSha);
102
+ const prIgnore = await resolveBaseRefIgnore({
103
+ isCi: params.isCi,
104
+ localIgnore: params.localIgnore,
105
+ runGit: params.runGit,
106
+ gitDirOwner: params.gitDirOwner,
107
+ baseSha,
108
+ });
109
+ const headLabel = `PR #${params.prNumber} head`;
110
+ const diffFromSha = await resolveDiffFrom(
111
+ params.gitDirOwner,
112
+ false,
113
+ params.target.baseRef,
114
+ headLabel,
115
+ baseSha,
116
+ headSha,
117
+ );
118
+ return { headSha, baseSha, diffFromSha, prIgnore, headLabel };
119
+ }