crysk 0.0.0 → 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 +609 -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/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 +81 -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
package/src/ui/plan.ts ADDED
@@ -0,0 +1,1039 @@
1
+ // The plan card and its details view, as LINES. Both pairs of renderers
2
+ // (local mode's and PR mode's) are total functions of their inputs: `styles`
3
+ // arrives as a parameter, width is either explicit or resolved from
4
+ // ui/primitives.ts's terminalWidth(), and all returned content is assertable
5
+ // offline without a TTY.
6
+
7
+ import { existsSync } from "node:fs";
8
+ import path from "node:path";
9
+ import type { EffectiveConfig } from "#config/config";
10
+ import { exclusionLines } from "#git/git";
11
+ import { isFullCommitId } from "#git/refs";
12
+ import type { FreeRouteBilling } from "#model/free-discovery";
13
+ import type { ResolvedRoutePlan } from "#model/routing";
14
+ import type { PrTarget } from "#pr/preflight";
15
+ import { DEFAULT_SCOUT_MODEL } from "#review/pipeline";
16
+ import {
17
+ type AgentsDirSource,
18
+ type BaseRefResolution,
19
+ type CliOptions,
20
+ type ConfigSource,
21
+ type ConfigSources,
22
+ DEFAULT_SUMMARY_MODEL,
23
+ type LocalConfig,
24
+ type SummarySettings,
25
+ } from "#review/preflight";
26
+ import type { ParsedAgent } from "#review/prompt-set";
27
+ import {
28
+ type DiffStat,
29
+ type estimateCost,
30
+ formatStepRoute,
31
+ } from "#review/report";
32
+ import { type SizeGateVerdict, sizeGateLine } from "#review/size-gate";
33
+ import type { ReviewSpec } from "#review/spec";
34
+ import {
35
+ bold,
36
+ box,
37
+ green,
38
+ labelColumnWidth,
39
+ markerRowLines,
40
+ red,
41
+ row,
42
+ section,
43
+ shortPath,
44
+ shortSha,
45
+ terminalWidth,
46
+ yellow,
47
+ } from "#ui/primitives";
48
+ import { FREE_STEPS_NOTE, freeBillingMode } from "#ui/select";
49
+
50
+ // C5 O-7's payload for both plan surfaces: everything the card and the
51
+ // details view need to name a value the operator cannot see by opening their
52
+ // checkout. Optional on both contexts, so a context assembled without it
53
+ // renders exactly the pre-C5 plan.
54
+ export interface ConfigProvenance {
55
+ sources: ConfigSources;
56
+ // Read off the RESOLUTION, never off `sources`: ConfigSource has no `flag`
57
+ // member (judgment ledger JD-10), so the record cannot say that --agents
58
+ // beat both layers — and a card that tagged such a run `global` would be
59
+ // naming the file that LOST. AgentsDirSource can say it, so it is what the
60
+ // tag is derived from.
61
+ agentsDirSource: AgentsDirSource;
62
+ repoConfigPath: string;
63
+ globalConfigPath: string;
64
+ globalPresent: boolean;
65
+ }
66
+
67
+ // The two halves the shell holds separately — the merge's record, and the
68
+ // agents-dir chain's own answer — joined once, so the three plan contexts
69
+ // (local, PR dry run, PR real) cannot assemble three different versions of
70
+ // the same fact.
71
+ export function configProvenanceOf(
72
+ loaded: EffectiveConfig,
73
+ agentsDirSource: AgentsDirSource,
74
+ ): ConfigProvenance {
75
+ return {
76
+ sources: loaded.sources,
77
+ agentsDirSource,
78
+ repoConfigPath: loaded.repoConfigPath,
79
+ globalConfigPath: loaded.globalConfigPath,
80
+ globalPresent: loaded.globalPresent,
81
+ };
82
+ }
83
+
84
+ // A value the operator cannot see in the checkout is tagged; a value from the
85
+ // repo file is not, because that is the unsurprising case and the card is
86
+ // already dense.
87
+ //
88
+ // `default` is deliberately NOT tagged (judgment ledger JD-21, where O-7's
89
+ // "any value that did not come from the repo file" and §3.6's "global or
90
+ // capped" disagree). §3.6's reading is the one that keeps the operator
91
+ // un-surprised: a defaulted value is byte-for-byte pre-C5 behaviour, and the
92
+ // card already prints every one of them in a row of its own — the summarizer
93
+ // row, the parity row, the priors count, the base's source tag. Tagging six
94
+ // defaults on every quiet repo would bury the one tag that is genuinely new
95
+ // information. Naming every key's layer is `pr-hero config`'s job (§3.10),
96
+ // where the whole point is the exhaustive list.
97
+ function configTag(key: string, source: ConfigSource): string | undefined {
98
+ return source === "global" || source === "capped"
99
+ ? `${key} ← ${source}`
100
+ : undefined;
101
+ }
102
+
103
+ // Which keys a flag decided, so the two consumers below cannot disagree about
104
+ // it. A flag decided the value, so NO config layer did — and D5 lets a flag
105
+ // exceed a cap on purpose. ConfigSource cannot express that (JD-10), so the
106
+ // honest move is to print no tag at all rather than to name a layer that lost.
107
+ // `agents_dir` is read off the RESOLUTION, the only thing that can say a flag
108
+ // beat both layers. Shared rather than inlined because the suppression and the
109
+ // caption that has to account for it are two sides of one fact: when this said
110
+ // only "suppress the tag", configDetail went on claiming an origin for exactly
111
+ // the keys the suppression had removed from the check.
112
+ function flagDecided(
113
+ provenance: ConfigProvenance,
114
+ options: Pick<CliOptions, "base" | "summary" | "model">,
115
+ ): { base: boolean; summary: boolean; model: boolean; any: boolean } {
116
+ const base = options.base !== undefined;
117
+ const summary = options.summary !== undefined;
118
+ const model = options.model !== undefined;
119
+ return {
120
+ base,
121
+ summary,
122
+ model,
123
+ any: base || summary || model || provenance.agentsDirSource === "flag",
124
+ };
125
+ }
126
+
127
+ function configTags(
128
+ provenance: ConfigProvenance,
129
+ options: Pick<CliOptions, "base" | "summary" | "model">,
130
+ ): string[] {
131
+ const s = provenance.sources;
132
+ const flagged = flagDecided(provenance, options);
133
+ // Every key is listed, including the three `repo` ones that can never
134
+ // produce a tag today: a direction change must not silently drop a key off
135
+ // the card.
136
+ return [
137
+ // Both sources the operator cannot see by opening the checkout, not just
138
+ // the global file. Judgment ledger JD-9 left "a global `agents_dir`
139
+ // silently preempts PRHERO_AGENTS_DIR" open on the grounds that this tag
140
+ // is the mitigation — but firing on `global` alone covered one direction
141
+ // only: an env-sourced prompt set, which picks every hunter's model, was
142
+ // as absent from the checkout as a global one and printed nothing. `flag`
143
+ // stays untagged (D5, JD-10) and `repo` stays untagged (§3.6, the
144
+ // unsurprising case).
145
+ provenance.agentsDirSource === "global" ||
146
+ provenance.agentsDirSource === "env"
147
+ ? `agents_dir ← ${provenance.agentsDirSource}`
148
+ : undefined,
149
+ flagged.base ? undefined : configTag("default_base", s.default_base),
150
+ configTag("parity_trigger_paths", s.parity_trigger_paths),
151
+ configTag("suspicion_priors", s.suspicion_priors),
152
+ flagged.summary
153
+ ? undefined
154
+ : configTag("summary.enabled", s.summary.enabled),
155
+ flagged.model ? undefined : configTag("summary.model", s.summary.model),
156
+ configTag("max_verification_steps", s.max_verification_steps),
157
+ ].filter((tag): tag is string => tag !== undefined);
158
+ }
159
+
160
+ // The card's row, present only when there is something to say. Empty is the
161
+ // common case — one global file and one quiet repo produce at most a couple
162
+ // of tags — so this costs the card nothing on a run where nothing hoisted.
163
+ function configRow(
164
+ provenance: ConfigProvenance | undefined,
165
+ options: Pick<CliOptions, "base" | "summary" | "model">,
166
+ styles: boolean,
167
+ width: number,
168
+ ): string[] {
169
+ if (provenance === undefined) return [];
170
+ const tags = configTags(provenance, options);
171
+ if (tags.length === 0) return [];
172
+ return row(
173
+ "CONFIG",
174
+ `${tags.join(" · ")} (${provenance.globalConfigPath})`,
175
+ {
176
+ styles,
177
+ width,
178
+ },
179
+ );
180
+ }
181
+
182
+ // The details view's row: both file paths whether or not they exist, because
183
+ // "where do I even write this" is the other half of the question a teammate
184
+ // asks the moment a value surprises them. Not dense, and this is the view
185
+ // that exists for the reader who wants the whole answer.
186
+ function configDetail(
187
+ provenance: ConfigProvenance,
188
+ options: Pick<CliOptions, "base" | "summary" | "model">,
189
+ ): string {
190
+ const tags = configTags(provenance, options);
191
+ // No tags has TWO causes, and only one of them licenses the sentence this
192
+ // used to print unconditionally. Nothing hoisted is one. The other is that a
193
+ // flag decided a key and configTags suppressed its tag on purpose (JD-10) —
194
+ // and on that run "every value came from the repo file or a built-in
195
+ // default" is false about the one value the operator most recently typed.
196
+ // The caption is therefore scoped to what the function actually checked; it
197
+ // is not fixed by tagging the flag, which would reopen JD-10 by naming a
198
+ // layer for a key no layer decided. With no flag in play the original
199
+ // sentence is exact and stays: `flag` is excluded by the branch, `global`
200
+ // and `env` both produce a tag, so only repo-or-default can reach it.
201
+ return (
202
+ `repo ${provenance.repoConfigPath}` +
203
+ ` · global ${provenance.globalConfigPath}` +
204
+ ` (${provenance.globalPresent ? "present" : "absent"})` +
205
+ (tags.length > 0
206
+ ? ` · ${tags.join(" · ")}`
207
+ : flagDecided(provenance, options).any
208
+ ? " — every value a flag did not decide came from the repo file or" +
209
+ " a built-in default"
210
+ : " — every value came from the repo file or a built-in default")
211
+ );
212
+ }
213
+
214
+ export interface PlanContext {
215
+ options: CliOptions;
216
+ repoRoot: string;
217
+ baseRef: BaseRefResolution;
218
+ baseSha: string;
219
+ diffFromSha: string;
220
+ headSha: string;
221
+ diffStat: DiffStat;
222
+ diffPath: string;
223
+ agentsDir: string;
224
+ agentFiles: Map<string, ParsedAgent>;
225
+ spec: ReviewSpec;
226
+ runDir: string;
227
+ config: LocalConfig;
228
+ summary: SummarySettings;
229
+ parityFires: boolean;
230
+ codegraphAvailable: boolean;
231
+ estimate: ReturnType<typeof estimateCost>;
232
+ hunterCount: number;
233
+ // The gate's ALREADY-EVALUATED verdict, carried in so the plan can print
234
+ // it last. The gate is still decided by the shell, before the cost band's
235
+ // confirm() — this only moves where the line lands on screen.
236
+ sizeGate: SizeGateVerdict;
237
+ droppedPaths: string[];
238
+ // C5 O-7. Optional for the reason `resolved`/`rereview` are on the PR
239
+ // context: a plan assembled without it renders the pre-C5 card.
240
+ configProvenance?: ConfigProvenance;
241
+ // D2 PR3: Optional resolved route plan for model routing display
242
+ routePlan?: ResolvedRoutePlan;
243
+ // Free verdicts of the admitted route plan, read off the admission that already
244
+ // decided them. Absent means unknown, and the estimate line keeps its band.
245
+ freeRoute?: FreeRouteBilling;
246
+ // The terminal width every row and card below is laid out against, carried
247
+ // in exactly as ui/result.ts's ResultInput carries it. Optional so the shell
248
+ // may leave the one sniff to the renderer's entry point; the tests ALWAYS
249
+ // pin it, because these renderers were the reason `bun test` in a narrow
250
+ // pane could fail on a wrap point no test could stub.
251
+ width?: number;
252
+ }
253
+
254
+ // Where the base ref came from, because "main" chosen by fallback and "main"
255
+ // asked for by name are the same string with very different confidence behind
256
+ // them. The full sentence lives in the details view now; the card carries the
257
+ // short tag below, which says the same thing in one token.
258
+ function baseSourceNote(ctx: PlanContext): string {
259
+ switch (ctx.baseRef.source) {
260
+ case "flag":
261
+ return "--base";
262
+ case "config":
263
+ return "config default_base";
264
+ case "remote":
265
+ return "refs/remotes/origin/HEAD";
266
+ default:
267
+ return "fallback: no --base, no default_base, no remote head";
268
+ }
269
+ }
270
+
271
+ function baseSourceTag(ctx: PlanContext): string {
272
+ return ctx.baseRef.source === "fallback" ? "fallback" : baseSourceNote(ctx);
273
+ }
274
+
275
+ // The prose the plan card demotes: why the base ref is trusted, what the
276
+ // range actually means, and what the cost band was computed from. Long,
277
+ // true, and read at most once — so it does not belong between the operator
278
+ // and the yes/no they are about to give.
279
+ const PERMISSIONS_NOTE =
280
+ "steps run with --permission-mode bypassPermissions, bounded only by " +
281
+ "each agent's read-only tool allow-list";
282
+
283
+ function agentRow(
284
+ ctx: {
285
+ options: CliOptions;
286
+ agentFiles: Map<string, ParsedAgent>;
287
+ routePlan?: ResolvedRoutePlan;
288
+ },
289
+ agent: ReviewSpec["agents"][number],
290
+ fires: string,
291
+ ): string {
292
+ const parsed = ctx.agentFiles.get(agent.key);
293
+ const model = ctx.options.model ?? agent.model ?? parsed?.model ?? "?";
294
+ if (ctx.routePlan) {
295
+ const stepRoute = ctx.routePlan.steps.find(
296
+ (s) =>
297
+ s.stepKey === agent.key ||
298
+ s.stepKey === `hunter-${agent.key}` ||
299
+ (agent.role === "refuter" &&
300
+ (s.role === "refuter" || s.stepKey === "refuter")),
301
+ );
302
+ if (stepRoute) {
303
+ const formatted = formatStepRoute(stepRoute, model);
304
+ return `${agent.key.padEnd(12)} ${formatted.padEnd(8)} ${fires}`;
305
+ }
306
+ }
307
+ return `${agent.key.padEnd(12)} ${model.padEnd(8)} ${fires}`;
308
+ }
309
+
310
+ function summarizerRow(summary: SummarySettings): string {
311
+ const model = summary.model ?? DEFAULT_SUMMARY_MODEL;
312
+ return (
313
+ `summarizer`.padEnd(12) +
314
+ `${model}`.padEnd(8) +
315
+ (summary.enabled ? "always" : "disabled")
316
+ );
317
+ }
318
+
319
+ export function summarizerLabel(summary: SummarySettings): string {
320
+ return summary.enabled ? "+ summarizer" : "+ summarizer disabled";
321
+ }
322
+
323
+ // Printed on EVERY plan, off included. The scout adds a paid stage to the
324
+ // front of the run and the operator is about to confirm a band that already
325
+ // counts it, so "scout: off" is information, not noise — and a stage that
326
+ // only appears when it is on is a stage nobody notices arriving.
327
+ function scoutRow(
328
+ options: Pick<CliOptions, "scout" | "scoutModel" | "model">,
329
+ ): string {
330
+ const label = "scout".padEnd(12);
331
+ if (!options.scout) return `${label}${"-".padEnd(8)}disabled`;
332
+ // The same chain the pipeline resolves, printed before the money is spent:
333
+ // --model > --scout-model > the engine default (the bundled prompt pins no
334
+ // model, so there is no frontmatter seat to show here).
335
+ const model = options.model ?? options.scoutModel ?? DEFAULT_SCOUT_MODEL;
336
+ return `${label}${model.padEnd(8)}diff-only, before the hunters (experimental)`;
337
+ }
338
+
339
+ export function scoutLabel(options: Pick<CliOptions, "scout">): string {
340
+ return options.scout ? " + scout" : "";
341
+ }
342
+
343
+ // Lives here rather than in review/run.ts, beside the two labels it composes.
344
+ // It was first extracted into review/run.ts with the other shared run stages,
345
+ // which made that domain module import #ui/plan by value while ui/plan already
346
+ // imports #review/pipeline and #review/size-gate: no file-level cycle, but the
347
+ // review domain depending on presentation. It is a log line, so it belongs to
348
+ // the presentation layer that owns its labels.
349
+ // The one-line expectation printed just before the pipeline starts. Returns
350
+ // the string only — the orchestrator still calls log(), because withCiWorkflowGroup
351
+ // wraps the two call sites differently (PR mode groups it in a CI log group;
352
+ // local mode does not).
353
+ export function reviewingLine(
354
+ hunterCount: number,
355
+ summary: SummarySettings,
356
+ options: Pick<CliOptions, "scout">,
357
+ ): string {
358
+ return (
359
+ `reviewing — ${hunterCount} hunter${hunterCount === 1 ? "" : "s"} + ` +
360
+ `refuter ${summarizerLabel(summary)}${scoutLabel(options)}; ` +
361
+ "comparable trees have taken " +
362
+ "8–25 minutes"
363
+ );
364
+ }
365
+
366
+ // The last block on screen and the only one an operator must read: the gate
367
+ // verdict, then the money. Both used to sit mid-list, where the eye that had
368
+ // already given up on the plan never reached them.
369
+ interface PlanDecision {
370
+ sizeGate: SizeGateVerdict;
371
+ freeRoute?: FreeRouteBilling;
372
+ // Set only where the verdict is an ESTIMATE rather than the gate's own
373
+ // answer (the PR dry run's aggregate counters); printed beside it so
374
+ // nobody reads a guess as the verdict.
375
+ sizeGateNote?: string;
376
+ droppedPaths: string[];
377
+ force: boolean;
378
+ // Interactive override, distinct from --force: the operator confirmed
379
+ // "review anyway" at the size-gate menu. The plan names which hatch
380
+ // opened so a log cannot be read as "they passed --force".
381
+ sizeGateConfirmed?: boolean;
382
+ estimate: ReturnType<typeof estimateCost>;
383
+ hunterCount: number;
384
+ summarizer: boolean;
385
+ }
386
+
387
+ function decisionLines(
388
+ d: PlanDecision,
389
+ styles: boolean,
390
+ width: number,
391
+ ): string[] {
392
+ // sizeGateLine's wording is FIXED — size-gate.test.ts pins five substrings
393
+ // of it, and the watcher's log parser reads the same phrasing. The ✓/✗ is
394
+ // decoration in front of it, never a replacement for it.
395
+ const note = d.sizeGateNote === undefined ? "" : ` ${d.sizeGateNote}`;
396
+ const lines = [
397
+ "",
398
+ ...markerRowLines(
399
+ d.sizeGate.ok ? "✓" : "✗",
400
+ `${sizeGateLine(d.sizeGate)}${note}`,
401
+ d.sizeGate.ok ? green : red,
402
+ styles,
403
+ width,
404
+ ),
405
+ ...exclusionLines(d.droppedPaths, styles, width),
406
+ ];
407
+ if (!d.sizeGate.ok && d.force) {
408
+ lines.push(
409
+ ...markerRowLines(
410
+ "!",
411
+ "--force given: reviewing anyway.",
412
+ yellow,
413
+ styles,
414
+ width,
415
+ ),
416
+ );
417
+ } else if (!d.sizeGate.ok && d.sizeGateConfirmed) {
418
+ lines.push(
419
+ ...markerRowLines(
420
+ "!",
421
+ "confirmed: reviewing anyway.",
422
+ yellow,
423
+ styles,
424
+ width,
425
+ ),
426
+ );
427
+ }
428
+ lines.push(
429
+ ...markerRowLines(
430
+ "$",
431
+ planEstimateLine({
432
+ estimate: d.estimate,
433
+ hunterCount: d.hunterCount,
434
+ summarizer: d.summarizer,
435
+ ...(d.freeRoute === undefined ? {} : { freeRoute: d.freeRoute }),
436
+ }),
437
+ bold,
438
+ styles,
439
+ width,
440
+ ),
441
+ );
442
+ return lines;
443
+ }
444
+
445
+ // The free-route wording of the estimate, shared by the plan card and the result
446
+ // footer's estimate row so both print one verdict. A free route bills nothing,
447
+ // so the band is relabelled as token-derived instead of read as a cost.
448
+ export function freeRouteEstimateText(estimate: {
449
+ low: number;
450
+ high: number;
451
+ }): string {
452
+ const low = `$${estimate.low.toFixed(2)}`;
453
+ const high = `$${estimate.high.toFixed(2)}`;
454
+ return `free route (token-derived ${low} – ${high}, not billed)`;
455
+ }
456
+
457
+ // The estimate row's text, shared by both plan cards. The band is token-derived
458
+ // whatever the route; the free verdict changes only the claim made about it. A
459
+ // free route bills nothing, so a dollar figure would read as a cost, and the
460
+ // band is relabelled as token-derived instead. A mix keeps the band and names
461
+ // the free share. No free step (metered or subscription) is today's line,
462
+ // byte-identical. The band never reads $0 – $0 here: estimateCost clamps the
463
+ // hunter seats (report.ts), so a free route is "not billed", never a zero estimate.
464
+ export function planEstimateLine(input: {
465
+ estimate: { low: number; high: number };
466
+ hunterCount: number;
467
+ summarizer: boolean;
468
+ freeRoute?: FreeRouteBilling;
469
+ }): string {
470
+ const low = `$${input.estimate.low.toFixed(2)}`;
471
+ const high = `$${input.estimate.high.toFixed(2)}`;
472
+ // The mode is the prompt's too (ui/select.ts freeBillingMode): the card and
473
+ // the confirm read one verdict, so they cannot disagree about what is billed.
474
+ const billing = freeBillingMode(input.freeRoute);
475
+ if (billing === "free") {
476
+ return `estimate: ${freeRouteEstimateText(input.estimate)}`;
477
+ }
478
+ const line =
479
+ `estimate ${low} – ${high} (${input.hunterCount} hunter(s) + refuter ` +
480
+ `${input.summarizer ? "+ summarizer" : "+ summarizer disabled"})`;
481
+ return billing === "mixed" ? `${line} ${FREE_STEPS_NOTE}` : line;
482
+ }
483
+
484
+ // Both details views' rows, with a label column DERIVED from their own labels
485
+ // instead of inherited from row()'s fixed default.
486
+ //
487
+ // WHY: that default is 11 and "permissions" is 11 characters, so padEnd() gave
488
+ // it no gap and the live run printed
489
+ // `permissionssteps run with --permission-mode bypassPermissions…` — one word
490
+ // welded out of two columns. Deriving the width means the next label longer
491
+ // than any of today's cannot bring the collision back.
492
+ function detailRows(
493
+ pairs: readonly [string, string][],
494
+ styles: boolean,
495
+ width: number,
496
+ ): string[] {
497
+ const labelWidth = labelColumnWidth(pairs.map(([label]) => label));
498
+ return pairs.flatMap(([label, value]) =>
499
+ row(label, value, { styles, width, labelWidth }),
500
+ );
501
+ }
502
+
503
+ // NOT printed by default: everything the plan card demoted lands here, and
504
+ // the confirm menu's "Show details" option is the only thing that prints it.
505
+ // Exported ONLY for test/cli-plan.test.ts — a test is a real consumer, and
506
+ // these four renderers had zero coverage until WU4. Nothing else may import
507
+ // them:
508
+ // biome's unused-symbol rule does not flag exports, so an `export` for a
509
+ // hypothetical consumer is how dead code hides through a clean `bun run check`
510
+ // (which is exactly how this pair sat unread for two work units).
511
+ //
512
+ // `styles` ARRIVES AS A PARAMETER and so does the WIDTH (`ctx.width`, resolved
513
+ // once here): ui.ts's contract, and the only reason the returned lines can be
514
+ // asserted offline without a TTY.
515
+ export function planDetails(ctx: PlanContext, styles: boolean): string[] {
516
+ const width = ctx.width ?? terminalWidth();
517
+ const pairs: [string, string][] = [];
518
+ const push = (label: string, value: string): void => {
519
+ pairs.push([label, value]);
520
+ };
521
+ push("repo", ctx.repoRoot);
522
+ push("base", `${ctx.baseRef.ref} → ${ctx.baseSha} (${baseSourceNote(ctx)})`);
523
+ push("head", `${ctx.options.head} → ${ctx.headSha}`);
524
+ // BOTH endpoints, always. The base ref the user asked for and the commit the
525
+ // diff is actually computed from are different things whenever base has
526
+ // moved on, and a plan that printed only one of them would leave the range
527
+ // ambiguous in exactly the case that motivated the merge-base default. The
528
+ // card satisfies that with its own BASE + RANGE pair (short shas); this
529
+ // view adds the full shas and the sentence explaining the range.
530
+ push(
531
+ "diff from",
532
+ ctx.options.twoDot
533
+ ? `${ctx.baseSha} — --two-dot: the literal ${ctx.baseRef.ref}..` +
534
+ `${ctx.options.head} two-point range, so commits base gained since ` +
535
+ "the branch point appear REVERSED"
536
+ : `${ctx.diffFromSha} — merge base of ${ctx.baseRef.ref} and ` +
537
+ `${ctx.options.head}; only what this branch adds is reviewed`,
538
+ );
539
+ push("diff", ctx.diffPath);
540
+ push("agents dir", ctx.agentsDir);
541
+ if (ctx.routePlan) {
542
+ for (const step of ctx.routePlan.steps) {
543
+ const rawModel =
544
+ step.role === "hunter"
545
+ ? (ctx.options.model ??
546
+ ctx.spec.agents.find(
547
+ (a) =>
548
+ a.key === step.stepKey || `hunter-${a.key}` === step.stepKey,
549
+ )?.model ??
550
+ ctx.agentFiles.get(step.stepKey.replace(/^hunter-/, ""))?.model)
551
+ : step.role === "refuter"
552
+ ? (ctx.options.model ??
553
+ ctx.spec.agents.find((a) => a.role === "refuter")?.model ??
554
+ ctx.agentFiles.get(step.stepKey)?.model)
555
+ : undefined;
556
+ push(`route ${step.stepKey}`, formatStepRoute(step, rawModel));
557
+ }
558
+ }
559
+ if (ctx.configProvenance) {
560
+ push("config", configDetail(ctx.configProvenance, ctx.options));
561
+ }
562
+ push("run dir", ctx.runDir);
563
+ push("hop budget", String(ctx.options.hopBudget));
564
+ push("summarizer", summarizerRow(ctx.summary));
565
+ push("scout", scoutRow(ctx.options));
566
+ push(
567
+ "parity",
568
+ ctx.config.parity_trigger_paths.length === 0
569
+ ? "no parity_trigger_paths configured — the parity hunter never fires"
570
+ : ctx.parityFires
571
+ ? `fires (a changed path matches ${ctx.config.parity_trigger_paths.length} configured pattern(s))`
572
+ : "configured, but no changed path matches — it will not fire",
573
+ );
574
+ push(
575
+ "codegraph",
576
+ ctx.codegraphAvailable
577
+ ? "available (.codegraph found; codegraph_explore is live)"
578
+ : "NOT FOUND — the agents' codegraph_explore grant is inert, so this " +
579
+ "review runs on Read/Grep/Glob alone",
580
+ );
581
+ push("priors", `${ctx.config.suspicion_priors.length} suspicion prior(s)`);
582
+ push("estimate", ctx.estimate.basis);
583
+ push("permissions", PERMISSIONS_NOTE);
584
+ return [section("details", styles), ...detailRows(pairs, styles, width)];
585
+ }
586
+
587
+ // The plan card as LINES, printed by the shell. Returning them rather than
588
+ // logging them is what makes the composition — card, agent grid, endpoints,
589
+ // decision block — assertable in one offline expectation.
590
+ export function renderPlan(ctx: PlanContext, styles: boolean): string[] {
591
+ const width = ctx.width ?? terminalWidth();
592
+ const lines = [
593
+ ...box(
594
+ "crysk · review",
595
+ [
596
+ `${ctx.baseRef.ref}..${ctx.options.head}`,
597
+ `${shortPath(ctx.repoRoot)} · ${ctx.diffStat.files} files ` +
598
+ `+${ctx.diffStat.insertions} −${ctx.diffStat.deletions}`,
599
+ ],
600
+ { styles, width },
601
+ ),
602
+ "",
603
+ ];
604
+ let label = "AGENTS";
605
+ for (const agent of ctx.spec.agents) {
606
+ const fires =
607
+ agent.role === "refuter"
608
+ ? "per severe finding"
609
+ : agent.trigger === undefined
610
+ ? "always"
611
+ : ctx.parityFires
612
+ ? "triggered"
613
+ : "✗ will not fire";
614
+ lines.push(...row(label, agentRow(ctx, agent, fires), { styles, width }));
615
+ label = "";
616
+ }
617
+ lines.push(...row(label, summarizerRow(ctx.summary), { styles, width }));
618
+ lines.push(...row("", scoutRow(ctx.options), { styles, width }));
619
+ label = "";
620
+ lines.push(
621
+ "",
622
+ ...row(
623
+ "BASE",
624
+ `${ctx.baseRef.ref} → ${shortSha(ctx.baseSha)} (${baseSourceTag(ctx)})`,
625
+ { styles, width },
626
+ ),
627
+ // The second endpoint of the pair the details view explains: what the diff
628
+ // is actually computed from, which is the merge base unless --two-dot moved
629
+ // it back to the base tip.
630
+ ...row(
631
+ "RANGE",
632
+ `${shortSha(ctx.diffFromSha)} → ${shortSha(ctx.headSha)} ` +
633
+ (ctx.options.twoDot ? "(--two-dot, two-point range)" : "(merge base)"),
634
+ { styles, width },
635
+ ),
636
+ ...row(
637
+ "RUN",
638
+ `${path.basename(ctx.runDir)} · ` +
639
+ (ctx.codegraphAvailable ? "codegraph live" : "codegraph NOT FOUND") +
640
+ ` · hop budget ${ctx.options.hopBudget}` +
641
+ ` · ${ctx.config.suspicion_priors.length} suspicion prior(s)`,
642
+ { styles, width },
643
+ ),
644
+ ...configRow(ctx.configProvenance, ctx.options, styles, width),
645
+ ...decisionLines(
646
+ {
647
+ sizeGate: ctx.sizeGate,
648
+ droppedPaths: ctx.droppedPaths,
649
+ force: ctx.options.force,
650
+ estimate: ctx.estimate,
651
+ hunterCount: ctx.hunterCount,
652
+ summarizer: ctx.summary.enabled,
653
+ ...(ctx.freeRoute === undefined ? {} : { freeRoute: ctx.freeRoute }),
654
+ },
655
+ styles,
656
+ width,
657
+ ),
658
+ );
659
+ return lines;
660
+ }
661
+
662
+ export interface PrPlanContext {
663
+ options: CliOptions;
664
+ operatorRoot: string;
665
+ target: PrTarget;
666
+ worktreePath: string;
667
+ runDir: string;
668
+ diffStat: DiffStat;
669
+ agentsDir: string;
670
+ agentFiles: Map<string, ParsedAgent>;
671
+ spec: ReviewSpec;
672
+ config: LocalConfig;
673
+ summary: SummarySettings;
674
+ estimate: ReturnType<typeof estimateCost>;
675
+ hunterCount: number;
676
+ // Same contract as PlanContext: the verdict is decided by the shell (and
677
+ // in PR mode enforced before the run dir even exists), printed here.
678
+ sizeGate: SizeGateVerdict;
679
+ sizeGateNote?: string;
680
+ droppedPaths: string[];
681
+ // C5 O-7, same contract as PlanContext's.
682
+ configProvenance?: ConfigProvenance;
683
+ // D2 PR3: Optional resolved route plan for model routing display
684
+ routePlan?: ResolvedRoutePlan;
685
+ // Free verdicts of the admitted route plan, read off the admission that already
686
+ // decided them. Absent means unknown, and the estimate line keeps its band.
687
+ freeRoute?: FreeRouteBilling;
688
+ // Set when this plan follows an interactive "Review anyway" at the
689
+ // size-gate menu. Distinct from options.force so the decision block can
690
+ // say "confirmed" rather than lie that --force was passed.
691
+ sizeGateConfirmed?: boolean;
692
+ // Present only once the fetch has happened: the canonical range and the
693
+ // on-disk diff. A dry-run plan prints GitHub's own counters instead.
694
+ resolved?: {
695
+ baseSha: string;
696
+ diffFromSha: string;
697
+ diffPath: string;
698
+ parityFires: boolean;
699
+ };
700
+ // Same contract, same reason as PlanContext.width.
701
+ width?: number;
702
+ // Item 7: queued verify steps shown as their own cost-band term (O-5a).
703
+ verificationSteps?: number;
704
+ rereview?: {
705
+ case: string;
706
+ lastHead: string | null;
707
+ discoveryRestricted: boolean;
708
+ skipDiscovery: boolean;
709
+ };
710
+ }
711
+
712
+ function prBaseSourceNote(target: PrTarget): string {
713
+ return target.baseSource === "merge-commit-parent"
714
+ ? "first parent of the merge commit — base as it was when the PR landed"
715
+ : `tip of ${target.baseRefName} as recorded on the PR`;
716
+ }
717
+
718
+ // A merged PR's baseRef is a `<sha>^1` EXPRESSION, not a branch name, so the
719
+ // card would otherwise carry a 40-char sha with a suffix. Shortened only for
720
+ // display, and only when it really is a full commit id — a branch name that
721
+ // happens to be long is left whole, because truncating a ref makes it
722
+ // unusable. The details view and pipeline.json both keep the full form.
723
+ function shortRev(rev: string): string {
724
+ const bare = rev.replace(/\^\d*$/, "");
725
+ return isFullCommitId(bare) ? shortSha(bare) + rev.slice(bare.length) : rev;
726
+ }
727
+
728
+ // The same fact in one token, for the card; the sentence above is the
729
+ // details view's job.
730
+ function prBaseSourceTag(target: PrTarget): string {
731
+ return target.baseSource === "merge-commit-parent"
732
+ ? "merge commit parent"
733
+ : "PR base tip";
734
+ }
735
+
736
+ // Pre-fetch the parity trigger cannot be evaluated (there is no diff yet).
737
+ // When triggers are configured the parity hunter MIGHT fire, so it counts:
738
+ // both recorded cost overruns were under-estimates, and a band that errs
739
+ // high costs a second of hesitation while one that errs low costs money.
740
+ export function dryRunHunterCount(
741
+ spec: ReviewSpec,
742
+ config: LocalConfig,
743
+ ): number {
744
+ return spec.agents.filter(
745
+ (a) =>
746
+ a.role === "hunter" &&
747
+ (a.trigger === undefined || config.parity_trigger_paths.length > 0),
748
+ ).length;
749
+ }
750
+
751
+ // Predicted, not decided: the ensure step runs only after the confirm gate,
752
+ // so the plan can promise a create but must leave reuse-vs-recreate to the
753
+ // HEAD and cleanliness checks at run time.
754
+ function worktreePlanNote(worktreePath: string): string {
755
+ return existsSync(worktreePath)
756
+ ? "exists — reuse/recreate decided at run time"
757
+ : "will create (git worktree add --detach)";
758
+ }
759
+
760
+ function codegraphPlanNote(worktreePath: string): string {
761
+ if (existsSync(path.join(worktreePath, ".codegraph"))) {
762
+ return (
763
+ "available (.codegraph found in the worktree; codegraph_explore " +
764
+ "is live)"
765
+ );
766
+ }
767
+ return Bun.which("codegraph") === null
768
+ ? "codegraph CLI not found — hunters run on Read/Grep/Glob alone"
769
+ : "will `codegraph init` in the worktree (~10s measured)";
770
+ }
771
+
772
+ // Same three states as codegraphPlanNote, in card width.
773
+ function codegraphPlanTag(worktreePath: string): string {
774
+ if (existsSync(path.join(worktreePath, ".codegraph"))) {
775
+ return "codegraph live";
776
+ }
777
+ return Bun.which("codegraph") === null
778
+ ? "codegraph NOT FOUND"
779
+ : "codegraph init ~10s";
780
+ }
781
+
782
+ function prWorktreePlanTag(worktreePath: string): string {
783
+ return existsSync(worktreePath)
784
+ ? "worktree exists"
785
+ : "worktree will be created";
786
+ }
787
+
788
+ // PR mode's half of planDetails — same contract, same test-only export:
789
+ // printed only when the confirm menu's "Show details" option asks for it.
790
+ export function prPlanDetails(ctx: PrPlanContext, styles: boolean): string[] {
791
+ const width = ctx.width ?? terminalWidth();
792
+ const pairs: [string, string][] = [];
793
+ const push = (label: string, value: string): void => {
794
+ pairs.push([label, value]);
795
+ };
796
+ push("repo", `${ctx.operatorRoot} (operator checkout; gh and git run here)`);
797
+ push("head", `${ctx.target.headSha} (the PR's head commit)`);
798
+ // BOTH endpoints, always — the rule local mode's details view spells out.
799
+ // The card shows the pair as short shas; here they are whole, with the
800
+ // sentence that says which is which.
801
+ push(
802
+ "base",
803
+ ctx.resolved
804
+ ? `${ctx.target.baseRef} → ${ctx.resolved.baseSha} ` +
805
+ `(${prBaseSourceNote(ctx.target)})`
806
+ : `${ctx.target.baseRef} (${prBaseSourceNote(ctx.target)}; resolved ` +
807
+ "after fetch)",
808
+ );
809
+ if (ctx.resolved) {
810
+ push(
811
+ "diff from",
812
+ `${ctx.resolved.diffFromSha} — merge base of base and the PR head; ` +
813
+ "only what the PR adds is reviewed",
814
+ );
815
+ }
816
+ push(
817
+ "diff",
818
+ ctx.resolved
819
+ ? ctx.resolved.diffPath
820
+ : "band from gh; exact numstat after fetch",
821
+ );
822
+ push(
823
+ "worktree",
824
+ `${ctx.worktreePath} — ${worktreePlanNote(ctx.worktreePath)}`,
825
+ );
826
+ push("agents dir", ctx.agentsDir);
827
+ if (ctx.routePlan) {
828
+ for (const step of ctx.routePlan.steps) {
829
+ const rawModel =
830
+ step.role === "hunter"
831
+ ? (ctx.options.model ??
832
+ ctx.spec.agents.find(
833
+ (a) =>
834
+ a.key === step.stepKey || `hunter-${a.key}` === step.stepKey,
835
+ )?.model ??
836
+ ctx.agentFiles.get(step.stepKey.replace(/^hunter-/, ""))?.model)
837
+ : step.role === "refuter"
838
+ ? (ctx.options.model ??
839
+ ctx.spec.agents.find((a) => a.role === "refuter")?.model ??
840
+ ctx.agentFiles.get(step.stepKey)?.model)
841
+ : undefined;
842
+ push(`route ${step.stepKey}`, formatStepRoute(step, rawModel));
843
+ }
844
+ }
845
+ if (ctx.configProvenance) {
846
+ // The repo path here is the OPERATOR checkout's, never the worktree's
847
+ // (O-8) — printed so that fact is visible rather than asserted.
848
+ push("config", configDetail(ctx.configProvenance, ctx.options));
849
+ }
850
+ push("run dir", ctx.runDir);
851
+ push("hop budget", String(ctx.options.hopBudget));
852
+ push("summarizer", summarizerRow(ctx.summary));
853
+ push("scout", scoutRow(ctx.options));
854
+ if (ctx.rereview) {
855
+ const last =
856
+ ctx.rereview.lastHead === null
857
+ ? "none"
858
+ : ctx.rereview.lastHead.slice(0, 8);
859
+ push(
860
+ "re-review",
861
+ `case ${ctx.rereview.case} · L=${last}` +
862
+ (ctx.rereview.skipDiscovery
863
+ ? " · discovery skipped (empty delta)"
864
+ : ctx.rereview.discoveryRestricted
865
+ ? " · restricted L..H"
866
+ : " · full B..H"),
867
+ );
868
+ if (ctx.rereview.case === "D") {
869
+ push(
870
+ "D4",
871
+ "last reviewed head is not an ancestor of this head — full B..H",
872
+ );
873
+ }
874
+ }
875
+ if (ctx.verificationSteps !== undefined && ctx.verificationSteps > 0) {
876
+ push(
877
+ "verify",
878
+ `${ctx.verificationSteps} verification step(s) (capped; not bypassed by --yes)`,
879
+ );
880
+ }
881
+ if (ctx.options.post) {
882
+ push(
883
+ "post",
884
+ "a marked PR comment will be created, or updated in place if one " +
885
+ "exists (idempotent — one comment per PR, found by its marker)",
886
+ );
887
+ }
888
+ push(
889
+ "parity",
890
+ ctx.config.parity_trigger_paths.length === 0
891
+ ? "no parity_trigger_paths configured — the parity hunter never fires"
892
+ : ctx.resolved === undefined
893
+ ? `configured (${ctx.config.parity_trigger_paths.length} ` +
894
+ "pattern(s)); whether a changed path matches is decided after fetch"
895
+ : ctx.resolved.parityFires
896
+ ? `fires (a changed path matches ${ctx.config.parity_trigger_paths.length} configured pattern(s))`
897
+ : "configured, but no changed path matches — it will not fire",
898
+ );
899
+ push("codegraph", codegraphPlanNote(ctx.worktreePath));
900
+ push("priors", `${ctx.config.suspicion_priors.length} suspicion prior(s)`);
901
+ push("estimate", ctx.estimate.basis);
902
+ push("permissions", PERMISSIONS_NOTE);
903
+ return [section("details", styles), ...detailRows(pairs, styles, width)];
904
+ }
905
+
906
+ export function renderPrPlan(ctx: PrPlanContext, styles: boolean): string[] {
907
+ const width = ctx.width ?? terminalWidth();
908
+ const lines = [
909
+ ...box(
910
+ `crysk · PR #${ctx.target.number}`,
911
+ [
912
+ ctx.target.title,
913
+ `${ctx.target.state} · base ${ctx.target.baseRefName} · ` +
914
+ `${ctx.diffStat.files} files +${ctx.diffStat.insertions} ` +
915
+ `−${ctx.diffStat.deletions}` +
916
+ (ctx.resolved ? "" : " (gh counters)"),
917
+ ],
918
+ { styles, width },
919
+ ),
920
+ "",
921
+ ];
922
+ let label = "AGENTS";
923
+ for (const agent of ctx.spec.agents) {
924
+ const fires =
925
+ agent.role === "refuter"
926
+ ? "per severe finding"
927
+ : agent.trigger === undefined
928
+ ? "always"
929
+ : ctx.resolved === undefined
930
+ ? "decided by the diff after fetch"
931
+ : ctx.resolved.parityFires
932
+ ? "triggered"
933
+ : "✗ will not fire";
934
+ lines.push(...row(label, agentRow(ctx, agent, fires), { styles, width }));
935
+ label = "";
936
+ }
937
+ lines.push(...row(label, summarizerRow(ctx.summary), { styles, width }));
938
+ lines.push(...row("", scoutRow(ctx.options), { styles, width }));
939
+ if (ctx.rereview) {
940
+ lines.push(
941
+ ...row(
942
+ "",
943
+ `re-review case ${ctx.rereview.case}` +
944
+ (ctx.rereview.skipDiscovery
945
+ ? " discovery skipped"
946
+ : ctx.rereview.discoveryRestricted
947
+ ? " restricted"
948
+ : " full range"),
949
+ { styles, width },
950
+ ),
951
+ );
952
+ if (ctx.rereview.case === "D") {
953
+ lines.push(
954
+ ...row(
955
+ "",
956
+ "⚠️ last reviewed head is not an ancestor — reviewing full B..H",
957
+ { styles, width },
958
+ ),
959
+ );
960
+ }
961
+ }
962
+ if (ctx.verificationSteps !== undefined && ctx.verificationSteps > 0) {
963
+ lines.push(
964
+ ...row("", `verify ${ctx.verificationSteps} step(s)`, {
965
+ styles,
966
+ width,
967
+ }),
968
+ );
969
+ }
970
+ label = "";
971
+ lines.push(
972
+ "",
973
+ ...row(
974
+ "BASE",
975
+ ctx.resolved
976
+ ? `${shortRev(ctx.target.baseRef)} → ` +
977
+ `${shortSha(ctx.resolved.baseSha)} ` +
978
+ `(${prBaseSourceTag(ctx.target)})`
979
+ : `${shortRev(ctx.target.baseRef)} (${prBaseSourceTag(ctx.target)}; ` +
980
+ "resolved after fetch)",
981
+ { styles, width },
982
+ ),
983
+ // The other endpoint. Pre-fetch there is no merge base yet, so the card
984
+ // says so rather than showing the head alone — a single endpoint is the
985
+ // ambiguity the details view's rule exists to prevent.
986
+ ...row(
987
+ "RANGE",
988
+ ctx.resolved
989
+ ? `${shortSha(ctx.resolved.diffFromSha)} → ` +
990
+ `${shortSha(ctx.target.headSha)} (merge base)`
991
+ : // A bare "?" for the unresolved endpoint was honest and read as a
992
+ // bug. Name the operation instead: the reader learns WHAT will be
993
+ // reviewed (only what the PR adds) without being shown a
994
+ // placeholder where a sha belongs.
995
+ `merge base of ${shortRev(ctx.target.baseRef)} → ` +
996
+ `${shortSha(ctx.target.headSha)} (exact sha after fetch)`,
997
+ { styles, width },
998
+ ),
999
+ ...row(
1000
+ "RUN",
1001
+ `${path.basename(ctx.runDir)} · ` +
1002
+ `${prWorktreePlanTag(ctx.worktreePath)} · ` +
1003
+ `${codegraphPlanTag(ctx.worktreePath)} · ` +
1004
+ `hop budget ${ctx.options.hopBudget} · ` +
1005
+ `${ctx.config.suspicion_priors.length} suspicion prior(s)`,
1006
+ { styles, width },
1007
+ ),
1008
+ ...configRow(ctx.configProvenance, ctx.options, styles, width),
1009
+ );
1010
+ if (ctx.options.post) {
1011
+ lines.push(
1012
+ ...row(
1013
+ "POST",
1014
+ "✓ one marked PR comment — created, or updated in place (idempotent)",
1015
+ { styles, width },
1016
+ ),
1017
+ );
1018
+ }
1019
+ lines.push(
1020
+ ...decisionLines(
1021
+ {
1022
+ sizeGate: ctx.sizeGate,
1023
+ ...(ctx.sizeGateNote === undefined
1024
+ ? {}
1025
+ : { sizeGateNote: ctx.sizeGateNote }),
1026
+ droppedPaths: ctx.droppedPaths,
1027
+ force: ctx.options.force,
1028
+ ...(ctx.sizeGateConfirmed === true ? { sizeGateConfirmed: true } : {}),
1029
+ estimate: ctx.estimate,
1030
+ hunterCount: ctx.hunterCount,
1031
+ summarizer: ctx.summary.enabled,
1032
+ ...(ctx.freeRoute === undefined ? {} : { freeRoute: ctx.freeRoute }),
1033
+ },
1034
+ styles,
1035
+ width,
1036
+ ),
1037
+ );
1038
+ return lines;
1039
+ }