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,154 @@
1
+ import { postCommitStatus } from "#pr/pr";
2
+ import {
3
+ CANCELLATION_COMMIT_STATUS_TIMEOUT_MS,
4
+ type commitStatusRequest,
5
+ type HeldCommitStatusLock,
6
+ settleRequestForCancellation,
7
+ } from "#pr/preflight";
8
+ import { log } from "#ui/primitives";
9
+ import { CliError } from "../errors";
10
+
11
+ // WHY this module-level state exists (paid for on PR #162, 2026-09-01): a run
12
+ // cancelled by the workflow's `cancel-in-progress` concurrency group posted its
13
+ // pending on the head it was legitimately reviewing and then never settled it,
14
+ // because the SIGTERM/SIGINT handlers end in `process.exit()` — which skips
15
+ // reviewPr's `finally`. The next run read that pending back through
16
+ // isInFlightCommitStatus, saw a lock younger than the 90-minute TTL, and
17
+ // skipped: PR #162 went unreviewed while the `review` job still reported
18
+ // success.
19
+ //
20
+ // The lock cannot tell "another process is working" from "a dead process left
21
+ // this behind" — it is a cross-machine TOCTOU guard, not a liveness probe. So
22
+ // the fix is on the holder's side: the process that took the lock releases it
23
+ // on the way out. This closes the CANCELLATION case, which is by far the most
24
+ // common one, because `cancel-in-progress: true` on a head-ref concurrency
25
+ // group fires on EVERY push, not only a force-push. A runner that dies with no
26
+ // signal at all (hard kill, OOM, a dropped machine) still reaches nothing here
27
+ // and remains covered only by the TTL.
28
+ //
29
+ // Module state, and the same precedent as `unregisterActiveRun(process.pid)`:
30
+ // a signal handler installed in runCli cannot see reviewPr's scope, so what it
31
+ // needs has to be parked where both can reach it.
32
+ let heldLock: HeldCommitStatusLock | null = null;
33
+ // When the lock was taken, in ms: the run's own start, which plan.ts reads before the
34
+ // pending post and passes in. The override check (teardown.ts, src/ci/override.ts)
35
+ // compares it with GitHub's status times, which are server time, so the two differ by
36
+ // whatever the runner's clock skew is; the override rule's allowance covers that.
37
+ let heldSinceMs: number | null = null;
38
+ // Whether this run's own pending status landed (plan.ts passes it with the hold). The
39
+ // start above is only a witness while that pending is on the head: when it did not land,
40
+ // no pr-hero status vouches for the start, so the override check compares with no
41
+ // clock-skew allowance (teardown.ts). Defaults to landed, the case every caller had before
42
+ // this flag existed.
43
+ let heldPendingLanded = true;
44
+
45
+ export function holdCommitStatusLock(
46
+ lock: HeldCommitStatusLock,
47
+ nowMs: number = Date.now(),
48
+ pendingLanded: boolean = true,
49
+ ): void {
50
+ heldLock = lock;
51
+ heldSinceMs = nowMs;
52
+ heldPendingLanded = pendingLanded;
53
+ }
54
+
55
+ export function releaseCommitStatusLock(): void {
56
+ heldLock = null;
57
+ heldSinceMs = null;
58
+ heldPendingLanded = true;
59
+ }
60
+
61
+ export function heldCommitStatusSince(): number | null {
62
+ return heldSinceMs;
63
+ }
64
+
65
+ export function heldCommitStatusPendingLanded(): boolean {
66
+ return heldPendingLanded;
67
+ }
68
+
69
+ export function heldCommitStatusLock(): HeldCommitStatusLock | null {
70
+ return heldLock;
71
+ }
72
+
73
+ // Settles the pending this process is holding, then exits — the caller is a
74
+ // signal handler and MUST still reach its `process.exit(code)`.
75
+ //
76
+ // Take-and-clear BEFORE the await, not after: Actions cancels with SIGINT and
77
+ // follows with SIGTERM before the grace period ends, so both handlers can be
78
+ // in flight at once and a peek-then-post would settle twice. `post` is a seam
79
+ // only so the take-and-clear and the bound below are testable offline.
80
+ //
81
+ // Every error is swallowed on purpose. Failing to settle leaves us exactly
82
+ // where PR #162 left us — never worse — and a throw here would cost the exit
83
+ // code the handler owes the runner.
84
+ export async function settleHeldCommitStatusOnSignal(
85
+ post: typeof postCommitStatus = postCommitStatus,
86
+ ): Promise<void> {
87
+ const settle = settleRequestForCancellation(heldLock);
88
+ releaseCommitStatusLock();
89
+ if (settle === null) return;
90
+ try {
91
+ await post(settle.operatorRoot, settle.sha, settle.request, undefined, {
92
+ attempts: 1,
93
+ timeoutMs: CANCELLATION_COMMIT_STATUS_TIMEOUT_MS,
94
+ });
95
+ } catch {
96
+ // Ignore
97
+ }
98
+ }
99
+
100
+ // `spawnFn` is the same invisible-to-production seam postCommitStatus
101
+ // already accepts (pr.ts's own established pattern): every existing call
102
+ // site omits it and gets `Bun.spawn`, exactly as before. It exists so an
103
+ // offline test can prove this function's actual swallow-errors behavior —
104
+ // a failed `gh` call caught here and logged, never rethrown — instead of
105
+ // replacing the whole function with a fake that can only assert it was
106
+ // called, not what it really does when gh fails.
107
+ //
108
+ // Resolves true when the status landed and false when it did not. The swallow is
109
+ // unchanged: a caller that ignores the result gets the same posture as before. The
110
+ // result exists for the one caller that must act on a failed write, the body-failed
111
+ // path in settleCommitStatusAndLedger (src/pr/teardown.ts).
112
+ export async function tryPublishCommitStatus(
113
+ operatorRoot: string,
114
+ sha: string,
115
+ request: ReturnType<typeof commitStatusRequest>,
116
+ spawnFn?: typeof Bun.spawn,
117
+ onCreatedAt?: (createdAt: string) => void,
118
+ ): Promise<boolean> {
119
+ try {
120
+ const createdAt = await postCommitStatus(
121
+ operatorRoot,
122
+ sha,
123
+ request,
124
+ spawnFn,
125
+ );
126
+ if (createdAt !== undefined) onCreatedAt?.(createdAt);
127
+ return true;
128
+ } catch (error) {
129
+ log(
130
+ `warning: commit status (${request.state}): ${(error as Error).message}`,
131
+ );
132
+ return false;
133
+ }
134
+ }
135
+
136
+ // S4, gate mode: the FINAL write does not swallow. In gate the status is the
137
+ // required check, so a write that never landed must fail the run (exit 1 and
138
+ // an `::error::` annotation, via the CLI's catch) rather than log a warning
139
+ // over a head GitHub still shows as pending. The pending write stays
140
+ // best-effort in both modes, and advisory keeps tryPublishCommitStatus.
141
+ export async function publishFinalCommitStatus(
142
+ operatorRoot: string,
143
+ sha: string,
144
+ request: ReturnType<typeof commitStatusRequest>,
145
+ spawnFn?: typeof Bun.spawn,
146
+ ): Promise<void> {
147
+ try {
148
+ await postCommitStatus(operatorRoot, sha, request, spawnFn);
149
+ } catch (error) {
150
+ throw new CliError(
151
+ `commit status (${request.state}) was not written, so the required check on this head is not settled: ${(error as Error).message}`,
152
+ );
153
+ }
154
+ }
@@ -0,0 +1,388 @@
1
+ // PR mode's target resolution (ROADMAP B1): the front half of reviewPr()
2
+ // that turns `--pr <n>` into an operator root, a resolved config, a prompt
3
+ // set, and a PR record — everything before the CI admission gate, the dry
4
+ // run, and the fetch/discovery machinery. Relocated out of reviewPr()
5
+ // (src/pr/review-pr.ts): identifiers moved onto explicit parameters, control
6
+ // flow and WHY comments unchanged.
7
+ //
8
+ // Split into three functions rather than one, deliberately: two calls sit
9
+ // between them in reviewPr() itself — `resolveEagerLocalIgnore(...)`
10
+ // (src/pr/range.ts, invariant 7/O-8) and `validateGotchas(gotchasPath)`
11
+ // (guarded by test/architecture/review-shell-invariants.test.ts's directory
12
+ // scan, not a per-file pin) — and both need to run in this exact relative
13
+ // position: the ignore read right after step 1's config load, gotchas
14
+ // validation right after step 2's prompt-set resolution, before step 2's own
15
+ // target record is resolved. Folding either call into this module would
16
+ // change that relative order, so reviewPr() keeps calling them inline, in
17
+ // between these three calls, in the exact original order.
18
+
19
+ import { existsSync } from "node:fs";
20
+ import os from "node:os";
21
+ import {
22
+ budgetDisabledWarningMessage,
23
+ budgetUnlimitedNoticeMessage,
24
+ type CiSizeLimits,
25
+ deriveCiBillingMode,
26
+ resolveCiBudgetCeiling,
27
+ resolveCiSizeLimits,
28
+ sizeGateUnlimitedNoticeMessage,
29
+ } from "#ci/gates";
30
+ import { formatWorkflowCommand } from "#ci/reporter";
31
+ import { resolveRepoRoot } from "#git/git";
32
+ import { ghCurrentBranchPr, ghPrView } from "#pr/pr";
33
+ import {
34
+ type PrTarget,
35
+ predictPrRunDir,
36
+ resolveCurrentPrNumber,
37
+ resolvePrDryRunSizeGate,
38
+ resolvePrTarget,
39
+ } from "#pr/preflight";
40
+ import {
41
+ type AgentsDirResolution,
42
+ type AgentsDirSource,
43
+ type CliOptions,
44
+ isCiEnvironment,
45
+ type NumstatFile,
46
+ } from "#review/preflight";
47
+ import type { ParsedAgent, PromptSetIdentity } from "#review/prompt-set";
48
+ import type { estimateCost } from "#review/report";
49
+ import {
50
+ type LoadedRunConfig,
51
+ loadRunConfig,
52
+ resolveGotchasPath,
53
+ resolvePromptSet,
54
+ } from "#review/run";
55
+ import type { SizeGateConfig } from "#review/size-gate";
56
+ import type { ReviewSpec } from "#review/spec";
57
+ import { configProvenanceOf, type PrPlanContext, renderPrPlan } from "#ui/plan";
58
+ import { log, styleEnabled } from "#ui/primitives";
59
+ import { type ResolvedRepoHome, resolveRepoHome } from "../home";
60
+ import {
61
+ legacyMigrationHint,
62
+ legacyWorktreePath,
63
+ prWorktreePath,
64
+ } from "../home-preflight";
65
+ import { resolveOpenCodeAuthPath } from "../security/credential-broker";
66
+
67
+ export interface ResolvedPrRunOptions {
68
+ operatorRoot: string;
69
+ prNumber: number;
70
+ home: string;
71
+ isCi: boolean;
72
+ options: CliOptions;
73
+ loaded: LoadedRunConfig["loaded"];
74
+ config: LoadedRunConfig["config"];
75
+ summary: LoadedRunConfig["summary"];
76
+ }
77
+
78
+ // Step 1's first half: the operator root, the PR number, `home`, and the
79
+ // config load — identical to loadRunConfig's own callers, plus reviewPr()'s
80
+ // own isCi/options-yes fold-in (ROADMAP Pillar 3). Returns BEFORE the
81
+ // `.cryskignore` read: `readLocalIgnoreRules(operatorRoot)` needs
82
+ // `operatorRoot` and `isCi` from here, but stays an inline statement in
83
+ // reviewPr() itself (see this module's header).
84
+ export async function resolvePrRunOptions(
85
+ options: CliOptions,
86
+ prArg: number | "current",
87
+ ): Promise<ResolvedPrRunOptions> {
88
+ // 1 — the operator root, and everything .prhero/ decides — loaded exactly
89
+ // as local mode loads it, all against the operator root.
90
+ const operatorRoot = await resolveRepoRoot(options.repo);
91
+ // Bare --pr: the PR is whichever one the operator checkout's current
92
+ // branch belongs to. Resolved first and said out loud, so the user sees
93
+ // WHICH PR is about to be reviewed before any plan prints.
94
+ const prNumber =
95
+ prArg === "current"
96
+ ? resolveCurrentPrNumber(await ghCurrentBranchPr(operatorRoot))
97
+ : prArg;
98
+ if (prArg === "current") {
99
+ log(`pr resolved from current branch: #${prNumber}`);
100
+ }
101
+ // The product home, hoisted above the config read: C5's global layer lives
102
+ // under it, and the PR-record resolution below needs the same value for
103
+ // the repo registry.
104
+ const home = os.homedir();
105
+ // `operatorRoot`, NEVER worktreePath — the worktree does not even exist
106
+ // yet at this point, and a `.crysk/config.json` committed by the PR author
107
+ // must stay unread (O-8). Same loader as local mode, so the two modes
108
+ // cannot drift on precedence.
109
+ const { loaded, config, summary, scout, post } = await loadRunConfig({
110
+ root: operatorRoot,
111
+ home,
112
+ configFlag: options.config,
113
+ options,
114
+ });
115
+ // ROADMAP Pillar 3 (GitHub Actions CI). isCi folds in HERE, alongside
116
+ // scout/post, so `options.yes` carries the headless bypass (spec 2.1:
117
+ // "MUST run headlessly ... equivalent to --yes") through every downstream
118
+ // read of `options.yes` in one move — the confirm gate, the in-flight
119
+ // TOCTOU check (`if (options.yes) return 0` is the correct CI answer to a
120
+ // stuck pending), and applySizeGate's own `opts.yes` read. A parallel
121
+ // `effectiveYes` local would miss whichever of those reads came later.
122
+ const isCi = isCiEnvironment(options, {
123
+ GITHUB_ACTIONS: process.env.GITHUB_ACTIONS,
124
+ CI: process.env.CI,
125
+ });
126
+ return {
127
+ operatorRoot,
128
+ prNumber,
129
+ home,
130
+ isCi,
131
+ options: { ...options, scout, post, yes: options.yes || isCi },
132
+ loaded,
133
+ config,
134
+ summary,
135
+ };
136
+ }
137
+
138
+ export interface ResolvedPrPromptSet {
139
+ ciBudgetCeiling: ReturnType<typeof resolveCiBudgetCeiling>;
140
+ ciSizeLimits: CiSizeLimits | undefined;
141
+ agents: AgentsDirResolution;
142
+ spec: ReviewSpec;
143
+ agentFiles: Map<string, ParsedAgent>;
144
+ promptSet: PromptSetIdentity;
145
+ gotchasPath: string;
146
+ }
147
+
148
+ // Step 1's second half: the CI budget ceiling (+ its notices), then the
149
+ // prompt set resolution and the gotchas PATH (never the validation itself —
150
+ // see this module's header). Runs after the caller's own
151
+ // `readLocalIgnoreRules(operatorRoot)` read, before its own
152
+ // `validateGotchas(gotchasPath)` call — same relative order reviewPr() has
153
+ // always executed them in.
154
+ export async function resolvePrPromptSetAndBudget(params: {
155
+ options: CliOptions;
156
+ loaded: LoadedRunConfig["loaded"];
157
+ config: LoadedRunConfig["config"];
158
+ isCi: boolean;
159
+ operatorRoot: string;
160
+ }): Promise<ResolvedPrPromptSet> {
161
+ // File presence, not envBillsMetered: that predicate stamps Claude
162
+ // usage and must stay Anthropic-env-only.
163
+ const billingMode = deriveCiBillingMode(process.env, {
164
+ openCodeAuthPresent: existsSync(resolveOpenCodeAuthPath()),
165
+ });
166
+ // Issue #156: resolve the ceiling ONCE, here, and use this same value at
167
+ // the budget gate far below (src/pr/review-pr.ts's plan/confirm stage).
168
+ // Resolving twice invites the announcement and the gate drifting apart.
169
+ // Deliberately NOT folded back into `options.budgetUsd` — the metered
170
+ // default is a CI-gate policy, and leaking a 10 that the operator never
171
+ // typed into every other read of `options.budgetUsd` would make it look
172
+ // configured.
173
+ const ciBudgetCeiling = resolveCiBudgetCeiling({
174
+ configured: params.options.budgetUsd,
175
+ billingMode,
176
+ });
177
+ // The size gate's half of the same route policy (ci/gates.ts,
178
+ // resolveCiSizeLimits). CI only: a local or watcher run keeps reading the
179
+ // flags and the repo config exactly as before.
180
+ const ciSizeLimits = params.isCi
181
+ ? resolveCiSizeLimits({
182
+ flags: params.options,
183
+ config: params.config,
184
+ billingMode,
185
+ })
186
+ : undefined;
187
+ // Spec 3.1: a silent disable is indistinguishable from a passing gate, so
188
+ // an EXPLICIT `--budget-usd <= 0` warns even though it never skips a run.
189
+ // Emitted here (once, as soon as isCi/budgetUsd are both known) rather
190
+ // than beside the budget-gate check far below, which only runs at all when
191
+ // there IS an estimate to compare against. The subscription notice rides
192
+ // the same reasoning and the same placement, one register quieter: a
193
+ // resolved no-ceiling is not an operator mistake, but it is still a gate
194
+ // that did not run, and this repo does not ship those silently.
195
+ if (params.isCi) {
196
+ const disabledWarning = budgetDisabledWarningMessage(
197
+ ciBudgetCeiling.budgetUsd,
198
+ );
199
+ if (disabledWarning !== null) {
200
+ log(formatWorkflowCommand("warning", disabledWarning));
201
+ }
202
+ const unlimitedNotice = budgetUnlimitedNoticeMessage(ciBudgetCeiling);
203
+ if (unlimitedNotice !== null) {
204
+ log(formatWorkflowCommand("notice", unlimitedNotice));
205
+ }
206
+ if (ciSizeLimits !== undefined) {
207
+ const sizeNotice = sizeGateUnlimitedNoticeMessage(ciSizeLimits);
208
+ if (sizeNotice !== null) {
209
+ log(formatWorkflowCommand("notice", sizeNotice));
210
+ }
211
+ }
212
+ }
213
+ // The WHOLE resolution, not just its dir: under the compiled binary the
214
+ // prompt set is a map of embedded paths and `dir` is only a display label.
215
+ const { agents, spec, agentFiles, promptSet } = await resolvePromptSet(
216
+ params.options,
217
+ params.loaded,
218
+ );
219
+ const gotchasPath = resolveGotchasPath(
220
+ params.options.gotchas,
221
+ params.operatorRoot,
222
+ );
223
+ return {
224
+ ciBudgetCeiling,
225
+ ciSizeLimits,
226
+ agents,
227
+ spec,
228
+ agentFiles,
229
+ promptSet,
230
+ gotchasPath,
231
+ };
232
+ }
233
+
234
+ // PR1b Addition 1 / #5557's degrade rule, extracted so it can be proven
235
+ // offline: a dry run creates nothing and is a PLAN, so a stalled or failing
236
+ // `gh pr view --json files` must degrade to the aggregate estimate rather
237
+ // than abort (GH_PR_VIEW_TIMEOUT_MS bounds `ghPrFiles`, turning a hang into a
238
+ // throw this function is what catches). `null` is returned DIRECTLY on
239
+ // failure or on a truncated fetch, never an empty array routed through the
240
+ // length check: `[].length >= 0` is true, so an empty list would sail
241
+ // through as "trustworthy" and hand the per-file gate zero lines to measure —
242
+ // a PASSING verdict manufactured out of a failed fetch, which is the one
243
+ // outcome a size gate must never invent. `totalFiles` is GitHub's own
244
+ // `changedFiles` counter (`target.ghDiffStat.files`); a per-file list shorter
245
+ // than it is the same truncation hazard watch/watch.ts's tier 2 guards
246
+ // against, and under-counting here would falsely rescue exactly the PR this
247
+ // gate exists to catch.
248
+ export async function resolvePrDryRunNumstat(params: {
249
+ fetchFiles: () => Promise<NumstatFile[]>;
250
+ totalFiles: number;
251
+ }): Promise<NumstatFile[] | null> {
252
+ try {
253
+ const rawFiles = await params.fetchFiles();
254
+ return rawFiles.length >= params.totalFiles ? rawFiles : null;
255
+ } catch {
256
+ return null;
257
+ }
258
+ }
259
+
260
+ export interface ResolvedPrTargetRecord {
261
+ repoHome: ResolvedRepoHome;
262
+ gitDirOwner: string;
263
+ target: PrTarget;
264
+ worktreePath: string;
265
+ }
266
+
267
+ // Step 2: the global home (origin -> repo-id -> worktree/runs paths), then
268
+ // the PR record itself. `home` and `operatorRoot` are the caller's own
269
+ // step-1 results; C5's global config layer already needed the same `home`
270
+ // value. `persist` is false on --dry-run so the free exit creates nothing,
271
+ // including registry.json. Local mode's dirty-tree and HEAD-match gates are
272
+ // both skipped for PR review ON PURPOSE: the hunters read the worktree and
273
+ // never this checkout, and the worktree satisfies the HEAD gate by
274
+ // construction (created detached at the PR's own head).
275
+ export async function resolvePrTargetRecord(params: {
276
+ home: string;
277
+ operatorRoot: string;
278
+ prNumber: number;
279
+ dryRun: boolean;
280
+ }): Promise<ResolvedPrTargetRecord> {
281
+ const repoHome = await resolveRepoHome({
282
+ home: params.home,
283
+ operatorRoot: params.operatorRoot,
284
+ persist: !params.dryRun,
285
+ });
286
+ const gitDirOwner = repoHome.gitDirOwner;
287
+ const target = resolvePrTarget(
288
+ await ghPrView(params.operatorRoot, params.prNumber),
289
+ );
290
+ const worktreePath = prWorktreePath(
291
+ params.home,
292
+ repoHome.repoId,
293
+ params.prNumber,
294
+ );
295
+ const leftover = legacyWorktreePath(params.operatorRoot, params.prNumber);
296
+ if (existsSync(leftover)) {
297
+ for (const line of legacyMigrationHint({
298
+ operatorRoot: params.operatorRoot,
299
+ legacyWorktree: leftover,
300
+ newWorktree: worktreePath,
301
+ })) {
302
+ log(line);
303
+ }
304
+ }
305
+ return { repoHome, gitDirOwner, target, worktreePath };
306
+ }
307
+
308
+ // Step 3's second half: the free dry-run exit's size-gate verdict, plan
309
+ // card, and closing lines. Relocated out of reviewPr()'s `if (options.dryRun)`
310
+ // block; the FIRST half of that block (hunterCount/estimate/dryRunGateConfig,
311
+ // then the `resolvePrDryRunNumstat` call just above) stays inline in
312
+ // reviewPr(), unchanged. This half picks up right after `perFile` is known
313
+ // and returns the dry run's exit code (always 0).
314
+ export function renderPrDryRunPlan(params: {
315
+ options: CliOptions;
316
+ operatorRoot: string;
317
+ prNumber: number;
318
+ target: PrTarget;
319
+ worktreePath: string;
320
+ repoHome: ResolvedRepoHome;
321
+ agentsDir: string;
322
+ agentsDirSource: AgentsDirSource;
323
+ agentFiles: Map<string, ParsedAgent>;
324
+ spec: ReviewSpec;
325
+ config: LoadedRunConfig["config"];
326
+ summary: LoadedRunConfig["summary"];
327
+ loaded: LoadedRunConfig["loaded"];
328
+ isCi: boolean;
329
+ hunterCount: number;
330
+ estimate: ReturnType<typeof estimateCost>;
331
+ dryRunGateConfig: SizeGateConfig;
332
+ perFile: NumstatFile[] | null;
333
+ }): number {
334
+ const { verdict: estimated, note: baseSizeGateNote } =
335
+ resolvePrDryRunSizeGate({
336
+ ghDiffStat: params.target.ghDiffStat,
337
+ perFile: params.perFile,
338
+ gateConfig: params.dryRunGateConfig,
339
+ });
340
+ // Under CI, `localIgnore` is intentionally undefined (see reviewPr()'s own
341
+ // comment on that read) — the base-ref read needs a fetch a dry run does
342
+ // not perform — so this estimate applies only the 9 BUILT-IN default
343
+ // exclusions, never a repo's user-defined `.cryskignore` rules. Said out
344
+ // loud rather than discovered: a CI dry run that quietly ignored
345
+ // `.cryskignore` would look like the SAME bug Addition 1 exists to fix.
346
+ const sizeGateNote = params.isCi
347
+ ? `${baseSizeGateNote} User-defined \`.cryskignore\` rules are not ` +
348
+ "applied to this estimate under --ci; only the built-in defaults " +
349
+ "are (the base ref is not fetched until a real run)."
350
+ : baseSizeGateNote;
351
+ const dryRunPlan: PrPlanContext = {
352
+ options: params.options,
353
+ operatorRoot: params.operatorRoot,
354
+ target: params.target,
355
+ worktreePath: params.worktreePath,
356
+ runDir: predictPrRunDir(
357
+ params.options,
358
+ params.operatorRoot,
359
+ params.worktreePath,
360
+ params.repoHome.paths.runs,
361
+ params.prNumber,
362
+ params.target.headSha,
363
+ ),
364
+ diffStat: params.target.ghDiffStat,
365
+ agentsDir: params.agentsDir,
366
+ agentFiles: params.agentFiles,
367
+ spec: params.spec,
368
+ config: params.config,
369
+ summary: params.summary,
370
+ estimate: params.estimate,
371
+ hunterCount: params.hunterCount,
372
+ sizeGate: estimated,
373
+ sizeGateNote,
374
+ droppedPaths: [],
375
+ // On the dry run too, and it is the case that matters most: this is the
376
+ // free card an operator reads BEFORE deciding to spend, so a value
377
+ // arriving from the global layer must be visible here or it is
378
+ // discovered only in the bill.
379
+ configProvenance: configProvenanceOf(params.loaded, params.agentsDirSource),
380
+ };
381
+ for (const line of renderPrPlan(dryRunPlan, styleEnabled())) log(line);
382
+ log();
383
+ if (!estimated.ok && !params.options.force) {
384
+ log("dry run: this PR would likely be SKIPPED by the size gate.");
385
+ }
386
+ log("dry run: nothing was fetched, created, or spent.");
387
+ return 0;
388
+ }