crysk 0.5.0 → 0.6.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 (59) hide show
  1. package/README.md +2 -1
  2. package/package.json +3 -2
  3. package/skills/crysk-ci-setup/assets/workflow.yml +3 -0
  4. package/src/asset-manifest.ts +11 -0
  5. package/src/assets.ts +1 -1
  6. package/src/ci/credential-refresh.ts +524 -0
  7. package/src/ci/crysk-secrets.ts +20 -6
  8. package/src/ci/force-comment.ts +14 -1
  9. package/src/ci/gates.ts +64 -21
  10. package/src/ci/outcome.ts +165 -15
  11. package/src/ci/platform-estimate.ts +111 -0
  12. package/src/ci/platform-trace.ts +30 -0
  13. package/src/ci/platform.ts +183 -5
  14. package/src/ci/reporter.ts +14 -4
  15. package/src/ci/setup.ts +96 -6
  16. package/src/ci/trace-bundle.ts +231 -27
  17. package/src/ci/trace-transcripts.ts +65 -0
  18. package/src/ci/trigger.ts +20 -4
  19. package/src/commands/ci-setup.ts +12 -3
  20. package/src/commands/doctor.ts +25 -23
  21. package/src/diversity/identity.ts +11 -1
  22. package/src/diversity/pipeline-integration.ts +19 -6
  23. package/src/doctor.ts +133 -4
  24. package/src/execution/contracts.ts +15 -3
  25. package/src/harness/materiality-judge.ts +153 -0
  26. package/src/harness/pipeline-plan.ts +133 -0
  27. package/src/harness/replay-rows.ts +172 -0
  28. package/src/harness/route-runner.ts +288 -0
  29. package/src/harness/single-step.ts +153 -0
  30. package/src/index.ts +1 -1
  31. package/src/model/catalog.ts +10 -7
  32. package/src/model/model-name.ts +14 -0
  33. package/src/model/profiles/claude.ts +34 -0
  34. package/src/model/profiles/openai.ts +44 -0
  35. package/src/model/profiles.ts +213 -0
  36. package/src/model/routing.ts +155 -50
  37. package/src/pr/ci-admission-gate.ts +2 -0
  38. package/src/pr/discovery.ts +18 -0
  39. package/src/pr/plan.ts +41 -2
  40. package/src/pr/review-pr.ts +43 -6
  41. package/src/pr/target.ts +67 -15
  42. package/src/production-runtime.ts +100 -13
  43. package/src/review/pipeline.ts +193 -58
  44. package/src/review/preflight.ts +91 -9
  45. package/src/review/prompt-set.ts +68 -0
  46. package/src/review/report.ts +4 -0
  47. package/src/review/review.ts +21 -11
  48. package/src/review/route-preflight.ts +117 -67
  49. package/src/review/run.ts +50 -4
  50. package/src/security/credential-broker.ts +21 -9
  51. package/src/security/oauth-providers.ts +101 -0
  52. package/src/transport-registry.ts +33 -0
  53. package/src/transports/opencode-sdk.ts +33 -1
  54. package/src/ui/config-edit.ts +9 -0
  55. package/src/ui/config.ts +1 -0
  56. package/src/ui/menu.ts +9 -2
  57. package/src/ui/plan.ts +8 -3
  58. package/src/updater.ts +21 -13
  59. package/src/wizard.ts +23 -0
@@ -3,6 +3,7 @@
3
3
  // routes across Claude and OpenCode runners before confirming or spending tokens.
4
4
 
5
5
  import type { ModelsConfig } from "#model/model-name";
6
+ import { FALLBACK_PROFILE, type ModelProfile } from "#model/profiles";
6
7
  import {
7
8
  capabilityGateDecision,
8
9
  produceClaudeCapabilityReport,
@@ -13,7 +14,7 @@ import {
13
14
  planRoutes,
14
15
  type ResolvedRoutePlan,
15
16
  } from "#model/routing";
16
- import { resolveEngineAssets } from "../assets";
17
+ import { type EngineAssets, resolveEngineAssets } from "../assets";
17
18
  import { CliError } from "../errors";
18
19
  import type { RunnerBackend } from "../execution/contracts";
19
20
  import {
@@ -40,26 +41,79 @@ import {
40
41
  type TransportRegistry,
41
42
  } from "../transport-registry";
42
43
  import type { OpenCodeSdkLike } from "../transports/opencode-client";
43
- import { DEFAULT_CONSOLIDATE_MODEL, DEFAULT_SCOUT_MODEL } from "./pipeline";
44
44
  import {
45
+ type AgentsDirResolution,
45
46
  type CliOptions,
46
47
  type ConfigLayer,
47
48
  resolveMaterialityGate,
48
49
  type SummarySettings,
49
50
  } from "./preflight";
50
- import { type ParsedAgent, parseAgentFile } from "./prompt-set";
51
+ import {
52
+ type EnginePromptFile,
53
+ type ParsedAgent,
54
+ type ProfilePromptSets,
55
+ profilePromptSet,
56
+ } from "./prompt-set";
51
57
  import type { ReviewSpec } from "./spec";
52
58
 
59
+ // Where the engine-owned root prompts are looked up (model-profiles S4). All
60
+ // optional: production passes nothing, which is the `claude` profile over the
61
+ // runtime's own assets. `promptSets` is injected by tests only, since no
62
+ // profile ships a set yet.
63
+ export interface EnginePromptOptions {
64
+ profile?: ModelProfile;
65
+ promptSets?: ProfilePromptSets;
66
+ assets?: EngineAssets;
67
+ }
68
+
69
+ // What a production caller hands the pipeline*Input helpers: the run's
70
+ // profile is required (openai-profile S3), so a caller cannot forget it and
71
+ // silently read the fallback profile's prompts.
72
+ export type RunPromptOptions = EnginePromptOptions & { profile: ModelProfile };
73
+
74
+ // THE read site for an engine-owned root prompt: the active profile's set,
75
+ // falling back to the default file. A user `agents_dir` never reaches here:
76
+ // it covers the five agent files only, as it always did.
77
+ export function enginePromptPath(
78
+ file: EnginePromptFile,
79
+ options: EnginePromptOptions = {},
80
+ ): string {
81
+ const assets = options.assets ?? resolveEngineAssets();
82
+ const override = profilePromptSet(
83
+ options.profile ?? FALLBACK_PROFILE,
84
+ Object.keys(assets.bundledAgentFiles),
85
+ options.promptSets,
86
+ ).engine[file];
87
+ if (override !== undefined) return override;
88
+ switch (file) {
89
+ case "consolidate.md":
90
+ return assets.consolidatePromptPath;
91
+ case "scout.md":
92
+ return assets.scoutPromptPath;
93
+ case "summarizer.md":
94
+ return assets.summarizerPromptPath;
95
+ case "materiality.md":
96
+ return assets.materialityPromptPath;
97
+ }
98
+ }
99
+
100
+ // Every input below marks its prompt `bundled`: it is the engine's own, so its
101
+ // model and effort come from the active profile and never from its
102
+ // frontmatter (S3), in the plan and in the step alike. The materiality judge
103
+ // needs no mark: its model is pinned (judgeModelChoice) and its frontmatter
104
+ // was never read for routing.
53
105
  export function pipelineSummarizerInput(
54
106
  summary: SummarySettings,
107
+ prompts: RunPromptOptions,
55
108
  ):
56
- | { summarizer: { promptPath: string; model?: string } }
109
+ | { summarizer: { promptPath: string; model?: string; bundled: true } }
57
110
  | Record<string, never> {
58
111
  return summary.enabled
59
112
  ? {
60
113
  summarizer: {
61
- promptPath: resolveEngineAssets().summarizerPromptPath,
114
+ promptPath: enginePromptPath("summarizer.md", prompts),
62
115
  ...(summary.model === undefined ? {} : { model: summary.model }),
116
+ bundled: true,
63
117
  },
64
118
  }
65
119
  : {};
@@ -73,14 +127,18 @@ export function pipelineSummarizerInput(
73
127
  // than argued. `prompts/` is the door the summarizer already walked through.
74
128
  export function pipelineScoutInput(
75
129
  options: Pick<CliOptions, "scout" | "scoutModel">,
76
- ): { scout: { promptPath: string; model?: string } } | Record<string, never> {
130
+ prompts: RunPromptOptions,
131
+ ):
132
+ | { scout: { promptPath: string; model?: string; bundled: true } }
133
+ | Record<string, never> {
77
134
  return options.scout
78
135
  ? {
79
136
  scout: {
80
- promptPath: resolveEngineAssets().scoutPromptPath,
137
+ promptPath: enginePromptPath("scout.md", prompts),
81
138
  ...(options.scoutModel === undefined
82
139
  ? {}
83
140
  : { model: options.scoutModel }),
141
+ bundled: true,
84
142
  },
85
143
  }
86
144
  : {};
@@ -91,11 +149,14 @@ export function pipelineScoutInput(
91
149
  // gain on the Martian 50 (lab bench/METRICS.md 2026-10-27), and a failed pass
92
150
  // falls back to the unconsolidated findings. The lab's direct `runPipeline`
93
151
  // callers do not go through here, so their pipeline is unchanged.
94
- export function pipelineConsolidateInput(): {
95
- consolidate: { promptPath: string; model?: string };
152
+ export function pipelineConsolidateInput(prompts: RunPromptOptions): {
153
+ consolidate: { promptPath: string; model?: string; bundled: true };
96
154
  } {
97
155
  return {
98
- consolidate: { promptPath: resolveEngineAssets().consolidatePromptPath },
156
+ consolidate: {
157
+ promptPath: enginePromptPath("consolidate.md", prompts),
158
+ bundled: true,
159
+ },
99
160
  };
100
161
  }
101
162
 
@@ -106,20 +167,37 @@ export function pipelineConsolidateInput(): {
106
167
  // travels here.
107
168
  export function pipelineMaterialityInput(
108
169
  config: Pick<ConfigLayer, "materiality_gate">,
170
+ prompts: RunPromptOptions,
109
171
  ): { materiality: { promptPath: string } } | Record<string, never> {
110
172
  return resolveMaterialityGate(config)
111
173
  ? {
112
174
  materiality: {
113
- promptPath: resolveEngineAssets().materialityPromptPath,
175
+ promptPath: enginePromptPath("materiality.md", prompts),
114
176
  },
115
177
  }
116
178
  : {};
117
179
  }
118
180
 
181
+ // Whether a run's agents are the engine's bundled prompt set, the one input
182
+ // that decides whether their routing comes from the model profile or from
183
+ // their frontmatter (model-profiles S3). The resolution's SOURCE, not its
184
+ // `kind`: `kind === "bundled"` is the compiled binary only, while dev and npm
185
+ // resolve the same bundled set to a real directory with source "default".
186
+ // Every product path reads it here, for the plan and the pipeline alike, so the
187
+ // two can never disagree about it.
188
+ export function isBundledAgentsDir(
189
+ agents: Pick<AgentsDirResolution, "source">,
190
+ ): boolean {
191
+ return agents.source === "default";
192
+ }
193
+
119
194
  export async function buildCliRoutePlan(params: {
120
195
  spec: ReviewSpec;
121
196
  options: CliOptions;
122
197
  agentFiles: Map<string, ParsedAgent>;
198
+ // isBundledAgentsDir of the run's agents. Required so no caller can drop it
199
+ // and build a plan that disagrees with the steps the pipeline composes.
200
+ bundledAgents: boolean;
123
201
  models?: ModelsConfig;
124
202
  summary: SummarySettings;
125
203
  summarizerEnabled?: boolean;
@@ -131,80 +209,50 @@ export async function buildCliRoutePlan(params: {
131
209
  // Defaults OFF, unlike consolidation: the gate is opt-in, and a judge key in
132
210
  // the plan changes its fingerprint, so absent must mean today's plan.
133
211
  materialityEnabled?: boolean;
212
+ // The active model profile (openai-profile S3): the config's `profile`,
213
+ // resolved once (resolveProfile). Required so the compiler finds every
214
+ // caller: a missed one would silently plan the fallback profile.
215
+ profile: ModelProfile;
134
216
  }): Promise<ResolvedRoutePlan> {
135
217
  const summarizerEnabled = params.summarizerEnabled ?? params.summary.enabled;
136
218
  const scoutEnabled = params.scoutEnabled ?? params.options.scout;
137
219
  const consolidateEnabled = params.consolidateEnabled ?? true;
138
- let summarizerFrontmatter: string | undefined;
139
- if (summarizerEnabled) {
140
- try {
141
- const parsed = await parseAgentFile(
142
- resolveEngineAssets().summarizerPromptPath,
143
- );
144
- summarizerFrontmatter = parsed.model;
145
- } catch {
146
- // Engine-owned prompt may be unreadable in tests; route resolution still
147
- // falls through CLI > spec > frontmatter precedence without it.
148
- }
149
- }
150
- let scoutFrontmatter: string | undefined;
151
- if (scoutEnabled) {
152
- try {
153
- const parsed = await parseAgentFile(
154
- resolveEngineAssets().scoutPromptPath,
155
- );
156
- scoutFrontmatter = parsed.model;
157
- } catch {
158
- // Same contract as the summarizer branch above.
159
- }
160
- }
161
- let consolidateFrontmatter: string | undefined;
162
- if (consolidateEnabled) {
163
- try {
164
- const parsed = await parseAgentFile(
165
- resolveEngineAssets().consolidatePromptPath,
166
- );
167
- consolidateFrontmatter = parsed.model;
168
- } catch {
169
- // Same contract as the summarizer branch above.
170
- }
171
- }
220
+ // The root prompts are the engine's own (pipeline*Input marks them), so
221
+ // their frontmatter is not read: the profile holds their seat (S3), the
222
+ // same seat the pipeline gives each step, and the two cannot disagree.
172
223
  return buildResolvedRoutePlan({
173
224
  agents: params.spec.agents,
174
225
  cliModel: params.options.model,
175
226
  models: params.models,
227
+ profile: params.profile,
228
+ ...(params.bundledAgents ? { bundledAgents: true } : {}),
176
229
  frontmatterModel: (agentKey) => params.agentFiles.get(agentKey)?.model,
177
230
  ...(summarizerEnabled
178
- ? {
179
- summarizer: {
180
- model: params.summary.model,
181
- frontmatterModel: summarizerFrontmatter,
182
- },
183
- }
231
+ ? { summarizer: { model: params.summary.model, bundled: true } }
184
232
  : {}),
185
233
  ...(scoutEnabled
186
- ? {
187
- scout: {
188
- model: params.options.scoutModel,
189
- frontmatterModel: scoutFrontmatter,
190
- defaultModel: DEFAULT_SCOUT_MODEL,
191
- },
192
- }
193
- : {}),
194
- ...(consolidateEnabled
195
- ? {
196
- consolidate: {
197
- frontmatterModel: consolidateFrontmatter,
198
- defaultModel: DEFAULT_CONSOLIDATE_MODEL,
199
- },
200
- }
234
+ ? { scout: { model: params.options.scoutModel, bundled: true } }
201
235
  : {}),
236
+ ...(consolidateEnabled ? { consolidate: { bundled: true } } : {}),
202
237
  ...(params.materialityEnabled === true
203
238
  ? { materiality: true as const }
204
239
  : {}),
205
240
  });
206
241
  }
207
242
 
243
+ // Whether a run needs the Claude binary's execution authority: always for the
244
+ // legacy no-plan runner (it is the Claude CLI), otherwise only when some route
245
+ // or fallback runs on claude-code. CI skips the Claude install exactly when no
246
+ // step routes to it (routing-claude=false), so this check must agree.
247
+ export function claudeAuthorityRequired(
248
+ routePlan: ResolvedRoutePlan | undefined,
249
+ ): boolean {
250
+ if (routePlan === undefined) return true;
251
+ return planRoutes(routePlan).some(
252
+ (step) => step.route.backend === "claude-code",
253
+ );
254
+ }
255
+
208
256
  // Whether a plan that failed to build may fall back to the legacy no-plan
209
257
  // path (a prompt or `--model` naming a raw Claude id the CLI resolves itself).
210
258
  // Never when `models` is set, and never for a model written in the new form:
@@ -244,7 +292,9 @@ export class OpenCodeCredentialRefusalError extends CredentialRefusalError {
244
292
  refusal.message,
245
293
  { kind: "credential", failureClass: refusal.failureClass },
246
294
  refusal.params,
247
- `no credential record for OpenCode provider ${refusal.params.provider}; refused before any provider spend`,
295
+ refusal.failureClass === "subscription_expiring"
296
+ ? `subscription login for OpenCode provider ${refusal.params.provider} expires within the review; refused before any provider spend`
297
+ : `no credential record for OpenCode provider ${refusal.params.provider}; refused before any provider spend`,
248
298
  );
249
299
  }
250
300
  }
package/src/review/run.ts CHANGED
@@ -22,6 +22,7 @@ import {
22
22
  notionalCostInput,
23
23
  } from "#config/config";
24
24
  import type { ModelsConfig } from "#model/model-name";
25
+ import { type ModelProfile, resolveProfile } from "#model/profiles";
25
26
  import type { ResolvedRoutePlan } from "#model/routing";
26
27
  import type { CiMode } from "#pr/preflight";
27
28
  import {
@@ -117,6 +118,10 @@ export interface LoadedRunConfig {
117
118
  summary: SummarySettings;
118
119
  scout: boolean;
119
120
  post: boolean;
121
+ // The run's model profile, resolved once here from `config.profile`
122
+ // (openai-profile S3). Every route, prompt and pipeline input of the run
123
+ // reads this one value.
124
+ profile: ModelProfile;
120
125
  }
121
126
 
122
127
  // Config load + the three per-run resolvers read right after it: identical
@@ -148,7 +153,8 @@ export async function loadRunConfig(params: {
148
153
  const summary = resolveSummary(params.options, config);
149
154
  const scout = resolveScout(params.options, config);
150
155
  const post = resolvePost(params.options, config);
151
- return { loaded, config, summary, scout, post };
156
+ const profile = resolveProfile(config.profile);
157
+ return { loaded, config, summary, scout, post, profile };
152
158
  }
153
159
 
154
160
  // Shared range guard. Both orchestrators check the same thing right after
@@ -256,6 +262,22 @@ export function resolveParityFires(
256
262
  return parityTriggered(changedPathsFromDiff(patch), parityTriggerPaths);
257
263
  }
258
264
 
265
+ // How many hunters a full review of the whole PR runs: the unconditional ones,
266
+ // plus the parity hunter when the full PR patch touches a trigger path. A
267
+ // narrowed run's own count (none on a verify-only pass, no parity hunter when
268
+ // only the delta was read) would understate a full review, which is what the
269
+ // platform estimate's share divides by (cryskai/platform#12).
270
+ export function fullReviewHunterCount(
271
+ agents: readonly AgentSpec[],
272
+ prPatch: string,
273
+ parityTriggerPaths: string[],
274
+ ): number {
275
+ return selectActiveHunters(
276
+ agents,
277
+ resolveParityFires(prPatch, parityTriggerPaths),
278
+ ).length;
279
+ }
280
+
259
281
  // The diff stat, TWICE and on purpose (moved here from review()'s own WHY
260
282
  // comment when reviewPr()'s copy — which never carried it — started sharing
261
283
  // this stage):
@@ -434,8 +456,14 @@ export interface ResolvedPromptSet {
434
456
  export async function resolvePromptSet(
435
457
  options: Pick<CliOptions, "agents">,
436
458
  loaded: EffectiveConfig,
459
+ // The run's profile (openai-profile S3), whose prompt set the agents come
460
+ // from (model-profiles S4). Required, so no caller reads the fallback's set
461
+ // by forgetting it; tests may add `promptSets`.
462
+ prompts: NonNullable<Parameters<typeof resolveAgentsDir>[3]> & {
463
+ profile: ModelProfile;
464
+ },
437
465
  ): Promise<ResolvedPromptSet> {
438
- const agents = resolveAgentsDir(options, loaded);
466
+ const agents = resolveAgentsDir(options, loaded, undefined, prompts);
439
467
  const spec = validateReviewSpec(localReviewSpec());
440
468
  spec.agents.forEach((agent, i) => {
441
469
  assertBasenameOnly(agent.file, i);
@@ -471,8 +499,10 @@ export async function resolvePromptSet(
471
499
  spec.agents.map((a) => agentFilePath(agents, a.file)),
472
500
  // A bundled set has no directory basename to be named after. "default"
473
501
  // is what dev and npm derive from prompts/default, so the same prompt
474
- // set names itself identically in all three runtimes.
475
- agents.kind === "bundled" ? "default" : undefined,
502
+ // set names itself identically in all three runtimes. A profile's prompt
503
+ // set merged over it (model-profiles S4) is named after that set, the way
504
+ // a person's set is named after its directory.
505
+ agents.promptSet ?? (agents.kind === "bundled" ? "default" : undefined),
476
506
  );
477
507
  return { agents, spec, agentFiles, promptSet };
478
508
  }
@@ -493,6 +523,16 @@ export async function writeMcpConfig(
493
523
  );
494
524
  }
495
525
 
526
+ // Whether the person chose the routing (openai-profile S5): `models` or a
527
+ // `profile`. Either one makes a route plan that fails to build fatal, rather
528
+ // than a fallback to the no-plan run, which runs the fallback profile's
529
+ // models: a person who chose a profile must never get another one silently.
530
+ export function routingConfigured(
531
+ config: Pick<LocalConfig, "models" | "profile">,
532
+ ): boolean {
533
+ return config.models !== undefined || config.profile !== undefined;
534
+ }
535
+
496
536
  // Production route resolution: identical in both orchestrators except the
497
537
  // workspace root and (reviewPr()'s skipped-discovery re-review only) the
498
538
  // summarizer/scout enable overrides. Named distinctly from
@@ -505,7 +545,11 @@ export async function resolvePipelineRoute(params: {
505
545
  spec: ReviewSpec;
506
546
  options: CliOptions;
507
547
  agentFiles: Map<string, ParsedAgent>;
548
+ // isBundledAgentsDir (#review/route-preflight) of the run's agents.
549
+ bundledAgents: boolean;
508
550
  models: ModelsConfig | undefined;
551
+ // The run's profile, resolved once from the config (openai-profile S3).
552
+ profile: ModelProfile;
509
553
  summary: SummarySettings;
510
554
  summarizerEnabled?: boolean;
511
555
  scoutEnabled?: boolean;
@@ -529,7 +573,9 @@ export async function resolvePipelineRoute(params: {
529
573
  spec: params.spec,
530
574
  options: params.options,
531
575
  agentFiles: params.agentFiles,
576
+ bundledAgents: params.bundledAgents,
532
577
  models: params.models,
578
+ profile: params.profile,
533
579
  summary: params.summary,
534
580
  summarizerEnabled: params.summarizerEnabled,
535
581
  scoutEnabled: params.scoutEnabled,
@@ -16,6 +16,7 @@ import {
16
16
  import { homedir, tmpdir } from "node:os";
17
17
  import path from "node:path";
18
18
  import type { CredentialKind } from "#model/provider-capabilities";
19
+ import { recordExpiresAt, reviewCopyOfRecord } from "./oauth-providers";
19
20
 
20
21
  export type CredentialProjectionFile = {
21
22
  readonly path: string;
@@ -76,7 +77,11 @@ export type CredentialProjectionFailureClass =
76
77
  // whatever provider keys happen to be ambient. It falls into the
77
78
  // fail-closed branch there, and must stay there.
78
79
  | "missing_provider_record"
79
- | "projection_layout_invalid";
80
+ | "projection_layout_invalid"
81
+ // A subscription login whose access token has expired (the broker) or expires
82
+ // within the review (admission, REVIEW_EXPIRY_MARGIN_MS). A review never renews
83
+ // a rotating provider's login itself (oauth-providers.ts).
84
+ | "subscription_expiring";
80
85
 
81
86
  export class CredentialProjectionError extends Error {
82
87
  readonly failureClass: CredentialProjectionFailureClass;
@@ -390,11 +395,18 @@ export class OpenCodeAuthBroker implements CredentialBroker {
390
395
  if (!lookup.ok) {
391
396
  throw new CredentialProjectionError(lookup.failureClass);
392
397
  }
398
+ // Admission refuses a login that would expire during the review; this is the
399
+ // last word for a step that starts after it already has, so the child never
400
+ // tries to renew it with the emptied refresh token.
401
+ const expiresAt = recordExpiresAt(lookup.record);
402
+ if (expiresAt !== undefined && expiresAt <= Date.now()) {
403
+ throw new CredentialProjectionError("subscription_expiring");
404
+ }
393
405
 
394
406
  return buildOpenCodeProjection(
395
407
  input.kind,
396
408
  OPENCODE_OAUTH_PROVIDER,
397
- lookup.record,
409
+ reviewCopyOfRecord(OPENCODE_OAUTH_PROVIDER, lookup.record),
398
410
  );
399
411
  }
400
412
  }
@@ -469,13 +481,13 @@ function buildOpenCodeProjection(
469
481
  mkdirSync(dir, { recursive: true, mode: 0o700 });
470
482
  }
471
483
 
472
- // The record travels WHOLE. On the OAuth route its access token expires
473
- // (~10 days on the observed store) and the child renews it with the refresh
474
- // token; a projection carrying only `access` would hand the child a
475
- // credential it cannot rotate, and it would go stale mid-run with no way
476
- // back. On the API-token route the same rule holds for a different reason:
477
- // the store's own record shape is what OpenCode reads, and reconstructing a
478
- // subset of it here would be a second, silently drifting schema.
484
+ // The record travels in the store's own shape, which is what OpenCode reads;
485
+ // reconstructing a subset here would be a second, silently drifting schema. The
486
+ // one change is made before this call, by the OAuth broker: a rotating
487
+ // provider's refresh token is emptied (reviewCopyOfRecord, oauth-providers.ts),
488
+ // because this copy is deleted after the run and a token renewed into it would
489
+ // spend the stored chain for nothing. The login is renewed by the Crysk
490
+ // platform's refresher, never by a review.
479
491
  const payload = `${JSON.stringify({ [provider]: record }, null, 2)}\n`;
480
492
  writeFileSync(layout.authFile, payload, { mode: 0o600 });
481
493
 
@@ -0,0 +1,101 @@
1
+ // OAuth subscription providers, one descriptor each (cryskai/platform
2
+ // odd/tasks/openai-oauth.md, "Provider-generic"). Behavior that differs by
3
+ // provider is read from here, never branched on a provider name, so a provider
4
+ // that behaves like OpenAI is one more entry. The Crysk platform keeps the same
5
+ // table in packages/core/src/oauth-providers.ts.
6
+ //
7
+ // WHY no imports: the steps that run before `bun install` (the trigger, the
8
+ // connect step) may read it, and they are limited to runtime builtins.
9
+
10
+ export interface OAuthProviderDescriptor {
11
+ // The OpenCode provider id, the key of its record in auth.json.
12
+ readonly id: string;
13
+ // Whether the provider issues a new refresh token on every refresh and refuses
14
+ // the old one afterwards (OpenAI answers `refresh_token_reused`). A review never
15
+ // holds such a provider's refresh token: renewing it inside a run would spend
16
+ // the stored chain and throw the new token away with the run's copy.
17
+ readonly rotatesRefreshToken: boolean;
18
+ // How the runner-side refresher renews the login (src/ci/credential-refresh.ts):
19
+ // an RFC 6749 `grant_type=refresh_token` POST, form-encoded, to `tokenUrl` with
20
+ // `client_id` and any `extraParams`.
21
+ readonly refresh: {
22
+ readonly tokenUrl: string;
23
+ readonly clientId: string;
24
+ readonly extraParams?: Readonly<Record<string, string>>;
25
+ };
26
+ // The provider error codes that mean the login is gone and the person must log
27
+ // in again. Read from the token endpoint's error body (a string `error`, an
28
+ // `error.code`, or a top-level `code`). Any other error is not permanent.
29
+ readonly permanentErrors: readonly string[];
30
+ // Where the record's account id comes from, or undefined when the provider has
31
+ // none. The id is read from the JWT claims of the token response's `tokens`,
32
+ // in order, trying each claim path in order; when none answers, the stored
33
+ // record's `recordField` is kept.
34
+ readonly accountId?: {
35
+ readonly recordField: string;
36
+ readonly tokens: readonly string[];
37
+ readonly claims: readonly (readonly (string | number)[])[];
38
+ };
39
+ }
40
+
41
+ // OpenAI's values are OpenCode's (v1.18.30,
42
+ // packages/opencode/src/plugin/openai/codex.ts: CLIENT_ID, refreshAccessToken,
43
+ // extractAccountIdFromClaims), so the refresher renews the login exactly as
44
+ // OpenCode itself would. The error codes are Codex's permanent refresh failures
45
+ // plus the standard OAuth `invalid_grant`.
46
+ export const OAUTH_PROVIDERS: readonly OAuthProviderDescriptor[] = [
47
+ {
48
+ id: "openai",
49
+ rotatesRefreshToken: true,
50
+ refresh: {
51
+ tokenUrl: "https://auth.openai.com/oauth/token",
52
+ clientId: "app_EMoamEEZ73f0CkXaXp7hrann",
53
+ },
54
+ permanentErrors: [
55
+ "refresh_token_reused",
56
+ "refresh_token_expired",
57
+ "refresh_token_invalidated",
58
+ "invalid_grant",
59
+ ],
60
+ accountId: {
61
+ recordField: "accountId",
62
+ tokens: ["id_token", "access_token"],
63
+ claims: [
64
+ ["chatgpt_account_id"],
65
+ ["https://api.openai.com/auth", "chatgpt_account_id"],
66
+ ["organizations", 0, "id"],
67
+ ],
68
+ },
69
+ },
70
+ ];
71
+
72
+ export function oauthProvider(id: string): OAuthProviderDescriptor | undefined {
73
+ return OAUTH_PROVIDERS.find((provider) => provider.id === id);
74
+ }
75
+
76
+ // A review refuses to start on a login whose access token expires within this
77
+ // margin. The longest review observed takes about 25 minutes; OpenAI's tokens
78
+ // live 240 hours, and the platform renews them at 80% of that.
79
+ export const REVIEW_EXPIRY_MARGIN_MS = 2 * 60 * 60 * 1000;
80
+
81
+ // The record's own expiry, in milliseconds since the epoch, or undefined when it
82
+ // states none. OpenCode's OAuth record keeps it as `expires`.
83
+ export function recordExpiresAt(record: unknown): number | undefined {
84
+ if (typeof record !== "object" || record === null) return undefined;
85
+ const expires = (record as Record<string, unknown>).expires;
86
+ return typeof expires === "number" && Number.isFinite(expires)
87
+ ? expires
88
+ : undefined;
89
+ }
90
+
91
+ // The copy of a record a review may hold: for a rotating provider, every field
92
+ // but the refresh token, emptied. OpenCode's schema accepts "" and reads it only
93
+ // once the access token has expired, and then fails instead of rotating.
94
+ export function reviewCopyOfRecord<T extends object>(
95
+ providerId: string,
96
+ record: T,
97
+ ): T {
98
+ if (oauthProvider(providerId)?.rotatesRefreshToken !== true) return record;
99
+ if (!("refresh" in record)) return record;
100
+ return { ...record, refresh: "" };
101
+ }
@@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
+ import { opencodeSecretName } from "#ci/crysk-secrets";
5
6
  import { capabilityGateDecision } from "#model/provider-capabilities";
6
7
  import {
7
8
  planRoutes,
@@ -15,6 +16,7 @@ import { type AssetMode, detectAssetMode } from "./assets";
15
16
  // step timeout and calls destroy on credential projection after transport returns).
16
17
  import type {
17
18
  CredentialKind,
19
+ OpenCodeFailureCredential,
18
20
  ProviderCapabilityReport,
19
21
  ProviderTransport,
20
22
  ResolvedModelRoute,
@@ -544,6 +546,27 @@ export interface CreateTransportRegistryOptions
544
546
  readonly mode?: "production" | "conformance";
545
547
  }
546
548
 
549
+ // S7: the CRYSK_OPENCODE_* secret an OpenCode route runs on, as a failed attempt names
550
+ // it. The kind decides the name the way chooseOpenCodeSecret decided the kind: the
551
+ // ChatGPT OAuth kind is the `_OAUTH` record, a metered token the `_API_KEY`. A free
552
+ // route runs on no secret, and an unknown kind or provider names none rather than guess.
553
+ export function openCodeFailureCredential(
554
+ provider: string | undefined,
555
+ kind: CredentialKind | undefined,
556
+ ): OpenCodeFailureCredential | undefined {
557
+ if (provider === undefined) return undefined;
558
+ const secretKind =
559
+ kind === "opencode_chatgpt_oauth"
560
+ ? "oauth"
561
+ : kind === "provider_api_token"
562
+ ? "api_key"
563
+ : undefined;
564
+ if (secretKind === undefined) return undefined;
565
+ return opencodeSecretName(provider, secretKind) as
566
+ | OpenCodeFailureCredential
567
+ | undefined;
568
+ }
569
+
547
570
  export class DefaultTransportRegistry implements TransportRegistry {
548
571
  private readonly factories = new Map<
549
572
  RunnerBackend,
@@ -672,6 +695,14 @@ export class DefaultTransportRegistry implements TransportRegistry {
672
695
  provider: route?.provider ?? "opencode",
673
696
  };
674
697
  const defaultRoute: ResolvedModelRoute | undefined = route;
698
+ // S7: the secret this route runs on, from the same kind the billing mode reads,
699
+ // computed above both construction branches for the same reason.
700
+ const failureCredential = openCodeFailureCredential(
701
+ route?.provider,
702
+ merged.credentialKind,
703
+ );
704
+ const credentialOption =
705
+ failureCredential === undefined ? {} : { failureCredential };
675
706
 
676
707
  if (merged.openCodeClient) {
677
708
  return new OpenCodeSdkTransport({
@@ -679,6 +710,7 @@ export class DefaultTransportRegistry implements TransportRegistry {
679
710
  billingMode: usageBillingMode,
680
711
  admissionIdentity,
681
712
  defaultRoute,
713
+ ...credentialOption,
682
714
  });
683
715
  }
684
716
 
@@ -745,6 +777,7 @@ export class DefaultTransportRegistry implements TransportRegistry {
745
777
  billingMode: usageBillingMode,
746
778
  admissionIdentity,
747
779
  defaultRoute,
780
+ ...credentialOption,
748
781
  });
749
782
  });
750
783
  }