crysk 0.4.0 → 0.5.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 (98) hide show
  1. package/README.md +26 -17
  2. package/config/models/anthropic.json +1 -1
  3. package/dist/SKILL-k4k0zn1w.md +143 -0
  4. package/dist/SKILL-vhb4c3vv.md +553 -0
  5. package/dist/SKILL-xpf6kmdw.md +74 -0
  6. package/dist/ci-admission-0ken6ehx.md +128 -0
  7. package/dist/cli.js +3056 -1623
  8. package/dist/index.js +1744 -938
  9. package/dist/opencode-ci-ac5zksdn.md +106 -0
  10. package/dist/workflow-4pkyck01.yml +160 -0
  11. package/package.json +1 -1
  12. package/prompts/default/PROVENANCE.md +1 -0
  13. package/skills/crysk/SKILL.md +16 -16
  14. package/skills/crysk-ci-setup/SKILL.md +41 -38
  15. package/skills/crysk-ci-setup/assets/workflow.yml +31 -22
  16. package/skills/crysk-ci-setup/references/ci-admission.md +1 -1
  17. package/skills/crysk-ci-setup/references/opencode-ci.md +53 -88
  18. package/skills/crysk-loop/SKILL.md +1 -1
  19. package/src/asset-manifest.ts +0 -4
  20. package/src/assets.ts +1 -1
  21. package/src/ci/admission-ledger.ts +4 -0
  22. package/src/ci/classify-error.ts +21 -24
  23. package/src/ci/cli-record.ts +53 -1
  24. package/src/ci/crysk-secrets.ts +409 -0
  25. package/src/ci/force-comment.ts +14 -1
  26. package/src/ci/gates.ts +86 -57
  27. package/src/ci/outcome.ts +421 -330
  28. package/src/ci/platform-config.ts +2 -2
  29. package/src/ci/platform-estimate.ts +111 -0
  30. package/src/ci/platform-report.ts +274 -41
  31. package/src/ci/platform-trace.ts +581 -0
  32. package/src/ci/platform.ts +58 -12
  33. package/src/ci/publish.ts +19 -6
  34. package/src/ci/reporter.ts +14 -4
  35. package/src/ci/review-levels.ts +8 -7
  36. package/src/ci/run.ts +88 -0
  37. package/src/ci/setup.ts +485 -118
  38. package/src/ci/trace-bundle.ts +1486 -0
  39. package/src/ci/trace-transcripts.ts +480 -0
  40. package/src/ci/trigger.ts +176 -33
  41. package/src/cli.ts +11 -3
  42. package/src/commands/ci-setup-questions.ts +3 -3
  43. package/src/commands/ci-setup.ts +152 -6
  44. package/src/commands/config.ts +3 -0
  45. package/src/commands/doctor.ts +15 -6
  46. package/src/config/config.ts +16 -3
  47. package/src/diversity/clustering.ts +0 -1
  48. package/src/diversity/identity.ts +4 -5
  49. package/src/diversity/pipeline-integration.ts +1 -9
  50. package/src/doctor.ts +3 -3
  51. package/src/execution/attempt-evidence.ts +10 -5
  52. package/src/execution/claude-session-trace.ts +480 -0
  53. package/src/execution/contracts.ts +21 -4
  54. package/src/execution/harness.ts +105 -8
  55. package/src/execution/model-fallback.ts +239 -0
  56. package/src/execution/usage-normalized.ts +6 -4
  57. package/src/home-preflight.ts +1 -1
  58. package/src/index.ts +1 -1
  59. package/src/model/catalog.ts +13 -37
  60. package/src/model/free-discovery.ts +117 -8
  61. package/src/model/model-name.ts +404 -0
  62. package/src/model/provider-capabilities.ts +22 -7
  63. package/src/model/routing.ts +346 -467
  64. package/src/pr/admission.ts +18 -0
  65. package/src/pr/ci-admission-gate.ts +2 -0
  66. package/src/pr/discovery.ts +18 -0
  67. package/src/pr/plan.ts +55 -5
  68. package/src/pr/preflight.ts +1 -1
  69. package/src/pr/publish-outcome.ts +1 -1
  70. package/src/pr/review-pr.ts +26 -1
  71. package/src/pr/target.ts +63 -11
  72. package/src/production-runtime.ts +760 -331
  73. package/src/review/pipeline.ts +277 -101
  74. package/src/review/preflight.ts +201 -294
  75. package/src/review/report.ts +30 -26
  76. package/src/review/review.ts +20 -3
  77. package/src/review/route-preflight.ts +79 -11
  78. package/src/review/run.ts +44 -6
  79. package/src/review/scout.ts +1 -1
  80. package/src/review/spec.ts +3 -3
  81. package/src/review/step-runner.ts +70 -1
  82. package/src/runner-authority.ts +127 -9
  83. package/src/security/binding-policy.ts +1 -2
  84. package/src/security/claude-credential.ts +355 -0
  85. package/src/security/credential-broker.ts +56 -40
  86. package/src/security/evidence-redaction.ts +179 -4
  87. package/src/security/opencode-secret-manifest.ts +114 -0
  88. package/src/security/redact.ts +45 -0
  89. package/src/system-tools.ts +48 -21
  90. package/src/transport-registry.ts +12 -2
  91. package/src/transports/claude-code-cli.ts +21 -2
  92. package/src/transports/opencode-sdk.ts +11 -9
  93. package/src/transports/opencode-server.ts +7 -10
  94. package/src/ui/config-edit.ts +9 -20
  95. package/src/ui/config.ts +32 -27
  96. package/src/ui/plan.ts +84 -50
  97. package/src/updater.ts +10 -7
  98. package/prompts/default/deep-review-lifecycle.md +0 -362
@@ -48,6 +48,7 @@ import {
48
48
  import { publishFinalCommitStatus } from "#pr/status";
49
49
  import { log } from "#ui/primitives";
50
50
  import { canonicalStatusText, STATUS_CONTEXT } from "../brand";
51
+ import { CredentialRefusalError } from "../security/claude-credential";
51
52
 
52
53
  // ROADMAP Pillar 3 (GitHub Actions CI). The mechanical glue behind a gate
53
54
  // skip in CI mode: every DECISION (what to say, which marker, what the
@@ -180,6 +181,23 @@ export async function settleCiGateSkip(
180
181
  await settleCiAdmissionLedger(state, "gate-skipped", reason, options);
181
182
  }
182
183
 
184
+ // R003 (#494): a credential refusal at admission (CredentialRefusalError: no Claude
185
+ // credential, or an OpenCode route with no auth record) stops a CI run after the
186
+ // reservation and before any binding or provider call (the OpenCode refusal follows
187
+ // only the token-free free-model probe), so it spent nothing:
188
+ // its row settles as gate-skipped, like the budget gate it follows, with the
189
+ // refusal's own reason. Any other error is left for teardown, which settles it
190
+ // `failed`. The caller rethrows the error unchanged. The name predates the OpenCode
191
+ // refusal and is kept: an architecture test pins its call site.
192
+ export async function settleClaudeCredentialRefusal(
193
+ state: CiAdmissionLedgerState | null,
194
+ error: unknown,
195
+ options?: { spawnFn?: typeof Bun.spawn },
196
+ ): Promise<void> {
197
+ if (!(error instanceof CredentialRefusalError)) return;
198
+ await settleCiGateSkip(state, error.ledgerReason, options);
199
+ }
200
+
183
201
  export async function reserveCiAdmissionLedger(input: {
184
202
  operatorRoot: string;
185
203
  prNumber: number;
@@ -352,6 +352,7 @@ export async function evaluateCiAdmissionGate(input: {
352
352
  verdict: admissionVerdict,
353
353
  admission: admissionContext,
354
354
  ciMode: input.ciMode,
355
+ platformConnected: process.env.CRYSK_PLATFORM_CONNECTED === "true",
355
356
  });
356
357
  const exitCode = await publishCiSkip({
357
358
  operatorRoot,
@@ -394,6 +395,7 @@ export async function evaluateCiAdmissionGate(input: {
394
395
  verdict: admissionVerdict,
395
396
  admission: admissionContext,
396
397
  ciMode: input.ciMode,
398
+ platformConnected: process.env.CRYSK_PLATFORM_CONNECTED === "true",
397
399
  });
398
400
  const exitCode = await publishCiSkip({
399
401
  operatorRoot,
@@ -138,6 +138,11 @@ export interface PrDiscoveryResult {
138
138
  }
139
139
  | undefined;
140
140
  diffStat: DiffStat;
141
+ // The whole PR range's stat, filtered by the same rules as `diffStat`
142
+ // (merge-base..head, no path restriction). Equal to `diffStat` when discovery
143
+ // read the whole range; the plan divides the two to price a narrowed run
144
+ // (cryskai/platform#12).
145
+ prDiffStat: DiffStat;
141
146
  sizeGate: SizeGateVerdict;
142
147
  }
143
148
 
@@ -426,6 +431,18 @@ export async function resolvePrDiscovery(params: {
426
431
  }));
427
432
  }
428
433
 
434
+ const prDiffStat =
435
+ discoveryIsPrRange && !skipDiscovery
436
+ ? diffStat
437
+ : (
438
+ await computeDiffStatAndSizeGate({
439
+ runGit: git.runGit,
440
+ range: `${diffFromSha}..${headSha}`,
441
+ pathArgs: [],
442
+ gateConfig,
443
+ })
444
+ ).diffStat;
445
+
429
446
  return {
430
447
  prepared,
431
448
  skipDiscovery,
@@ -439,6 +456,7 @@ export async function resolvePrDiscovery(params: {
439
456
  adjudicationQueue: adjudicationSubjects,
440
457
  phaseB,
441
458
  diffStat,
459
+ prDiffStat,
442
460
  sizeGate,
443
461
  };
444
462
  }
package/src/pr/plan.ts CHANGED
@@ -23,15 +23,17 @@
23
23
  import { recordPendingCreatedAt, recordReviewing } from "#ci/cli-record";
24
24
  import { planCiBudgetSkip } from "#ci/gates";
25
25
  import { actionsRunUrl } from "#ci/outcome";
26
+ import { readPlatformEstimate, runCostEstimate } from "#ci/platform-estimate";
26
27
  import {
27
28
  countFreeRouteSteps,
28
29
  type FreeRouteBilling,
29
30
  } from "#model/free-discovery";
30
- import type { ResolvedRoutePlan } from "#model/routing";
31
+ import { planRoutes, type ResolvedRoutePlan } from "#model/routing";
31
32
  import {
32
33
  type CiAdmissionLedgerState,
33
34
  publishCiSkip,
34
35
  settleCiGateSkip,
36
+ settleClaudeCredentialRefusal,
35
37
  } from "#pr/admission";
36
38
  import { ghRepoWebUrl } from "#pr/pr";
37
39
  import {
@@ -71,6 +73,7 @@ import {
71
73
  type RunnerAuthorityResolution,
72
74
  resolveRunnerAuthority,
73
75
  } from "../runner-authority";
76
+ import type { RunClaudeCredential } from "../security/claude-credential";
74
77
 
75
78
  export type PrPlanAndConfirmResult =
76
79
  | { exitCode: number }
@@ -110,6 +113,8 @@ export async function resolvePrPlanAndConfirm(params: {
110
113
  diffFromSha: string;
111
114
  diffPath: string;
112
115
  diffStat: DiffStat;
116
+ // The whole PR range's stat under the same filters (discovery's prDiffStat).
117
+ prDiffStat: DiffStat;
113
118
  droppedPaths: string[];
114
119
  sizeGate: SizeGateVerdict;
115
120
  sizeGateConfirmed: boolean;
@@ -128,9 +133,13 @@ export async function resolvePrPlanAndConfirm(params: {
128
133
  // run, pr-hero/local otherwise (resolveCiPosture). Passed down, never re-derived.
129
134
  statusContext: CommitStatusContext;
130
135
  ciBudgetCeiling: { budgetUsd: number | undefined };
136
+ // S5: the run's Claude credential, chosen once at run start (reviewPr).
137
+ claudeRun: RunClaudeCredential;
131
138
  ciAdmissionLedger: CiAdmissionLedgerState | null;
132
139
  skipDiscovery: boolean;
133
140
  hunterCount: number;
141
+ // Hunters a full review of the whole PR runs (fullReviewHunterCount).
142
+ fullHunterCount: number;
134
143
  parityFires: boolean;
135
144
  verifyQueue: ReturnType<typeof buildPhaseBQueue>["queued"];
136
145
  prepared: PreparedDiscovery;
@@ -140,7 +149,18 @@ export async function resolvePrPlanAndConfirm(params: {
140
149
  params.verifyQueue.length,
141
150
  maxVerificationSteps,
142
151
  );
143
- const estimate = estimateCost(
152
+ // cryskai/platform#12: in a platform run the platform's estimate, priced from
153
+ // the setup's models and its recent reviews, replaces the band, which prices
154
+ // every model as Claude. The platform prices the whole pull request, so a run
155
+ // that covers less of it (a re-review whose discovery reads only the commits
156
+ // or paths since the last review, or one that hunts nothing new) scales it by
157
+ // the share of a full review it does, which the band measures
158
+ // (runCostEstimate). Without a platform estimate (standalone, or nothing
159
+ // priceable) the band decides.
160
+ const platformEstimate = params.isCi
161
+ ? readPlatformEstimate(process.env)
162
+ : undefined;
163
+ const band = estimateCost(
144
164
  params.diffStat,
145
165
  params.hunterCount,
146
166
  params.summary.enabled && !params.skipDiscovery,
@@ -148,6 +168,23 @@ export async function resolvePrPlanAndConfirm(params: {
148
168
  queuedVerification,
149
169
  !params.skipDiscovery,
150
170
  );
171
+ // discoveryPaths is null only when the hunters read the full PR range.
172
+ const narrowed =
173
+ params.skipDiscovery || params.prepared.discoveryPaths !== null;
174
+ const estimate = runCostEstimate(
175
+ platformEstimate,
176
+ band,
177
+ narrowed && platformEstimate !== undefined
178
+ ? estimateCost(
179
+ params.prDiffStat,
180
+ params.fullHunterCount,
181
+ params.summary.enabled,
182
+ params.options.scout,
183
+ queuedVerification,
184
+ true,
185
+ )
186
+ : undefined,
187
+ );
151
188
  // 7b(CI) — the budget gate, immediately after the estimate it reads and
152
189
  // BEFORE the plan card/confirm/"committed to spending" commit-status
153
190
  // block below: spec 3.1 ("Review MUST halt before agent spawning") is
@@ -182,6 +219,7 @@ export async function resolvePrPlanAndConfirm(params: {
182
219
  prNumber: params.prNumber,
183
220
  force: params.options.force,
184
221
  ciMode: params.ciMode,
222
+ platformConnected: process.env.CRYSK_PLATFORM_CONNECTED === "true",
185
223
  });
186
224
  if (budgetPlan !== null) {
187
225
  await settleCiGateSkip(
@@ -204,12 +242,12 @@ export async function resolvePrPlanAndConfirm(params: {
204
242
  }
205
243
  }
206
244
  const productionRoute = await resolvePipelineRoute({
207
- routingConfigured: params.config.routing !== undefined,
245
+ modelsConfigured: params.config.models !== undefined,
208
246
  workspaceRoot: params.worktreePath,
209
247
  spec: params.spec,
210
248
  options: params.options,
211
249
  agentFiles: params.agentFiles,
212
- routingConfig: params.config.routing,
250
+ models: params.config.models,
213
251
  summary: params.summary,
214
252
  summarizerEnabled: params.summary.enabled && !params.skipDiscovery,
215
253
  scoutEnabled: params.options.scout && !params.skipDiscovery,
@@ -218,6 +256,10 @@ export async function resolvePrPlanAndConfirm(params: {
218
256
  // re-review that hunts nothing new.
219
257
  materialityEnabled:
220
258
  resolveMaterialityGate(params.config) && !params.skipDiscovery,
259
+ claudeRun: params.claudeRun,
260
+ }).catch(async (error: unknown) => {
261
+ await settleClaudeCredentialRefusal(params.ciAdmissionLedger, error);
262
+ throw error;
221
263
  });
222
264
  const routePlan = productionRoute?.routePlan;
223
265
  const productionAdmission = productionRoute?.productionAdmission;
@@ -227,11 +269,19 @@ export async function resolvePrPlanAndConfirm(params: {
227
269
  routePlan === undefined || productionAdmission === undefined
228
270
  ? undefined
229
271
  : await countFreeRouteSteps({
230
- steps: routePlan.steps,
272
+ steps: planRoutes(routePlan),
231
273
  probe: productionAdmission.freeModelProbe,
274
+ // The CRYSK_OPENCODE_* names admission bound each route's kind with,
275
+ // so the card counts free exactly the routes admission probed (U3).
276
+ openCodeSecretNames:
277
+ productionAdmission.authorityOptions.openCodeSecretNames,
232
278
  });
233
279
  const runnerAuthority = await resolveRunnerAuthority({
234
280
  workspaceRoot: params.worktreePath,
281
+ env: params.claudeRun.env,
282
+ ...(params.claudeRun.kind === undefined
283
+ ? {}
284
+ : { claudeCredential: params.claudeRun.kind }),
235
285
  });
236
286
  await enforceCapabilityGate({
237
287
  routePlan,
@@ -828,7 +828,7 @@ export function settleRequestForCancellation(
828
828
  lock: HeldCommitStatusLock | null,
829
829
  ): { operatorRoot: string; sha: string; request: CommitStatusRequest } | null {
830
830
  if (lock === null) return null;
831
- // WHY PRH-CANCELLED and not "review did not finish": a signal is a cancel, and the
831
+ // WHY CRYSK-CANCELLED and not "review did not finish": a signal is a cancel, and the
832
832
  // action's cancel-settle step writes the same text when this settle does not land
833
833
  // first (src/ci/publish.ts runCancelSettle). Either writer leaves one coded status.
834
834
  return {
@@ -339,7 +339,7 @@ export async function publishRunOutcome(
339
339
  findings: doc.findings,
340
340
  costUsdEst: result.usage.cost_usd_est,
341
341
  wallMs,
342
- model: envelopeModel(input.options, input.agentFiles),
342
+ model: envelopeModel(input.options, input.agentFiles, result.routePlan),
343
343
  webUrl,
344
344
  delta: posted?.delta,
345
345
  runDir: input.runDir,
@@ -22,6 +22,7 @@ import path from "node:path";
22
22
  import {
23
23
  cliHeadField,
24
24
  hunterFailureRecords,
25
+ recordRunDir,
25
26
  writeCliRecord,
26
27
  } from "#ci/cli-record";
27
28
  import { planCiExcludedSkip, planCiSizeSkip } from "#ci/gates";
@@ -100,6 +101,7 @@ import {
100
101
  pipelineSummarizerInput,
101
102
  } from "#review/route-preflight";
102
103
  import {
104
+ fullReviewHunterCount,
103
105
  prepareRunnerForRoute,
104
106
  resolveParityFires,
105
107
  validateGotchas,
@@ -121,6 +123,7 @@ import { acquirePidLock } from "../home";
121
123
  import { worktreeLockPath } from "../home-preflight";
122
124
  import { readLocalIgnoreRules } from "../ignore-read";
123
125
  import type { ProductionRuntime } from "../production-runtime";
126
+ import { resolveRunClaudeCredential } from "../security/claude-credential";
124
127
  import { writeGateRecord } from "./gate-record";
125
128
 
126
129
  // The CLI's record for a pipeline whose every hunter failed (cli.json,
@@ -142,7 +145,7 @@ export function recordPipelineOutcome(
142
145
  ): void {
143
146
  if (result?.sessionFailed !== true) return;
144
147
  // WHY the causes ride on the record: the publisher names the provider and the model
145
- // when every hunter failed on the provider's side (PRH-MODEL-UNAVAILABLE). A run with
148
+ // when every hunter failed on the provider's side (CRYSK-MODEL-UNAVAILABLE). A run with
146
149
  // no failed hunter list keeps the record as it was before the field existed.
147
150
  const failures = result.hunterFailures ?? [];
148
151
  writeCliRecord(
@@ -279,6 +282,13 @@ export async function reviewPr(
279
282
  const step1 = await resolvePrRunOptions(options, prArg);
280
283
  options = step1.options;
281
284
  const { operatorRoot, prNumber, home, isCi, loaded, config, summary } = step1;
285
+ // S5: the Claude credential this run uses, chosen once, here, from
286
+ // `credentials.claude` and what is set. The CI ceiling, the admission, every
287
+ // runner and binding, and the child read its env, which holds that one
288
+ // credential and no other.
289
+ const claudeRun = resolveRunClaudeCredential({
290
+ credentials: config.credentials,
291
+ });
282
292
  // S4 + T3 S7: the run's one posture. Every gate, skip, status, comment and
283
293
  // summary below takes these values; nothing re-resolves them. Both key on the
284
294
  // explicit --ci flag, never on `isCi` (which also folds in the CI/GITHUB_ACTIONS
@@ -299,8 +309,10 @@ export async function reviewPr(
299
309
  options,
300
310
  loaded,
301
311
  config,
312
+ summary,
302
313
  isCi,
303
314
  operatorRoot,
315
+ claudeRun,
304
316
  });
305
317
  await validateGotchas(step2.gotchasPath);
306
318
  } catch (error) {
@@ -555,6 +567,7 @@ export async function reviewPr(
555
567
  adjudicationQueue,
556
568
  phaseB,
557
569
  diffStat,
570
+ prDiffStat,
558
571
  sizeGate,
559
572
  } = discovery;
560
573
 
@@ -575,6 +588,7 @@ export async function reviewPr(
575
588
  maxChangedLines: gateConfig.maxChangedLines,
576
589
  maxChangedFiles: gateConfig.maxChangedFiles,
577
590
  ciMode,
591
+ platformConnected: process.env.CRYSK_PLATFORM_CONNECTED === "true",
578
592
  });
579
593
  if (sizePlan !== null) {
580
594
  await settleCiGateSkip(
@@ -644,6 +658,9 @@ export async function reviewPr(
644
658
  prNumber,
645
659
  headSha,
646
660
  );
661
+ // Action mode only: the trace step reads the run's files from here when
662
+ // the run step publishes no run_dir (src/ci/cli-record.ts recordRunDir).
663
+ recordRunDir(runDir);
647
664
  // diff.patch is the EFFECTIVE diff — exactly what the hunters read (see
648
665
  // filterDiffByIgnoreRules); diff.raw.patch preserves the unfiltered
649
666
  // bytes, and only when the filter actually dropped something.
@@ -669,6 +686,11 @@ export async function reviewPr(
669
686
  parityFires,
670
687
  });
671
688
  const hunterCount = activeHunters.length;
689
+ const fullHunterCount = fullReviewHunterCount(
690
+ spec.agents,
691
+ anchorPatch,
692
+ config.parity_trigger_paths,
693
+ );
672
694
  // See resolvePrPlanAndConfirm (src/pr/plan.ts) for the full rationale —
673
695
  // the CI budget gate, route/capability resolution, the plan card, the
674
696
  // interactive confirm, and the "committed to spending" commit-status
@@ -685,6 +707,7 @@ export async function reviewPr(
685
707
  diffFromSha,
686
708
  diffPath,
687
709
  diffStat,
710
+ prDiffStat,
688
711
  droppedPaths: effectiveDiff.droppedPaths,
689
712
  sizeGate,
690
713
  sizeGateConfirmed,
@@ -699,9 +722,11 @@ export async function reviewPr(
699
722
  ciMode,
700
723
  statusContext,
701
724
  ciBudgetCeiling,
725
+ claudeRun,
702
726
  ciAdmissionLedger,
703
727
  skipDiscovery,
704
728
  hunterCount,
729
+ fullHunterCount,
705
730
  parityFires,
706
731
  verifyQueue,
707
732
  prepared,
package/src/pr/target.ts CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  sizeGateUnlimitedNoticeMessage,
29
29
  } from "#ci/gates";
30
30
  import { formatWorkflowCommand } from "#ci/reporter";
31
+ import { openCodeRoutesBillMetered } from "#ci/setup";
31
32
  import { resolveRepoRoot } from "#git/git";
32
33
  import { ghCurrentBranchPr, ghPrView } from "#pr/pr";
33
34
  import {
@@ -46,6 +47,7 @@ import {
46
47
  } from "#review/preflight";
47
48
  import type { ParsedAgent, PromptSetIdentity } from "#review/prompt-set";
48
49
  import type { estimateCost } from "#review/report";
50
+ import { buildCliRoutePlan } from "#review/route-preflight";
49
51
  import {
50
52
  type LoadedRunConfig,
51
53
  loadRunConfig,
@@ -64,7 +66,9 @@ import {
64
66
  legacyWorktreePath,
65
67
  prWorktreePath,
66
68
  } from "../home-preflight";
69
+ import type { RunClaudeCredential } from "../security/claude-credential";
67
70
  import { resolveOpenCodeAuthPath } from "../security/credential-broker";
71
+ import { readOpenCodeSecretNames } from "../security/opencode-secret-manifest";
68
72
 
69
73
  export interface ResolvedPrRunOptions {
70
74
  operatorRoot: string;
@@ -148,6 +152,29 @@ export interface ResolvedPrPromptSet {
148
152
  gotchasPath: string | undefined;
149
153
  }
150
154
 
155
+ // The OpenCode providers of every route the run resolves, fallbacks included,
156
+ // from the same plan builder the run confirms with (buildCliRoutePlan), so each
157
+ // source routing reads counts the way routing reads it. Undefined when the plan
158
+ // cannot be built here; the run itself surfaces that error at confirm.
159
+ async function openCodeRouteProviders(
160
+ input: Parameters<typeof buildCliRoutePlan>[0],
161
+ ): Promise<string[] | undefined> {
162
+ let plan: Awaited<ReturnType<typeof buildCliRoutePlan>>;
163
+ try {
164
+ plan = await buildCliRoutePlan(input);
165
+ } catch {
166
+ return undefined;
167
+ }
168
+ const providers = new Set<string>();
169
+ for (const step of plan.steps) {
170
+ for (const route of [step, ...(step.fallbacks ?? [])]) {
171
+ if (route.route.backend === "opencode")
172
+ providers.add(route.route.provider);
173
+ }
174
+ }
175
+ return [...providers].sort();
176
+ }
177
+
151
178
  // Step 1's second half: the CI budget ceiling (+ its notices), then the
152
179
  // prompt set resolution and the gotchas PATH (never the validation itself —
153
180
  // see this module's header). Runs after the caller's own
@@ -160,12 +187,43 @@ export async function resolvePrPromptSetAndBudget(params: {
160
187
  config: LoadedRunConfig["config"];
161
188
  isCi: boolean;
162
189
  operatorRoot: string;
190
+ // The summarizer's settings, for its route (openCodeRouteProviders).
191
+ summary: LoadedRunConfig["summary"];
192
+ // S5: the run's Claude credential, chosen once at run start (reviewPr). Its env
193
+ // holds only the chosen credential, so the ceiling follows the choice: the
194
+ // subscription has no metered ceiling, the API key keeps it. Absent (tests that
195
+ // pin the older wiring) reads the process env as before.
196
+ claudeRun?: RunClaudeCredential;
163
197
  }): Promise<ResolvedPrPromptSet> {
164
- // File presence, not envBillsMetered: that predicate stamps Claude
165
- // usage and must stay Anthropic-env-only.
166
- const billingMode = deriveCiBillingMode(process.env, {
167
- openCodeAuthPresent: existsSync(resolveOpenCodeAuthPath()),
168
- });
198
+ // The WHOLE resolution, not just its dir: under the compiled binary the
199
+ // prompt set is a map of embedded paths and `dir` is only a display label.
200
+ // Resolved first because the ceiling below reads the models it names.
201
+ const { agents, spec, agentFiles, promptSet } = await resolvePromptSet(
202
+ params.options,
203
+ params.loaded,
204
+ );
205
+ // The OpenCode half from the routes the run can take, not from the auth file
206
+ // existing (cryskai/platform#12): a file built for a ChatGPT subscription, one
207
+ // left on a runner whose HOME persists, or a local `opencode auth login` store
208
+ // invoices nothing for a run whose models do not bill per token. Not
209
+ // envBillsMetered either: that predicate stamps Claude usage and must stay
210
+ // Anthropic-env-only.
211
+ const billingMode = deriveCiBillingMode(
212
+ params.claudeRun?.env ?? process.env,
213
+ {
214
+ openCodeBillsMetered: openCodeRoutesBillMetered({
215
+ providers: await openCodeRouteProviders({
216
+ spec,
217
+ options: params.options,
218
+ agentFiles,
219
+ models: params.config.models,
220
+ summary: params.summary,
221
+ }),
222
+ authFilePresent: existsSync(resolveOpenCodeAuthPath()),
223
+ openCodeSecretNames: readOpenCodeSecretNames(),
224
+ }),
225
+ },
226
+ );
169
227
  // Issue #156: resolve the ceiling ONCE, here, and use this same value at
170
228
  // the budget gate far below (src/pr/review-pr.ts's plan/confirm stage).
171
229
  // Resolving twice invites the announcement and the gate drifting apart.
@@ -213,12 +271,6 @@ export async function resolvePrPromptSetAndBudget(params: {
213
271
  }
214
272
  }
215
273
  }
216
- // The WHOLE resolution, not just its dir: under the compiled binary the
217
- // prompt set is a map of embedded paths and `dir` is only a display label.
218
- const { agents, spec, agentFiles, promptSet } = await resolvePromptSet(
219
- params.options,
220
- params.loaded,
221
- );
222
274
  const instructions = resolveReviewInstructions(
223
275
  params.options.gotchas,
224
276
  params.operatorRoot,