crysk 0.0.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +611 -3
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/SKILL-y8rv8msh.md +134 -0
  10. package/dist/SKILL-ygka1bs0.md +515 -0
  11. package/dist/adjudicator-dtg2axnh.md +86 -0
  12. package/dist/admission-config.example-a9vqmmad.json +9 -0
  13. package/dist/ci-admission-camfbx2b.md +122 -0
  14. package/dist/ci-admission-qk9r9taq.md +124 -0
  15. package/dist/cli.js +42501 -0
  16. package/dist/consolidate-ac0mnfyj.md +24 -0
  17. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  18. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  19. package/dist/deep-review-parity-0ec904db.md +120 -0
  20. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  21. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  22. package/dist/index.js +20190 -0
  23. package/dist/opencode-ci-7b0be64p.md +141 -0
  24. package/dist/review-refuter-j4e9gezy.md +71 -0
  25. package/dist/scout-yvp153q7.md +140 -0
  26. package/dist/summarizer-zca44nxa.md +18 -0
  27. package/dist/workflow-w1g9szna.yml +151 -0
  28. package/package.json +81 -4
  29. package/prompts/consolidate.md +24 -0
  30. package/prompts/default/PROVENANCE.md +18 -0
  31. package/prompts/default/deep-review-lifecycle.md +362 -0
  32. package/prompts/default/deep-review-logic.md +156 -0
  33. package/prompts/default/deep-review-parity.md +120 -0
  34. package/prompts/default/deep-review-reliability.md +125 -0
  35. package/prompts/default/deep-review-resilience.md +118 -0
  36. package/prompts/default/review-refuter.md +71 -0
  37. package/prompts/scout.md +140 -0
  38. package/prompts/summarizer.md +18 -0
  39. package/skills/crysk/SKILL.md +74 -0
  40. package/skills/crysk-ci-setup/SKILL.md +134 -0
  41. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  42. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  43. package/skills/crysk-ci-setup/references/ci-admission.md +124 -0
  44. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  45. package/skills/crysk-loop/SKILL.md +515 -0
  46. package/skills/crysk-loop/adjudicator.md +86 -0
  47. package/skills/crysk-pr/SKILL.md +66 -0
  48. package/src/agent-env.ts +1084 -0
  49. package/src/asset-manifest.ts +83 -0
  50. package/src/assets.d.ts +6 -0
  51. package/src/assets.ts +183 -0
  52. package/src/brand-paths.ts +155 -0
  53. package/src/brand.ts +255 -0
  54. package/src/ci/admission-ledger.ts +350 -0
  55. package/src/ci/classify-error.ts +73 -0
  56. package/src/ci/cli-record.ts +271 -0
  57. package/src/ci/force-comment.ts +39 -0
  58. package/src/ci/gates.ts +945 -0
  59. package/src/ci/outcome.ts +2181 -0
  60. package/src/ci/override.ts +187 -0
  61. package/src/ci/publish.ts +1639 -0
  62. package/src/ci/reporter.ts +626 -0
  63. package/src/ci/review-admission.ts +910 -0
  64. package/src/ci/review-levels.ts +310 -0
  65. package/src/ci/review-policy.ts +18 -0
  66. package/src/ci/review-risk.ts +184 -0
  67. package/src/ci/setup.ts +844 -0
  68. package/src/ci/trigger.ts +1353 -0
  69. package/src/cli.ts +348 -0
  70. package/src/commands/activity.ts +67 -0
  71. package/src/commands/ci-setup-questions.ts +397 -0
  72. package/src/commands/ci-setup.ts +381 -0
  73. package/src/commands/config.ts +99 -0
  74. package/src/commands/doctor.ts +108 -0
  75. package/src/commands/init.ts +139 -0
  76. package/src/commands/mcp.ts +10 -0
  77. package/src/commands/menu.ts +129 -0
  78. package/src/commands/post.ts +302 -0
  79. package/src/commands/skills.ts +83 -0
  80. package/src/commands/status.ts +173 -0
  81. package/src/commands/triage.ts +342 -0
  82. package/src/commands/uninstall.ts +37 -0
  83. package/src/commands/upgrade.ts +214 -0
  84. package/src/commands/usage.ts +98 -0
  85. package/src/compare/compare.ts +28 -0
  86. package/src/compare/floor-test.ts +471 -0
  87. package/src/compare/martian-adapter.ts +80 -0
  88. package/src/config/config.ts +267 -0
  89. package/src/corpus/corpus.ts +1094 -0
  90. package/src/corpus/preflight.ts +1789 -0
  91. package/src/diversity/accounting.ts +90 -0
  92. package/src/diversity/adjudication.ts +145 -0
  93. package/src/diversity/admission.ts +60 -0
  94. package/src/diversity/benchmark.ts +195 -0
  95. package/src/diversity/clustering.ts +285 -0
  96. package/src/diversity/errors.ts +7 -0
  97. package/src/diversity/identity.ts +285 -0
  98. package/src/diversity/index.ts +11 -0
  99. package/src/diversity/pipeline-integration.ts +448 -0
  100. package/src/diversity/projection.ts +57 -0
  101. package/src/diversity/self-contained.ts +68 -0
  102. package/src/diversity/target-validation.ts +179 -0
  103. package/src/doctor-migration.ts +209 -0
  104. package/src/doctor.ts +723 -0
  105. package/src/errors.ts +83 -0
  106. package/src/execution/admission.ts +75 -0
  107. package/src/execution/atomic-write.ts +35 -0
  108. package/src/execution/attempt-evidence.ts +415 -0
  109. package/src/execution/bucket-id.ts +136 -0
  110. package/src/execution/concurrency-limiter.ts +175 -0
  111. package/src/execution/contracts.ts +443 -0
  112. package/src/execution/failure-classification.ts +42 -0
  113. package/src/execution/failure-policy.ts +240 -0
  114. package/src/execution/harness.ts +2548 -0
  115. package/src/execution/settlement.ts +348 -0
  116. package/src/execution/spawned-process.ts +66 -0
  117. package/src/execution/spend-limiter.ts +424 -0
  118. package/src/execution/step-artifacts.ts +55 -0
  119. package/src/execution/usage-normalized.ts +469 -0
  120. package/src/git/git.ts +396 -0
  121. package/src/git/identity.ts +64 -0
  122. package/src/git/refs.ts +140 -0
  123. package/src/home-preflight.ts +443 -0
  124. package/src/home.ts +243 -0
  125. package/src/ignore-file.ts +336 -0
  126. package/src/ignore-read.ts +118 -0
  127. package/src/index.ts +34 -0
  128. package/src/legacy-launchd.ts +29 -0
  129. package/src/mcp/mcp.ts +150 -0
  130. package/src/mcp/preflight.ts +407 -0
  131. package/src/menu-context.ts +192 -0
  132. package/src/model/catalog.ts +251 -0
  133. package/src/model/exec-snapshots.ts +390 -0
  134. package/src/model/free-discovery.ts +302 -0
  135. package/src/model/provider-capabilities.ts +814 -0
  136. package/src/model/routing.ts +600 -0
  137. package/src/pr/admission.ts +984 -0
  138. package/src/pr/answered-findings.ts +169 -0
  139. package/src/pr/ci-admission-gate.ts +743 -0
  140. package/src/pr/ci-publish.ts +76 -0
  141. package/src/pr/discovery.ts +432 -0
  142. package/src/pr/inline.ts +507 -0
  143. package/src/pr/plan.ts +366 -0
  144. package/src/pr/posting.ts +115 -0
  145. package/src/pr/pr-status.ts +845 -0
  146. package/src/pr/pr.ts +3642 -0
  147. package/src/pr/preflight.ts +1031 -0
  148. package/src/pr/publish-outcome.ts +361 -0
  149. package/src/pr/range.ts +119 -0
  150. package/src/pr/reverts-preflight.ts +606 -0
  151. package/src/pr/reverts.ts +377 -0
  152. package/src/pr/review-pr.ts +927 -0
  153. package/src/pr/status.ts +154 -0
  154. package/src/pr/target.ts +388 -0
  155. package/src/pr/teardown.ts +437 -0
  156. package/src/pr/worktree-setup.ts +60 -0
  157. package/src/production-runtime.ts +1877 -0
  158. package/src/progress.ts +487 -0
  159. package/src/rereview/adjudicate.ts +89 -0
  160. package/src/rereview/classify.ts +362 -0
  161. package/src/rereview/identity.ts +211 -0
  162. package/src/rereview/plan.ts +308 -0
  163. package/src/rereview/prepare.ts +1025 -0
  164. package/src/rereview/state.ts +767 -0
  165. package/src/rereview/verify.ts +241 -0
  166. package/src/review/boundary.ts +105 -0
  167. package/src/review/consolidate.ts +246 -0
  168. package/src/review/dedupe.ts +368 -0
  169. package/src/review/drafts.ts +448 -0
  170. package/src/review/findings-conformance.ts +120 -0
  171. package/src/review/findings.ts +714 -0
  172. package/src/review/pipeline.ts +3977 -0
  173. package/src/review/preflight.ts +3575 -0
  174. package/src/review/prompt-set.ts +177 -0
  175. package/src/review/proof-refs.ts +187 -0
  176. package/src/review/report.ts +1821 -0
  177. package/src/review/review.ts +490 -0
  178. package/src/review/root-cause.ts +120 -0
  179. package/src/review/route-preflight.ts +289 -0
  180. package/src/review/run.ts +601 -0
  181. package/src/review/scout.ts +323 -0
  182. package/src/review/size-gate.ts +595 -0
  183. package/src/review/spec.ts +235 -0
  184. package/src/review/step-runner.ts +233 -0
  185. package/src/runner-authority.ts +596 -0
  186. package/src/security/binding-policy.ts +115 -0
  187. package/src/security/credential-broker.ts +773 -0
  188. package/src/security/evidence-redaction.ts +62 -0
  189. package/src/security/execution-authority.ts +27 -0
  190. package/src/security/redact.ts +71 -0
  191. package/src/security/workspace-read-broker.ts +466 -0
  192. package/src/server/client.ts +190 -0
  193. package/src/server/preflight.ts +217 -0
  194. package/src/server/server.ts +327 -0
  195. package/src/signal-handler.ts +50 -0
  196. package/src/store/activity.ts +413 -0
  197. package/src/store/backfill-preflight.ts +49 -0
  198. package/src/store/backfill.ts +141 -0
  199. package/src/store/gc-preflight.ts +206 -0
  200. package/src/store/gc.ts +424 -0
  201. package/src/store/metrics-preflight.ts +229 -0
  202. package/src/store/metrics.ts +236 -0
  203. package/src/store/preflight.ts +748 -0
  204. package/src/store/store.ts +693 -0
  205. package/src/system-tools.ts +355 -0
  206. package/src/transport-registry.ts +1124 -0
  207. package/src/transports/claude-code-cli.ts +1348 -0
  208. package/src/transports/opencode-admission.ts +515 -0
  209. package/src/transports/opencode-client.ts +3328 -0
  210. package/src/transports/opencode-evidence.ts +557 -0
  211. package/src/transports/opencode-mcp.ts +248 -0
  212. package/src/transports/opencode-sdk.ts +2294 -0
  213. package/src/transports/opencode-server.ts +535 -0
  214. package/src/triage/adjudication.ts +113 -0
  215. package/src/triage/reply.ts +125 -0
  216. package/src/triage/triage.ts +255 -0
  217. package/src/ui/activity.ts +173 -0
  218. package/src/ui/config-edit.ts +816 -0
  219. package/src/ui/config.ts +462 -0
  220. package/src/ui/menu.ts +1325 -0
  221. package/src/ui/plan.ts +1039 -0
  222. package/src/ui/primitives.ts +300 -0
  223. package/src/ui/progress.ts +298 -0
  224. package/src/ui/result.ts +552 -0
  225. package/src/ui/review-menu.ts +312 -0
  226. package/src/ui/select.ts +528 -0
  227. package/src/ui/tree.ts +178 -0
  228. package/src/uninstaller.ts +479 -0
  229. package/src/updater.ts +836 -0
  230. package/src/usage.ts +77 -0
  231. package/src/watch/preflight.ts +1389 -0
  232. package/src/watch/watch.ts +1235 -0
  233. package/src/wizard.ts +877 -0
@@ -0,0 +1,490 @@
1
+ // Local mode (ROADMAP B0): point the engine at a real repo + branch and get a
2
+ // human-readable review back. Moved out of src/cli.ts (cli-decomp Phase 2,
3
+ // odd/tasks/cli-decomposition.md) as a byte-for-byte relocation — no
4
+ // behaviour change. See src/cli.ts's own header for the two hard rules that
5
+ // run through the sequence below (every failure loud and before any spend;
6
+ // human-readable output to stderr).
7
+
8
+ import { existsSync } from "node:fs";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ import {
12
+ ingestReviewMetrics,
13
+ notionalCostInput,
14
+ persistCanonicalReview,
15
+ pipelineConfigInput,
16
+ } from "#config/config";
17
+ import {
18
+ git,
19
+ localResultLinks,
20
+ resolveBase,
21
+ resolveCommit,
22
+ resolveDiffFrom,
23
+ resolveRepoRoot,
24
+ } from "#git/git";
25
+ import { engineIdentity } from "#git/identity";
26
+ import { countFreeRouteSteps } from "#model/free-discovery";
27
+ import { reviewPr } from "#pr/review-pr";
28
+ import type { Telemetry } from "#review/findings";
29
+ import { type PipelineResult, runPipeline } from "#review/pipeline";
30
+ import {
31
+ allExcludedMessage,
32
+ type CliOptions,
33
+ createRunDir,
34
+ emptyDiffMessage,
35
+ resolveMaxConcurrentSteps,
36
+ resolveSharedPrefix,
37
+ } from "#review/preflight";
38
+ import { estimateCost } from "#review/report";
39
+ import {
40
+ pipelineConsolidateInput,
41
+ pipelineScoutInput,
42
+ pipelineSummarizerInput,
43
+ } from "#review/route-preflight";
44
+ import {
45
+ assertDistinctRange,
46
+ buildTelemetry,
47
+ computeDiffStatAndSizeGate,
48
+ enforceCapabilityGate,
49
+ loadRunConfig,
50
+ prepareRunnerForRoute,
51
+ resolveGotchasPath,
52
+ resolveParityFires,
53
+ resolvePipelineRoute,
54
+ resolvePromptSet,
55
+ selectActiveHunters,
56
+ validateGotchas,
57
+ writeMcpConfig,
58
+ writeRunFindings,
59
+ writeRunReport,
60
+ } from "#review/run";
61
+ import { filterDiffByIgnoreRules, sizeGateConfigFor } from "#review/size-gate";
62
+ import { registerActiveRun, unregisterActiveRun } from "#store/activity";
63
+ import {
64
+ configProvenanceOf,
65
+ type PlanContext,
66
+ planDetails,
67
+ renderPlan,
68
+ reviewingLine,
69
+ } from "#ui/plan";
70
+ import { log, styleEnabled } from "#ui/primitives";
71
+ import { applySizeGate, confirm, startProgressRenderer } from "#ui/progress";
72
+ import { renderResult } from "#ui/result";
73
+ import { freeBillingMode } from "#ui/select";
74
+ import { CliError } from "../errors";
75
+ import { prheroLayout } from "../home-preflight";
76
+ import { readLocalIgnoreRules } from "../ignore-read";
77
+ import type { ProductionRuntime } from "../production-runtime";
78
+ import { resolveRunnerAuthority } from "../runner-authority";
79
+
80
+ export async function review(options: CliOptions): Promise<number> {
81
+ // PR mode is a different front half (gh-resolved range, detached worktree)
82
+ // around the same pipeline; it branches here so the local flow below stays
83
+ // byte-for-byte what B0 shipped.
84
+ if (options.pr !== undefined) return reviewPr(options, options.pr);
85
+
86
+ // 1 — the repo.
87
+ const repoRoot = await resolveRepoRoot(options.repo);
88
+
89
+ // 2 — the config, read BEFORE anything that consumes it. It now carries
90
+ // agents_dir and default_base, so both the prompt set and the base ref
91
+ // depend on it; loading it later would mean resolving them against a config
92
+ // that had not been read yet.
93
+ //
94
+ // Two layers since C5, folded by loadEffectiveConfig into the one
95
+ // LocalConfig everything below already expected. The --config missing-file
96
+ // error and the boundary rules live there.
97
+ const { loaded, config, summary, scout, post } = await loadRunConfig({
98
+ root: repoRoot,
99
+ home: os.homedir(),
100
+ configFlag: options.config,
101
+ options,
102
+ });
103
+ options = { ...options, scout, post };
104
+
105
+ // 3 — the base ref, then the canonical refs and the range.
106
+ const baseRef = await resolveBase(repoRoot, options, config);
107
+ const baseSha = await resolveCommit(repoRoot, baseRef.ref);
108
+ const headSha = await resolveCommit(repoRoot, options.head);
109
+ assertDistinctRange(baseSha, headSha);
110
+ const diffFromSha = await resolveDiffFrom(
111
+ repoRoot,
112
+ options.twoDot,
113
+ baseRef.ref,
114
+ options.head,
115
+ baseSha,
116
+ headSha,
117
+ );
118
+
119
+ // 4 — the tree the hunters will actually read.
120
+ // Every spawned step runs with repoRoot as its cwd, so the bytes under
121
+ // review are the WORKING TREE, not the commit. A dirty tree, or a checkout
122
+ // sitting on a different commit than --head, means the report describes one
123
+ // thing and the hunters read another — and nothing downstream can detect it.
124
+ const status = await git(repoRoot, ["status", "--porcelain"]);
125
+ if (!status.ok) throw new CliError(`git status failed: ${status.stderr}`);
126
+ if (status.stdout.trim().length > 0) {
127
+ throw new CliError(
128
+ "the working tree is dirty. Every review step reads this checkout " +
129
+ "directly, so uncommitted changes would be reviewed but never " +
130
+ "reported. Commit or stash them first:\n" +
131
+ `${status.stdout.trimEnd()}`,
132
+ );
133
+ }
134
+ const checkedOut = await resolveCommit(repoRoot, "HEAD");
135
+ if (checkedOut !== headSha) {
136
+ throw new CliError(
137
+ `HEAD is ${checkedOut} but --head resolves to ${headSha}. The steps ` +
138
+ "read the checkout, so review the commit that is checked out (or " +
139
+ "check out the one you want reviewed).",
140
+ );
141
+ }
142
+
143
+ // 5 + 6 — the prompt set and the wiring that consumes it.
144
+ // The WHOLE resolution, not just its dir: under the compiled binary the
145
+ // prompt set is a map of embedded paths and `dir` is only a display label.
146
+ const { agents, spec, agentFiles, promptSet } = await resolvePromptSet(
147
+ options,
148
+ loaded,
149
+ );
150
+ const { dir: agentsDir, source: agentsDirSource } = agents;
151
+
152
+ // 7 — gotchas. Checked HERE rather than left to the pipeline's fail-loud
153
+ // abort: the pipeline is right to refuse, but all it can return is a
154
+ // zero-cost partial run, which reads like a clean review to a human.
155
+ //
156
+ // `--gotchas` exists because requiring the file INSIDE the reviewed tree
157
+ // makes two legitimate cases impossible: reviewing a historical commit (the
158
+ // file would be an untracked addition, and the clean-tree gate rightly
159
+ // refuses), and reviewing a repo you do not control. The gotchas describe
160
+ // the repo, not the commit, so they do not belong to the checkout.
161
+ const gotchasPath = resolveGotchasPath(options.gotchas, repoRoot);
162
+ await validateGotchas(gotchasPath);
163
+
164
+ // 7.5 — `.prheroignore`, read from the WORKING TREE. Local review has no
165
+ // PR-author trust boundary to defend (there is no "someone else's commit"
166
+ // here — repoRoot is the operator's own checkout), so it is read from
167
+ // exactly the tree the diff below comes from, the same way gotchas.md just
168
+ // was.
169
+ const userIgnore = await readLocalIgnoreRules(repoRoot);
170
+
171
+ // 8 — run dir + diff.
172
+ const { runDir, repoId } = await createRunDir(options, repoRoot, headSha);
173
+ const diffPath = path.join(runDir, "diff.patch");
174
+ // diffFromSha, never baseSha: see resolveDiffFrom. The numstat below uses
175
+ // the same endpoint on purpose — a cost estimate computed over a wider range
176
+ // than the one being reviewed is a bill that arrives from nowhere.
177
+ const diff = await git(repoRoot, ["diff", `${diffFromSha}..${headSha}`]);
178
+ if (!diff.ok) throw new CliError(`git diff failed: ${diff.stderr}`);
179
+ if (diff.stdout.trim().length === 0) {
180
+ throw new CliError(
181
+ emptyDiffMessage(baseRef.ref, options.head, options.twoDot),
182
+ );
183
+ }
184
+ // The EFFECTIVE diff is what lands in diff.patch, because diff.patch is
185
+ // what the pipeline hands to every hunter: excluded files must fall out of
186
+ // the reviewed diff itself, or the gate discounts a lockfile the bill still
187
+ // pays for in full (see filterDiffByIgnoreRules). diff.raw.patch keeps the
188
+ // unfiltered bytes for audit, and only when there is a difference to audit.
189
+ const gateConfig = sizeGateConfigFor(options, loaded.effective, userIgnore);
190
+ const effectiveDiff = filterDiffByIgnoreRules(
191
+ diff.stdout,
192
+ gateConfig.excludeRules,
193
+ );
194
+ if (effectiveDiff.patch.trim().length === 0) {
195
+ throw new CliError(allExcludedMessage(effectiveDiff.droppedPaths));
196
+ }
197
+ await Bun.write(diffPath, effectiveDiff.patch);
198
+ if (effectiveDiff.droppedPaths.length > 0) {
199
+ await Bun.write(path.join(runDir, "diff.raw.patch"), diff.stdout);
200
+ }
201
+
202
+ // 9 — diff stat, TWICE and on purpose. See computeDiffStatAndSizeGate
203
+ // (src/review/run.ts) for the full rationale.
204
+ const { diffStat, sizeGate } = await computeDiffStatAndSizeGate({
205
+ runGit: (args) => git(repoRoot, args),
206
+ range: `${diffFromSha}..${headSha}`,
207
+ pathArgs: [],
208
+ gateConfig,
209
+ });
210
+
211
+ // 10 — MCP registry.
212
+ const mcpConfigPath = path.join(runDir, "mcp.json");
213
+ const codegraphAvailable = existsSync(path.join(repoRoot, ".codegraph"));
214
+ await writeMcpConfig(mcpConfigPath, codegraphAvailable);
215
+
216
+ // 11 — the plan. Triggers read the EFFECTIVE diff, the same bytes the
217
+ // pipeline will read back from diff.patch: a conditional hunter must never
218
+ // fire on a path no hunter was given.
219
+ const parityFires = resolveParityFires(
220
+ effectiveDiff.patch,
221
+ config.parity_trigger_paths,
222
+ );
223
+ const activeHunters = selectActiveHunters(spec.agents, parityFires);
224
+ const hunterCount = activeHunters.length;
225
+ const estimate = estimateCost(
226
+ diffStat,
227
+ hunterCount,
228
+ summary.enabled,
229
+ options.scout,
230
+ 0,
231
+ true,
232
+ );
233
+ const productionRoute = await resolvePipelineRoute({
234
+ routingConfigured: config.routing !== undefined,
235
+ workspaceRoot: repoRoot,
236
+ spec,
237
+ options,
238
+ agentFiles,
239
+ routingConfig: config.routing,
240
+ summary,
241
+ });
242
+ const routePlan = productionRoute?.routePlan;
243
+ const productionAdmission = productionRoute?.productionAdmission;
244
+ // Read off the admission above, which already decided every free verdict:
245
+ // this adds no probe. Absent without routing, so the band stays.
246
+ const freeRoute =
247
+ routePlan === undefined || productionAdmission === undefined
248
+ ? undefined
249
+ : await countFreeRouteSteps({
250
+ steps: routePlan.steps,
251
+ probe: productionAdmission.freeModelProbe,
252
+ });
253
+ // Named rather than inlined into renderPlan: the same context is what the
254
+ // confirm menu's "Show details" renders, and building it twice would risk
255
+ // the card and the details view disagreeing about the run they describe.
256
+ const planContext: PlanContext = {
257
+ options,
258
+ repoRoot,
259
+ baseRef,
260
+ baseSha,
261
+ diffFromSha,
262
+ headSha,
263
+ diffStat,
264
+ diffPath,
265
+ agentsDir,
266
+ agentFiles,
267
+ spec,
268
+ runDir,
269
+ config,
270
+ summary,
271
+ parityFires,
272
+ codegraphAvailable,
273
+ estimate,
274
+ hunterCount,
275
+ // Evaluated above (step 9) and ENFORCED below at step 13, unchanged;
276
+ // the plan only prints the verdict, last, where the decision is made.
277
+ sizeGate,
278
+ droppedPaths: effectiveDiff.droppedPaths,
279
+ configProvenance: configProvenanceOf(loaded, agentsDirSource),
280
+ ...(routePlan === undefined ? {} : { routePlan }),
281
+ ...(freeRoute === undefined ? {} : { freeRoute }),
282
+ };
283
+ for (const line of renderPlan(planContext, styleEnabled())) log(line);
284
+
285
+ // 12 — the free exit. Dry run reports the gate verdict (including that it
286
+ // WOULD skip) and still exits 0: its contract is "everything except
287
+ // spawn", and a $0 report is never a failure.
288
+ if (options.dryRun) {
289
+ log();
290
+ if (!sizeGate.ok && !options.force) {
291
+ log("dry run: this diff would be SKIPPED by the size gate (exit 1).");
292
+ }
293
+ log("dry run: nothing was spawned and nothing was spent.");
294
+ return 0;
295
+ }
296
+
297
+ // 12.5 — the capability gate (§11/D1-09): routed runs gate exact-binding
298
+ // readiness for the bindings that would execute; legacy runs keep the
299
+ // claude-code ProviderCapabilityReport path byte-compatible.
300
+ const runnerAuthority = await resolveRunnerAuthority({
301
+ workspaceRoot: repoRoot,
302
+ });
303
+ await enforceCapabilityGate({
304
+ routePlan,
305
+ workspaceRoot: repoRoot,
306
+ runnerAuthority,
307
+ productionAdmission,
308
+ });
309
+
310
+ // 13 — the size gate, BEFORE the cost band's confirm() for the unattended
311
+ // path. The watcher spawns with --yes, so a gate that lived only inside
312
+ // that confirmation would never fire in the one place — unattended spend
313
+ // — it exists to protect. An interactive TTY is offered Continue/Cancel
314
+ // instead of dying: --force stays the unattended hatch, not the only one.
315
+ const sizeGateChoice = await applySizeGate(sizeGate, options);
316
+ if (sizeGateChoice === "abort") return 1;
317
+
318
+ // 14 — the paid one. Local mode can never post (parseArgs rejects --post
319
+ // without --pr), so the "don't post" option is not offered and the choice's
320
+ // `post` field carries nothing local mode could act on.
321
+ if (!options.yes) {
322
+ const choice = await confirm(
323
+ estimate.low,
324
+ estimate.high,
325
+ false,
326
+ () => planDetails(planContext, styleEnabled()),
327
+ freeRoute,
328
+ );
329
+ if (choice.kind === "cancel") {
330
+ log("aborted; nothing was spent.");
331
+ return 1;
332
+ }
333
+ }
334
+
335
+ // 15 — run, with live progress: the expectation line up front, then one
336
+ // stderr line per pipeline event (plus a TTY heartbeat between them).
337
+ log(reviewingLine(hunterCount, summary, options));
338
+ const started = performance.now();
339
+ const progress = startProgressRenderer(
340
+ started,
341
+ `${baseRef.ref}..${options.head}`,
342
+ activeHunters.map((a) => a.key),
343
+ spec.agents.some((a) => a.role === "refuter"),
344
+ summary.enabled,
345
+ );
346
+ let result: PipelineResult;
347
+ await registerActiveRun({
348
+ pid: process.pid,
349
+ repo: repoId ?? path.basename(repoRoot),
350
+ runDir,
351
+ startedAt: new Date().toISOString(),
352
+ });
353
+ // §5.3 D1-10b: ONE controller shared by the pipeline and the runner. The
354
+ // pipeline aborts it when the ceiling fires; the runner's harness reads the
355
+ // same signal and refuses to start another attempt. Two controllers would
356
+ // leave the ceiling unable to stop the steps it is waiting on.
357
+ const ceilingController = new AbortController();
358
+ let productionRuntime: ProductionRuntime | undefined;
359
+ try {
360
+ const prepared = await prepareRunnerForRoute({
361
+ routePlan,
362
+ productionAdmission,
363
+ workspaceRoot: repoRoot,
364
+ runnerAuthority,
365
+ ceilingController,
366
+ onProgress: progress.onProgress,
367
+ maxConcurrentSteps: resolveMaxConcurrentSteps(config),
368
+ });
369
+ productionRuntime = prepared.productionRuntime;
370
+ result = await runPipeline(
371
+ {
372
+ // Local mode has no PR number. 0 is the schema-legal "not a PR" value
373
+ // the fixture eval already uses.
374
+ pr: 0,
375
+ // The commit the diff was actually computed against, not the tip of the
376
+ // base branch: the recorded base_sha must name the range that was
377
+ // reviewed, or nothing downstream can reproduce it.
378
+ baseSha: diffFromSha,
379
+ headSha,
380
+ worktree: repoRoot,
381
+ diffPath,
382
+ excludedPaths: effectiveDiff.droppedPaths,
383
+ exclusions: effectiveDiff.exclusions,
384
+ ignoreFile: { readFrom: "working-tree", found: userIgnore.found },
385
+ gotchasPath,
386
+ agentsDir,
387
+ ...(agents.files ? { agentFiles: agents.files } : {}),
388
+ runDir,
389
+ outPath: path.join(runDir, "findings.json"),
390
+ mcpConfigPath,
391
+ hopBudget: options.hopBudget,
392
+ ...(options.model ? { model: options.model } : {}),
393
+ parityTriggerPaths: config.parity_trigger_paths,
394
+ suspicionPriors: config.suspicion_priors,
395
+ ...pipelineSummarizerInput(summary),
396
+ ...pipelineScoutInput(options),
397
+ ...pipelineConsolidateInput(),
398
+ ...(resolveSharedPrefix(options) ? { sharedPrefix: true } : {}),
399
+ ...pipelineConfigInput(loaded),
400
+ ...(routePlan === undefined ? {} : { routePlan }),
401
+ engine: await engineIdentity(),
402
+ promptSet,
403
+ spec,
404
+ },
405
+ prepared.deps,
406
+ );
407
+ } finally {
408
+ // try/finally, never success-only: a leaked interval keeps the event
409
+ // loop alive and hangs process exit on the error path.
410
+ progress.stop();
411
+ await unregisterActiveRun(process.pid);
412
+ if (productionRuntime !== undefined) {
413
+ await productionRuntime.dispose();
414
+ }
415
+ }
416
+ const wallMs = Math.round(performance.now() - started);
417
+
418
+ // 16 — the artifact. Local mode neither builds nor syncs a codegraph
419
+ // index (it consumes whatever the repo already has), so indexMs is 0.
420
+ const telemetry: Telemetry = buildTelemetry(result, wallMs, 0);
421
+ const { doc, findingsPath } = await writeRunFindings({
422
+ runDir,
423
+ result,
424
+ pr: 0,
425
+ baseSha: diffFromSha,
426
+ headSha,
427
+ options,
428
+ agentFiles,
429
+ promptSet,
430
+ engine: await engineIdentity(),
431
+ telemetry,
432
+ });
433
+
434
+ // 16b — canonical product store & observability metrics.
435
+ persistCanonicalReview({
436
+ repoId,
437
+ runDir,
438
+ checkoutPath: repoRoot,
439
+ doc,
440
+ perAgent: result.perAgent,
441
+ log,
442
+ });
443
+ ingestReviewMetrics({
444
+ dbPath: prheroLayout(os.homedir()).metricsDbPath,
445
+ repoId,
446
+ runDir,
447
+ checkoutPath: repoRoot,
448
+ doc,
449
+ perAgent: result.perAgent,
450
+ log,
451
+ });
452
+
453
+ // 17 — the report.
454
+ const reportPath = await writeRunReport({
455
+ runDir,
456
+ doc,
457
+ repo: path.basename(repoRoot),
458
+ base: baseRef.ref,
459
+ head: options.head,
460
+ diffStat,
461
+ droppedPaths: effectiveDiff.droppedPaths,
462
+ result,
463
+ wallMs,
464
+ });
465
+
466
+ // 18 — the summary. Counts, the FINDINGS THEMSELVES, where the artifacts
467
+ // landed, and a clickable url per finding: the renderer derives every number
468
+ // from `doc`, so the terminal cannot disagree with the findings.json written
469
+ // two steps up. Links are best-effort and silent when unavailable (no github
470
+ // remote, or a head this repo has not pushed) — see localResultLinks.
471
+ const links = await localResultLinks(repoRoot, headSha);
472
+ for (const line of renderResult({
473
+ doc,
474
+ costUsd: result.usage.cost_usd_est,
475
+ ...notionalCostInput(result),
476
+ ...(freeRoute === undefined ? {} : { billing: freeBillingMode(freeRoute) }),
477
+ wallMs,
478
+ estimate: { low: estimate.low, high: estimate.high },
479
+ runDir,
480
+ artifacts: [path.basename(reportPath), path.basename(findingsPath)],
481
+ ...(links === undefined ? {} : { links }),
482
+ sessionFailed: result.sessionFailed,
483
+ ...(result.unresolved.length > 0 ? { unresolved: result.unresolved } : {}),
484
+ styles: styleEnabled(),
485
+ })) {
486
+ log(line);
487
+ }
488
+ if (result.sessionFailed) return 1;
489
+ return 0;
490
+ }
@@ -0,0 +1,120 @@
1
+ // Derived root-cause clustering: how many DISTINCT defects a findings array
2
+ // actually describes. Pure and deterministic — same input array, same output.
3
+ //
4
+ // MEASUREMENT ONLY, and that is load-bearing. Nothing here deletes, merges,
5
+ // reorders, retiers, or renumbers a finding: the lab's scorer reads
6
+ // `findings[]` alone, so any collapse performed here would surface as a recall
7
+ // regression on a run whose recall did not change. Clustering is reported
8
+ // alongside the findings, never applied to them.
9
+
10
+ export interface RootCauseCluster {
11
+ id: string; // RC001, RC002, … in first-appearance order
12
+ anchor: string | null; // null when the finding carried no anchor at all
13
+ finding_ids: string[]; // in input order
14
+ }
15
+
16
+ export interface RootCauseSummary {
17
+ clusters: RootCauseCluster[];
18
+ distinct_root_causes: number;
19
+ }
20
+
21
+ // The minimum a finding must expose to be clustered. Structural on purpose:
22
+ // the same function has to serve live engine `Finding`s and raw findings.json
23
+ // parsed off disk from a run that predates `root_cause_id` entirely.
24
+ export interface RootCauseInput {
25
+ id: string;
26
+ proof_refs: string[];
27
+ }
28
+
29
+ // A proof_ref reads `path:line-range (prose about what happens there)`. The
30
+ // location token is the stable part: findings in one fan-out cite the SAME
31
+ // root-cause location but describe it differently ("stores raw seconds",
32
+ // "returns unscaled value"), so everything from the first whitespace on is
33
+ // discarded before comparison.
34
+ //
35
+ // Comparison is then EXACT — no case folding, no path normalization, no line
36
+ // -range merging, so `foo.ts:19` and `foo.ts:19-20` are different anchors.
37
+ // Every normalization rule is a guess about whether two citations mean the
38
+ // same place, and a wrong guess here merges unrelated findings (see the
39
+ // direction-of-error note on clusterByRootCause).
40
+ // A ref written `path.tsx: 12-14 (prose)` — a space after the colon — degenerates
41
+ // to a bare `path.tsx:` once the prose is cut, and a token with no colon at all is
42
+ // bare path too. Both are FILE-level, and a file-level anchor merges every finding
43
+ // that happens to live in the same file. `review/dedupe.ts` already paid for this exact
44
+ // mistake: its pass 2 refuses to collapse symbol-less findings because keying on
45
+ // path alone over-merges distinct defects file-wide (a judgment-day finding). Same
46
+ // rule here — no location component means no anchor, so the finding stays a
47
+ // singleton instead of dragging its neighbours in.
48
+ export function extractAnchor(proofRefs: string[]): string | null {
49
+ const first = proofRefs[0];
50
+ if (first === undefined) return null;
51
+ const trimmed = first.trim();
52
+ const boundary = trimmed.search(/\s/);
53
+ const anchor = boundary === -1 ? trimmed : trimmed.slice(0, boundary);
54
+ if (anchor.length === 0) return null;
55
+ const colon = anchor.lastIndexOf(":");
56
+ if (colon === -1 || colon === anchor.length - 1) return null;
57
+ return anchor;
58
+ }
59
+
60
+ // Partitions `findings` by the anchor of their FIRST proof_ref only — never a
61
+ // union-find over any shared ref.
62
+ //
63
+ // Transitive clustering is the tempting version and it is wrong: findings in a
64
+ // fan-out also share INCIDENTAL refs (every consumer of a broken producer
65
+ // tends to cite the same shared formatting or utility helper too), so chaining
66
+ // on "shares any ref" welds unrelated defects into one blob. Over-clustering
67
+ // deflates the apparent false-positive count, which is the direction that
68
+ // flatters the engine — so this deliberately errs toward UNDER-clustering:
69
+ // worst case a real fan-out is reported as several root causes, never the
70
+ // reverse.
71
+ //
72
+ // The first ref is not an arbitrary pick either. The hunter output contract
73
+ // orders proof_refs as ["producer path:line", "consumer path:line"], so
74
+ // proof_refs[0] is where the defect LIVES while the rest is where it shows up.
75
+ //
76
+ // A finding with no anchor is always its own singleton and never joins
77
+ // anything: absence of evidence about the root cause is not evidence that two
78
+ // findings share one.
79
+ export function clusterByRootCause(
80
+ findings: ReadonlyArray<RootCauseInput>,
81
+ ): RootCauseSummary {
82
+ const ordered: Array<{ anchor: string | null; finding_ids: string[] }> = [];
83
+ const byAnchor = new Map<string, { finding_ids: string[] }>();
84
+ for (const finding of findings) {
85
+ const anchor = extractAnchor(finding.proof_refs);
86
+ if (anchor === null) {
87
+ ordered.push({ anchor: null, finding_ids: [finding.id] });
88
+ continue;
89
+ }
90
+ const existing = byAnchor.get(anchor);
91
+ if (existing) {
92
+ existing.finding_ids.push(finding.id);
93
+ continue;
94
+ }
95
+ const cluster = { anchor, finding_ids: [finding.id] };
96
+ byAnchor.set(anchor, cluster);
97
+ ordered.push(cluster);
98
+ }
99
+ // Ids are stamped after the partition so RC00N follows the order in which
100
+ // each cluster FIRST appeared over the input array, not the order in which
101
+ // it happened to finish filling up.
102
+ const clusters = ordered.map((cluster, i) => ({
103
+ id: `RC${String(i + 1).padStart(3, "0")}`,
104
+ anchor: cluster.anchor,
105
+ finding_ids: cluster.finding_ids,
106
+ }));
107
+ return { clusters, distinct_root_causes: clusters.length };
108
+ }
109
+
110
+ export function rootCauseIdByFinding(
111
+ summary: RootCauseSummary,
112
+ ): Map<string, string> {
113
+ const byFinding = new Map<string, string>();
114
+ for (const cluster of summary.clusters) {
115
+ for (const findingId of cluster.finding_ids) {
116
+ byFinding.set(findingId, cluster.id);
117
+ }
118
+ }
119
+ return byFinding;
120
+ }