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,601 @@
1
+ // CLI decomposition P2.1 (odd/tasks/cli-decomposition.md): the pure stages
2
+ // shared by `review()` and `reviewPr()` in cli.ts. A block detector found 28
3
+ // verbatim-duplicated blocks (205 lines) between the two orchestrators; they
4
+ // walk the same sequence of stages, and `reviewPr` interleaves PR-only ones
5
+ // around them. This module extracts the PURE stages only — no `await`, no
6
+ // I/O — so each one gets a test and replaces its copy in BOTH orchestrators.
7
+ //
8
+ // Design rule (accepted 2026-09-16, see the task doc's "Design decision"):
9
+ // compose, never unify with a mode flag. Where the two orchestrators diverge
10
+ // (the working root, index_ms, ...), the difference is an explicit parameter
11
+ // here, never a branch on an `isPr`-shaped flag.
12
+ //
13
+ // P2.2 (odd/tasks/shared-run-stages.md) adds the run-lifecycle stages below.
14
+ // registerActiveRun and the try/finally around runPipeline stay call-site
15
+ // owned: their POSITION differs between the orchestrators, not their data.
16
+
17
+ import path from "node:path";
18
+ import {
19
+ type EffectiveConfig,
20
+ loadEffectiveConfig,
21
+ notionalCostInput,
22
+ } from "#config/config";
23
+ import type { ResolvedRoutePlan, RoutingConfig } from "#model/routing";
24
+ import type { CiMode } from "#pr/preflight";
25
+ import {
26
+ type FindingsDocument,
27
+ mergeRunEnvelope,
28
+ type Telemetry,
29
+ writeFindings,
30
+ } from "#review/findings";
31
+ import {
32
+ changedPathsFromDiff,
33
+ type PipelineDeps,
34
+ type PipelineResult,
35
+ parityTriggered,
36
+ } from "#review/pipeline";
37
+ import {
38
+ type AgentsDirResolution,
39
+ agentFilePath,
40
+ assertBasenameOnly,
41
+ type CliOptions,
42
+ gotchasErrorMessage,
43
+ gotchasUnusableReason,
44
+ type LocalConfig,
45
+ localReviewSpec,
46
+ parseNumstatFiles,
47
+ preflightAgentsDir,
48
+ resolveAgentsDir,
49
+ resolvePost,
50
+ resolveScout,
51
+ resolveSummary,
52
+ type SummarySettings,
53
+ } from "#review/preflight";
54
+ import {
55
+ type ParsedAgent,
56
+ type PromptSetIdentity,
57
+ parseAgentFile,
58
+ promptSetIdentity,
59
+ } from "#review/prompt-set";
60
+ import { type DiffStat, envelopeModel, renderReport } from "#review/report";
61
+ import {
62
+ buildCliRoutePlan,
63
+ enforceProviderCapabilityGate,
64
+ type ProductionRoutePlanResult,
65
+ resolveProductionRoutePlanAtConfirm,
66
+ } from "#review/route-preflight";
67
+ import {
68
+ effectiveDiffStat,
69
+ evaluateSizeGate,
70
+ type SizeGateConfig,
71
+ type SizeGateVerdict,
72
+ } from "#review/size-gate";
73
+ import {
74
+ type AgentSpec,
75
+ type ReviewSpec,
76
+ validateReviewSpec,
77
+ } from "#review/spec";
78
+ import { ClaudeCodeRunner } from "#review/step-runner";
79
+ import { resolveRepoDir } from "../brand-paths";
80
+ import { CliError, withRecordClass } from "../errors";
81
+ import {
82
+ type AttemptAdmissionGate,
83
+ ConcurrencyAttemptAdmissionGate,
84
+ } from "../execution/admission";
85
+ import { ConcurrencyLimiter } from "../execution/concurrency-limiter";
86
+ import {
87
+ createProductionRuntime,
88
+ type ProductionAdmissionContext,
89
+ type ProductionRuntime,
90
+ } from "../production-runtime";
91
+ import type { RunnerAuthorityResolution } from "../runner-authority";
92
+
93
+ // The codegraph server, and ONLY the codegraph server. Written per run and
94
+ // handed to every step together with the runner's --strict-mcp-config: an
95
+ // agent's tool surface is a threat model, not a preference, and a registry
96
+ // the driver did not write is a channel it does not control. Shared by both
97
+ // orchestrators (review() and reviewPr()), which is why it lives here rather
98
+ // than in either one's own module.
99
+ export const CODEGRAPH_ONLY_MCP_CONFIG = {
100
+ mcpServers: {
101
+ codegraph: {
102
+ type: "stdio" as const,
103
+ command: "codegraph",
104
+ args: ["serve", "--mcp"],
105
+ },
106
+ },
107
+ };
108
+
109
+ export const EMPTY_MCP_CONFIG = { mcpServers: {} };
110
+
111
+ export interface LoadedRunConfig {
112
+ loaded: EffectiveConfig;
113
+ config: LocalConfig;
114
+ summary: SummarySettings;
115
+ scout: boolean;
116
+ post: boolean;
117
+ }
118
+
119
+ // Config load + the three per-run resolvers read right after it: identical
120
+ // in both orchestrators except the root/home they read from (repoRoot +
121
+ // os.homedir() in review(), operatorRoot + the hoisted `home` in reviewPr()).
122
+ // Callers still own their own `options = { ...options, scout, post, ... }`
123
+ // reassignment — reviewPr() folds an extra `yes` field into the same spread,
124
+ // and forcing that in here would make this a mode flag instead of an
125
+ // explicit parameter.
126
+ export async function loadRunConfig(params: {
127
+ root: string;
128
+ home: string;
129
+ configFlag: string | undefined;
130
+ options: Pick<CliOptions, "summary" | "model" | "scout" | "post">;
131
+ }): Promise<LoadedRunConfig> {
132
+ const loaded = await loadEffectiveConfig({
133
+ root: params.root,
134
+ home: params.home,
135
+ configFlag: params.configFlag,
136
+ });
137
+ const config = loaded.effective;
138
+ const summary = resolveSummary(params.options, config);
139
+ const scout = resolveScout(params.options, config);
140
+ const post = resolvePost(params.options, config);
141
+ return { loaded, config, summary, scout, post };
142
+ }
143
+
144
+ // Shared range guard. Both orchestrators check the same thing right after
145
+ // resolving base/head — the copies are byte-identical apart from
146
+ // indentation — and both throw before spending anything on a range that
147
+ // reviews nothing.
148
+ export function assertDistinctRange(baseSha: string, headSha: string): void {
149
+ if (baseSha === headSha) {
150
+ throw new CliError(
151
+ `base and head resolve to the same commit (${headSha}); there is ` +
152
+ "nothing to review",
153
+ );
154
+ }
155
+ }
156
+
157
+ // The gotchas file path: an explicit `--gotchas` flag always wins (resolved
158
+ // against cwd, exactly like path.resolve did inline); otherwise it is
159
+ // `<root>/.crysk/gotchas.md` (or the legacy `.prhero/`). `root` is the caller's own root — repoRoot in
160
+ // review(), operatorRoot in reviewPr(), repoDir in doctor.ts's default-branch
161
+ // check — never resolved here, so this stays agnostic of which mode called
162
+ // it.
163
+ export function resolveGotchasPath(
164
+ flag: string | undefined,
165
+ root: string,
166
+ exists?: (p: string) => boolean,
167
+ ): string {
168
+ return flag !== undefined
169
+ ? path.resolve(flag)
170
+ : path.join(resolveRepoDir(root, exists), "gotchas.md");
171
+ }
172
+
173
+ // Byte-identical gotchas read + validation in both orchestrators. Neither
174
+ // caller reads the text afterward (only `gotchasPath` goes on to the
175
+ // pipeline), so this validates and returns nothing.
176
+ export async function validateGotchas(gotchasPath: string): Promise<void> {
177
+ const file = Bun.file(gotchasPath);
178
+ const gotchas = (await file.exists()) ? await file.text() : "";
179
+ const unusable = gotchasUnusableReason(gotchas);
180
+ if (unusable !== undefined) {
181
+ // The class carries the gate's reason into cli.json (T2d-1). Both reasons render
182
+ // the one gotchas code today; the reason stays on the record for that reason only.
183
+ throw new CliError(gotchasErrorMessage(gotchasPath, unusable), {
184
+ cls: { kind: "gotchas", reason: unusable },
185
+ });
186
+ }
187
+ }
188
+
189
+ // Which hunters actually run: every unconditional hunter, plus every
190
+ // conditional (triggered) hunter when the parity trigger fired. Refuters are
191
+ // never included — they are a different role. Identical in both
192
+ // orchestrators; `reviewPr()`'s own `skipDiscovery` short-circuit to `[]`
193
+ // stays a call-site concern (a re-review with no delta to discover), not a
194
+ // parameter here.
195
+ export function selectActiveHunters(
196
+ agents: readonly AgentSpec[],
197
+ parityFires: boolean,
198
+ ): AgentSpec[] {
199
+ return agents.filter(
200
+ (a) => a.role === "hunter" && (a.trigger === undefined || parityFires),
201
+ );
202
+ }
203
+
204
+ // Whether the parity hunter fires for this diff: identical in both
205
+ // orchestrators. `changedPathsFromDiff`'s own list is never read afterward
206
+ // by either caller, only this boolean.
207
+ export function resolveParityFires(
208
+ patch: string,
209
+ parityTriggerPaths: string[],
210
+ ): boolean {
211
+ return parityTriggered(changedPathsFromDiff(patch), parityTriggerPaths);
212
+ }
213
+
214
+ // The diff stat, TWICE and on purpose (moved here from review()'s own WHY
215
+ // comment when reviewPr()'s copy — which never carried it — started sharing
216
+ // this stage):
217
+ //
218
+ // The GATE counts from `-w --ignore-blank-lines`: a pure formatter sweep
219
+ // must not consume the budget, and a file whose every change is whitespace
220
+ // drops out of that numstat entirely (verified: git emits no row for it).
221
+ //
222
+ // The COST BAND counts from the plain numstat, exclusions applied. The
223
+ // hunters are handed diff.patch verbatim, whitespace hunks included, so
224
+ // those bytes are genuinely billed — pricing them at zero would be the same
225
+ // class of lie the exclusion bug was.
226
+ //
227
+ // `runGit` arrives as a callback, not an import of `git()` from `#git/git`:
228
+ // this module's import surface is deliberately narrowed to review-domain
229
+ // modules (see header), and the two orchestrators already run it against
230
+ // different roots (repoRoot vs gitDirOwner) — an explicit parameter here,
231
+ // never a branch on which mode called it.
232
+ export async function computeDiffStatAndSizeGate(params: {
233
+ runGit: (
234
+ args: string[],
235
+ ) => Promise<{ ok: boolean; stdout: string; stderr: string }>;
236
+ range: string;
237
+ pathArgs: string[];
238
+ gateConfig: SizeGateConfig;
239
+ }): Promise<{ diffStat: DiffStat; sizeGate: SizeGateVerdict }> {
240
+ const numstat = await params.runGit([
241
+ "diff",
242
+ "--numstat",
243
+ params.range,
244
+ ...params.pathArgs,
245
+ ]);
246
+ if (!numstat.ok) {
247
+ throw new CliError(`git diff --numstat failed: ${numstat.stderr}`);
248
+ }
249
+ const gateNumstat = await params.runGit([
250
+ "diff",
251
+ "-w",
252
+ "--ignore-blank-lines",
253
+ "--numstat",
254
+ params.range,
255
+ ...params.pathArgs,
256
+ ]);
257
+ if (!gateNumstat.ok) {
258
+ throw new CliError(`git diff -w --numstat failed: ${gateNumstat.stderr}`);
259
+ }
260
+ return {
261
+ diffStat: effectiveDiffStat(
262
+ parseNumstatFiles(numstat.stdout),
263
+ params.gateConfig.excludeRules,
264
+ ),
265
+ sizeGate: evaluateSizeGate(
266
+ parseNumstatFiles(gateNumstat.stdout),
267
+ params.gateConfig,
268
+ ),
269
+ };
270
+ }
271
+
272
+ // The Telemetry artifact built right after runPipeline returns. Identical in
273
+ // both orchestrators except `index_ms`: local mode hardcodes 0 (it neither
274
+ // builds nor syncs a codegraph index), PR mode passes the measured build
275
+ // time.
276
+ export function buildTelemetry(
277
+ result: PipelineResult,
278
+ wallMs: number,
279
+ indexMs: number,
280
+ ): Telemetry {
281
+ return {
282
+ index_ms: indexMs,
283
+ index_mode: "sync",
284
+ index_disk_mb: 0,
285
+ // Driver-MEASURED elapsed time, never the sum of the steps: hunters run
286
+ // in parallel, so summing their wall clocks reports a number the run
287
+ // never took — and this engine exists to be compared on time and cost.
288
+ wall_ms: wallMs,
289
+ tokens_in: result.usage.tokens_in,
290
+ tokens_out: result.usage.tokens_out,
291
+ tokens_total: result.usage.tokens_total,
292
+ cost_usd_est: result.usage.cost_usd_est,
293
+ ...(result.unresolved.length > 0 ? { cost_usd_est_is_floor: true } : {}),
294
+ per_agent: result.perAgent,
295
+ };
296
+ }
297
+
298
+ export interface RunFindingsResult {
299
+ doc: FindingsDocument;
300
+ findingsPath: string;
301
+ }
302
+
303
+ // The findings artifact: merge the run envelope, then write it. Identical in
304
+ // both orchestrators except `pr` (the schema-legal 0 for "not a PR" in
305
+ // review(), the real PR number in reviewPr()). `engine`'s type is read off
306
+ // `mergeRunEnvelope`'s own parameter rather than imported from
307
+ // `#git/identity` — this module's import surface stays review-domain-only
308
+ // (see header); the caller already has an `EngineIdentity` from calling
309
+ // `engineIdentity()` itself.
310
+ export async function writeRunFindings(params: {
311
+ runDir: string;
312
+ result: PipelineResult;
313
+ pr: number;
314
+ baseSha: string;
315
+ headSha: string;
316
+ options: Pick<CliOptions, "model">;
317
+ agentFiles: Map<string, ParsedAgent>;
318
+ promptSet: PromptSetIdentity;
319
+ engine: Parameters<typeof mergeRunEnvelope>[0]["engine"];
320
+ telemetry: Telemetry;
321
+ }): Promise<RunFindingsResult> {
322
+ const doc = mergeRunEnvelope({
323
+ skillOutput: params.result.skillOutput,
324
+ pr: params.pr,
325
+ base_sha: params.baseSha,
326
+ head_sha: params.headSha,
327
+ model: envelopeModel(params.options, params.agentFiles),
328
+ iteration: 0,
329
+ prompt_set: params.promptSet,
330
+ engine: params.engine,
331
+ sessionFailed: params.result.sessionFailed,
332
+ telemetry: params.telemetry,
333
+ });
334
+ const findingsPath = path.join(params.runDir, "findings.json");
335
+ await writeFindings(findingsPath, doc);
336
+ return { doc, findingsPath };
337
+ }
338
+
339
+ // The report artifact: renderReport + write. Identical in both orchestrators
340
+ // except the repo/base/head labels (operator-root basename + `PR #<n>` in
341
+ // reviewPr(), repo-root basename + `--head` in review()).
342
+ export async function writeRunReport(params: {
343
+ runDir: string;
344
+ doc: FindingsDocument;
345
+ repo: string;
346
+ base: string;
347
+ head: string;
348
+ diffStat: DiffStat;
349
+ droppedPaths: string[];
350
+ result: PipelineResult;
351
+ wallMs: number;
352
+ // S4: the mode the commit status was set under. A PR run passes the mode it
353
+ // resolved; the local review leaves it out, and the closing note is advisory.
354
+ ciMode?: CiMode;
355
+ }): Promise<string> {
356
+ const reportPath = path.join(params.runDir, "report.md");
357
+ await Bun.write(
358
+ reportPath,
359
+ renderReport(params.doc, {
360
+ repo: params.repo,
361
+ base: params.base,
362
+ head: params.head,
363
+ diffStat: params.diffStat,
364
+ excludedPaths: params.droppedPaths,
365
+ costUsd: params.result.usage.cost_usd_est,
366
+ ...notionalCostInput(params.result),
367
+ wallMs: params.wallMs,
368
+ ...(params.ciMode === undefined ? {} : { ciMode: params.ciMode }),
369
+ }),
370
+ );
371
+ return reportPath;
372
+ }
373
+
374
+ export interface ResolvedPromptSet {
375
+ agents: AgentsDirResolution;
376
+ spec: ReviewSpec;
377
+ agentFiles: Map<string, ParsedAgent>;
378
+ promptSet: PromptSetIdentity;
379
+ }
380
+
381
+ // Prompt-set resolution: resolve the agents dir, validate + preflight the
382
+ // spec against it, parse every agent file, and compute the prompt set's
383
+ // identity (§3.9). Byte-identical in both orchestrators — the block
384
+ // detector's largest non-import match (17 lines).
385
+ export async function resolvePromptSet(
386
+ options: Pick<CliOptions, "agents">,
387
+ loaded: EffectiveConfig,
388
+ ): Promise<ResolvedPromptSet> {
389
+ const agents = resolveAgentsDir(options, loaded);
390
+ const spec = validateReviewSpec(localReviewSpec());
391
+ spec.agents.forEach((agent, i) => {
392
+ assertBasenameOnly(agent.file, i);
393
+ });
394
+ await preflightAgentsDir(
395
+ agents,
396
+ spec.agents.map((a) => a.file),
397
+ );
398
+ const agentFiles = new Map<string, ParsedAgent>();
399
+ for (const agent of spec.agents) {
400
+ // Parsing every agent file now is a preflight too: a malformed
401
+ // frontmatter block must fail here, not three spawned steps later.
402
+ // A failure is the error parseAgentFile threw, with its prompt-set class
403
+ // recorded beside it (T2d-1). It stays a plain Error, not a CliError: main()
404
+ // prints a CliError as one line, and a local run has always let this failure
405
+ // take the uncaught path with its excerpt and stack. Wrapping it in a helper
406
+ // would add a stack frame, so the try stays here.
407
+ let parsed: ParsedAgent;
408
+ try {
409
+ parsed = await parseAgentFile(agentFilePath(agents, agent.file));
410
+ } catch (error) {
411
+ throw withRecordClass(error, { kind: "prompt-set" });
412
+ }
413
+ agentFiles.set(agent.key, parsed);
414
+ }
415
+ // The prompt set's identity (§3.9), computed from the spec's DECLARATION
416
+ // order — the same order the lab's promptSetFingerprint hashes in, so the
417
+ // two sides produce the same string for the same bytes. Reading the list
418
+ // off the bundled map's keys instead would move every fingerprint ever
419
+ // recorded, silently — the digest still looks valid.
420
+ const promptSet = await promptSetIdentity(
421
+ agents.dir,
422
+ spec.agents.map((a) => agentFilePath(agents, a.file)),
423
+ // A bundled set has no directory basename to be named after. "default"
424
+ // is what dev and npm derive from prompts/default, so the same prompt
425
+ // set names itself identically in all three runtimes.
426
+ agents.kind === "bundled" ? "default" : undefined,
427
+ );
428
+ return { agents, spec, agentFiles, promptSet };
429
+ }
430
+
431
+ // Byte-identical MCP registry write in both orchestrators; only the
432
+ // `codegraphAvailable` check (which config to write) differs upstream.
433
+ export async function writeMcpConfig(
434
+ mcpConfigPath: string,
435
+ codegraphAvailable: boolean,
436
+ ): Promise<void> {
437
+ await Bun.write(
438
+ mcpConfigPath,
439
+ `${JSON.stringify(
440
+ codegraphAvailable ? CODEGRAPH_ONLY_MCP_CONFIG : EMPTY_MCP_CONFIG,
441
+ null,
442
+ 2,
443
+ )}\n`,
444
+ );
445
+ }
446
+
447
+ // Production route resolution: identical in both orchestrators except the
448
+ // workspace root and (reviewPr()'s skipped-discovery re-review only) the
449
+ // summarizer/scout enable overrides. Named distinctly from
450
+ // resolveProductionRoutePlanAtConfirm (#review/route-preflight), which this
451
+ // wraps — `resolveProductionRoute` reads as a near-duplicate of that name at
452
+ // a glance, which is exactly the confusion a shared wrapper should not add.
453
+ export async function resolvePipelineRoute(params: {
454
+ routingConfigured: boolean;
455
+ workspaceRoot: string;
456
+ spec: ReviewSpec;
457
+ options: CliOptions;
458
+ agentFiles: Map<string, ParsedAgent>;
459
+ routingConfig: RoutingConfig | undefined;
460
+ summary: SummarySettings;
461
+ summarizerEnabled?: boolean;
462
+ scoutEnabled?: boolean;
463
+ consolidateEnabled?: boolean;
464
+ }): Promise<ProductionRoutePlanResult | undefined> {
465
+ return resolveProductionRoutePlanAtConfirm({
466
+ routingConfigured: params.routingConfigured,
467
+ workspaceRoot: params.workspaceRoot,
468
+ buildRoutePlan: () =>
469
+ buildCliRoutePlan({
470
+ spec: params.spec,
471
+ options: params.options,
472
+ agentFiles: params.agentFiles,
473
+ routingConfig: params.routingConfig,
474
+ summary: params.summary,
475
+ summarizerEnabled: params.summarizerEnabled,
476
+ scoutEnabled: params.scoutEnabled,
477
+ consolidateEnabled: params.consolidateEnabled,
478
+ }),
479
+ });
480
+ }
481
+
482
+ // The capability gate: identical in both orchestrators except the workspace
483
+ // root. Wraps enforceProviderCapabilityGate (#review/route-preflight),
484
+ // unpacking the same three productionAdmission-derived fields both callers
485
+ // pass it.
486
+ export async function enforceCapabilityGate(params: {
487
+ routePlan: ResolvedRoutePlan | undefined;
488
+ workspaceRoot: string;
489
+ runnerAuthority: RunnerAuthorityResolution;
490
+ productionAdmission: ProductionAdmissionContext | undefined;
491
+ }): Promise<void> {
492
+ await enforceProviderCapabilityGate({
493
+ routePlan: params.routePlan,
494
+ workspaceRoot: params.workspaceRoot,
495
+ runnerAuthority: params.runnerAuthority,
496
+ authorityOptions: params.productionAdmission?.authorityOptions,
497
+ admissionRegistry: params.productionAdmission?.registry,
498
+ productionEvidence: params.productionAdmission?.evidence,
499
+ });
500
+ }
501
+
502
+ // The max_concurrent_steps cap, as the production runtime's admission gate.
503
+ // Undefined means no gate is constructed at all, so an unset cap is today's
504
+ // unlimited behavior byte for byte. The cap is one number for both bucket and
505
+ // global ceilings: pr-hero's steps all share one provider's concurrency
506
+ // budget (OpenCode's aiand allows 10 in-flight; 14 simultaneous requests drew
507
+ // HTTP 429 with x-ratelimit-policy: concurrency, which surfaced as
508
+ // UnknownError and lost refuters), so there is no per-bucket split to honor.
509
+ //
510
+ // The gate is cap-only: it omits `reportUnconfirmedRemote`, so an attempt
511
+ // whose abort the provider never confirmed does not trip the limiter's
512
+ // permanent bucket breaker. Every bucket here is the one shared bucket, so a
513
+ // breaker would refuse every remaining step of the review after one watchdog
514
+ // timeout. Fencing unconfirmed spend is the spend ledger's job, and it
515
+ // already fences a metered bucket on `unresolved_remote`; a concurrency cap
516
+ // must not add a second fence the run never had without it.
517
+ export function admissionGateFor(
518
+ maxConcurrentSteps?: number,
519
+ ): AttemptAdmissionGate | undefined {
520
+ if (maxConcurrentSteps === undefined) return undefined;
521
+ const gate = new ConcurrencyAttemptAdmissionGate(
522
+ new ConcurrencyLimiter({
523
+ bucketCeiling: maxConcurrentSteps,
524
+ globalCeiling: maxConcurrentSteps,
525
+ }),
526
+ );
527
+ return { acquire: (input) => gate.acquire(input) };
528
+ }
529
+
530
+ export interface PreparedPipelineRunner {
531
+ productionRuntime: ProductionRuntime | undefined;
532
+ deps: PipelineDeps;
533
+ }
534
+
535
+ // The run-lifecycle core (Target 1 + Target 3): create the production
536
+ // runtime when a route plan + admission are present (else `undefined`, the
537
+ // legacy path), then build the runPipeline's second argument around it — the
538
+ // production runtime's runner, or a fresh ClaudeCodeRunner sharing the
539
+ // ceiling's signal. Byte-identical logic in both orchestrators; only the
540
+ // workspace root differs. `productionRuntime` rides back out alongside
541
+ // `deps` because each caller's own `finally` disposes it — that ordering
542
+ // stays call-site-owned (see this module's header).
543
+ export async function prepareRunnerForRoute(params: {
544
+ routePlan: ResolvedRoutePlan | undefined;
545
+ productionAdmission: ProductionAdmissionContext | undefined;
546
+ workspaceRoot: string;
547
+ runnerAuthority: RunnerAuthorityResolution;
548
+ ceilingController: AbortController;
549
+ onProgress: PipelineDeps["onProgress"];
550
+ maxConcurrentSteps?: number;
551
+ }): Promise<PreparedPipelineRunner> {
552
+ const attemptAdmissionGate = admissionGateFor(params.maxConcurrentSteps);
553
+ const productionRuntime =
554
+ params.routePlan === undefined || params.productionAdmission === undefined
555
+ ? undefined
556
+ : await createProductionRuntime({
557
+ ...params.productionAdmission.authorityOptions,
558
+ plan: params.routePlan,
559
+ workspaceRoot: params.workspaceRoot,
560
+ registry: params.productionAdmission.registry,
561
+ evidence: params.productionAdmission.evidence,
562
+ // #182 follow-up: without this the admission may decide
563
+ // free-server while the bindings stay metered, and the runtime's
564
+ // own guard refuses the divergence — both or neither.
565
+ ...(params.productionAdmission.freeModelProbe === undefined
566
+ ? {}
567
+ : { freeModelProbe: params.productionAdmission.freeModelProbe }),
568
+ mode: "production",
569
+ signal: params.ceilingController.signal,
570
+ // Absent when no cap is configured: the runtime then gets no gate,
571
+ // exactly as before this key existed.
572
+ ...(attemptAdmissionGate === undefined
573
+ ? {}
574
+ : { attemptAdmissionGate }),
575
+ });
576
+ return {
577
+ productionRuntime,
578
+ deps: {
579
+ runner:
580
+ productionRuntime !== undefined
581
+ ? productionRuntime.runner
582
+ : new ClaudeCodeRunner({
583
+ ...params.runnerAuthority.runnerOptions,
584
+ signal: params.ceilingController.signal,
585
+ ...(attemptAdmissionGate === undefined
586
+ ? {}
587
+ : { attemptAdmissionGate }),
588
+ }),
589
+ ...(productionRuntime !== undefined
590
+ ? {
591
+ transportRegistry: productionRuntime.registry,
592
+ ...(productionRuntime.evidence === undefined
593
+ ? {}
594
+ : { admissionEvidence: productionRuntime.evidence }),
595
+ }
596
+ : {}),
597
+ ceilingController: params.ceilingController,
598
+ onProgress: params.onProgress,
599
+ },
600
+ };
601
+ }