crysk 0.5.1 → 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 (48) 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/outcome.ts +165 -15
  9. package/src/ci/platform.ts +155 -7
  10. package/src/ci/setup.ts +64 -6
  11. package/src/ci/trigger.ts +20 -4
  12. package/src/commands/ci-setup.ts +12 -3
  13. package/src/commands/doctor.ts +25 -23
  14. package/src/diversity/identity.ts +11 -1
  15. package/src/diversity/pipeline-integration.ts +19 -6
  16. package/src/doctor.ts +133 -4
  17. package/src/execution/contracts.ts +15 -3
  18. package/src/harness/materiality-judge.ts +153 -0
  19. package/src/harness/pipeline-plan.ts +133 -0
  20. package/src/harness/replay-rows.ts +172 -0
  21. package/src/harness/route-runner.ts +288 -0
  22. package/src/harness/single-step.ts +153 -0
  23. package/src/index.ts +1 -1
  24. package/src/model/catalog.ts +10 -7
  25. package/src/model/model-name.ts +14 -0
  26. package/src/model/profiles/claude.ts +34 -0
  27. package/src/model/profiles/openai.ts +44 -0
  28. package/src/model/profiles.ts +213 -0
  29. package/src/model/routing.ts +155 -50
  30. package/src/pr/plan.ts +6 -1
  31. package/src/pr/review-pr.ts +32 -6
  32. package/src/pr/target.ts +16 -7
  33. package/src/production-runtime.ts +100 -13
  34. package/src/review/pipeline.ts +193 -58
  35. package/src/review/preflight.ts +91 -9
  36. package/src/review/prompt-set.ts +68 -0
  37. package/src/review/review.ts +21 -11
  38. package/src/review/route-preflight.ts +117 -67
  39. package/src/review/run.ts +34 -4
  40. package/src/security/credential-broker.ts +21 -9
  41. package/src/security/oauth-providers.ts +101 -0
  42. package/src/transport-registry.ts +33 -0
  43. package/src/transports/opencode-sdk.ts +33 -1
  44. package/src/ui/config-edit.ts +9 -0
  45. package/src/ui/config.ts +1 -0
  46. package/src/ui/menu.ts +9 -2
  47. package/src/updater.ts +21 -13
  48. package/src/wizard.ts +23 -0
package/src/ci/setup.ts CHANGED
@@ -51,6 +51,7 @@ import {
51
51
  CREDENTIALS_INPUT_LINE,
52
52
  type ErrorClass,
53
53
  MODELS_INPUT_LINE,
54
+ PROFILE_INPUT_LINE,
54
55
  type SetupRecord,
55
56
  } from "#ci/outcome";
56
57
  import { appendGithubOutput } from "#ci/platform";
@@ -74,6 +75,7 @@ import {
74
75
  parseModelName,
75
76
  parseModelsConfig,
76
77
  } from "#model/model-name";
78
+ import { MODEL_PROFILES, profileModels } from "#model/profiles";
77
79
  import { parseGlobalConfig, parseLocalConfig } from "#review/preflight";
78
80
  import { commandForms } from "../brand";
79
81
  import {
@@ -281,7 +283,10 @@ ${lines}
281
283
  # repository variables. Unset, every role runs the default Claude model
282
284
  # and the subscription is tried first.
283
285
  ${MODELS_INPUT_LINE}
284
- ${CREDENTIALS_INPUT_LINE}`;
286
+ ${CREDENTIALS_INPUT_LINE}
287
+ # The model profile (claude or openai) from a repository variable.
288
+ # Unset, the claude profile. models still wins role by role.
289
+ ${PROFILE_INPUT_LINE}`;
285
290
  }
286
291
 
287
292
  export function generateCiWorkflowTemplate(
@@ -749,6 +754,9 @@ export interface MaterializeCiOpenCodeDataOptions {
749
754
  // unless a platform person layer exists, which wins whole.
750
755
  modelsInput?: string;
751
756
  credentialsInput?: string;
757
+ // The `profile` input (openai-profile S6), a profile id from
758
+ // vars.CRYSK_PROFILE, written beside them. The platform's layer wins whole.
759
+ profileInput?: string;
752
760
  home?: string;
753
761
  env?: Readonly<Record<string, string | undefined>>;
754
762
  // Platform mode: the person layer the Crysk platform returned (`{}` when it
@@ -796,8 +804,12 @@ const INPUT_CLASS: Record<"models" | "credentials", ErrorClass> = {
796
804
  models: { kind: "config-parse", source: "models-input" },
797
805
  credentials: { kind: "config-parse", source: "credentials-input" },
798
806
  };
807
+ const PROFILE_INPUT_CLASS: ErrorClass = {
808
+ kind: "config-parse",
809
+ source: "profile-input",
810
+ };
799
811
  const INPUTS_IGNORED_WARNING =
800
- "The models and credentials inputs are ignored: this repository is connected to the Crysk platform, whose model settings apply.";
812
+ "The models, credentials and profile inputs are ignored: this repository is connected to the Crysk platform, whose model settings apply.";
801
813
 
802
814
  // A crysk-secrets, models or credentials input the user configured wrongly. `message` is the
803
815
  // line stderr has always printed; `cls` and `detail` are what the record carries.
@@ -853,6 +865,30 @@ export function openCodeProvidersOfModels(models: unknown): string[] {
853
865
  return [...providers].sort();
854
866
  }
855
867
 
868
+ // The OpenCode providers the person layer's routing runs on (openai-profile
869
+ // S6): its models', plus, for the roles `models` does not set (no `default`),
870
+ // its `profile`'s. A profile the parser refused never reaches here.
871
+ export function openCodeProvidersOfPerson(person: {
872
+ models?: unknown;
873
+ profile?: unknown;
874
+ }): string[] {
875
+ const providers = new Set(openCodeProvidersOfModels(person.models));
876
+ const models = person.models as Record<string, unknown> | undefined;
877
+ const coversEveryRole = models !== undefined && models.default !== undefined;
878
+ const profile =
879
+ typeof person.profile === "string" &&
880
+ Object.hasOwn(MODEL_PROFILES, person.profile)
881
+ ? MODEL_PROFILES[person.profile]
882
+ : undefined;
883
+ if (!coversEveryRole && profile !== undefined) {
884
+ for (const model of profileModels(profile)) {
885
+ const parsed = parseModelName(model);
886
+ if (parsed.backend === "opencode") providers.add(parsed.provider);
887
+ }
888
+ }
889
+ return [...providers].sort();
890
+ }
891
+
856
892
  // Whether an OpenCode route this run takes bills per token (cryskai/platform#12
857
893
  // item 5): an auth file exists AND some OpenCode provider among the run's
858
894
  // resolved routes, any step or fallback, binds an API key, by the same rule the
@@ -953,6 +989,23 @@ function assembleOpenCodeAuth(
953
989
  return { records, manifest, notices, problems };
954
990
  }
955
991
 
992
+ // The `profile` input: a bare id, not JSON, checked by the person parser like
993
+ // the key in ~/.crysk/config.json. Returns undefined for an empty input.
994
+ function readProfileInput(raw: string | undefined): string | undefined {
995
+ if (raw === undefined || raw.trim() === "") return undefined;
996
+ const profile = raw.trim();
997
+ try {
998
+ parseGlobalConfig(JSON.stringify({ profile }), "the profile input");
999
+ } catch (error) {
1000
+ throw new SetupInputError(
1001
+ PROFILE_INPUT_CLASS,
1002
+ "the profile input is not a known profile (the setup step's log names the known ones)",
1003
+ messageOf(error),
1004
+ );
1005
+ }
1006
+ return profile;
1007
+ }
1008
+
956
1009
  // One of the two inputs (D1), read the way the person parser reads that key in
957
1010
  // ~/.crysk/config.json: the value is the key's own object, checked under that
958
1011
  // key alone. Returns undefined for an empty input.
@@ -1024,9 +1077,11 @@ export async function materializeCiOpenCodeData(
1024
1077
  personBody = { ...platformPerson };
1025
1078
  // The inputs are not even read: a value the platform overrides is not this
1026
1079
  // run's configuration, so a malformed one must not fail it.
1027
- const inputGiven = [options.modelsInput, options.credentialsInput].some(
1028
- (raw) => raw !== undefined && raw.trim() !== "",
1029
- );
1080
+ const inputGiven = [
1081
+ options.modelsInput,
1082
+ options.credentialsInput,
1083
+ options.profileInput,
1084
+ ].some((raw) => raw !== undefined && raw.trim() !== "");
1030
1085
  if (inputGiven) warnings.push(INPUTS_IGNORED_WARNING);
1031
1086
  } else {
1032
1087
  const models = readConfigInput(options.modelsInput, "models");
@@ -1034,13 +1089,15 @@ export async function materializeCiOpenCodeData(
1034
1089
  options.credentialsInput,
1035
1090
  "credentials",
1036
1091
  );
1092
+ const profile = readProfileInput(options.profileInput);
1037
1093
  personBody = {
1038
1094
  ...(models === undefined ? {} : { models }),
1039
1095
  ...(credentials === undefined ? {} : { credentials }),
1096
+ ...(profile === undefined ? {} : { profile }),
1040
1097
  };
1041
1098
  }
1042
1099
 
1043
- const providers = openCodeProvidersOfModels(personBody.models);
1100
+ const providers = openCodeProvidersOfPerson(personBody);
1044
1101
  const notices: string[] = [];
1045
1102
  const assembly =
1046
1103
  options.cryskSecrets === undefined
@@ -1226,6 +1283,7 @@ async function runCiOpenCodeSetup(deps: CiOpenCodeSetupDeps): Promise<number> {
1226
1283
  env: deps.env,
1227
1284
  modelsInput: deps.env.MODELS_INPUT ?? "",
1228
1285
  credentialsInput: deps.env.CREDENTIALS_INPUT ?? "",
1286
+ profileInput: deps.env.PROFILE_INPUT ?? "",
1229
1287
  ...(platformMode ? { platformPerson: platform?.person ?? {} } : {}),
1230
1288
  ...(cryskSecrets === undefined ? {} : { cryskSecrets }),
1231
1289
  });
package/src/ci/trigger.ts CHANGED
@@ -19,8 +19,9 @@
19
19
  // ignored comment costs seconds instead of a dependency install. A package
20
20
  // import has no node_modules to resolve against yet, and a `#...` alias is no
21
21
  // better: it resolves to a src module whose own imports reach packages. Keep
22
- // every import here `node:` or `bun`, plus the import-free ../brand and
23
- // ./crysk-secrets (the CRYSK_* grammar, kept import-free for this step).
22
+ // every import here `node:` or `bun`, plus the import-free ../brand,
23
+ // ./crysk-secrets (the CRYSK_* grammar, kept import-free for this step) and the
24
+ // profile registry ../model/profiles.
24
25
 
25
26
  import { randomBytes } from "node:crypto";
26
27
  import {
@@ -33,6 +34,10 @@ import {
33
34
  } from "node:fs";
34
35
  import path from "node:path";
35
36
  import { commandHint, isCommand, startsWithCommand } from "../brand";
37
+ // The profile registry: data modules with no runtime imports of their own
38
+ // (test/architecture/profile-registry.test.ts), so the builtins-only rule
39
+ // still holds.
40
+ import { profileRunsOnlyOnOpenCode } from "../model/profiles";
36
41
  import {
37
42
  type CryskSecretsParse,
38
43
  cryskSecretsCarryCredential,
@@ -868,9 +873,20 @@ function lookupClass(decision: {
868
873
 
869
874
  // The route the run would have used. The trigger has no models text, only
870
875
  // whether the models in effect name OpenCode: the platform's, or else the
871
- // `models` input's (action.yml's HAS_OPENCODE_ROUTING, D1).
876
+ // `models` input's (action.yml's HAS_OPENCODE_ROUTING, D1). With no platform
877
+ // answer, a `profile` input whose every route is OpenCode names OpenCode too,
878
+ // unless a `models` default sends every role elsewhere (STANDALONE_*).
872
879
  function backendOf(deps: CiTriggerDeps): string {
873
- return deps.env.HAS_OPENCODE_ROUTING === "true" ? "opencode" : "claude";
880
+ if (deps.env.HAS_OPENCODE_ROUTING === "true") return "opencode";
881
+ // The platform answered (its person layer wins whole): the input is ignored.
882
+ if ((deps.env.PLATFORM_ROUTING_OPENCODE ?? "") !== "") return "claude";
883
+ if (
884
+ deps.env.STANDALONE_MODELS_DEFAULT !== "true" &&
885
+ profileRunsOnlyOnOpenCode(deps.env.STANDALONE_PROFILE)
886
+ ) {
887
+ return "opencode";
888
+ }
889
+ return "claude";
874
890
  }
875
891
 
876
892
  // The run's PR number, or why there is none. `malformed` is kept apart from a
@@ -19,7 +19,7 @@ import {
19
19
  appendIgnorePatterns,
20
20
  ignorePatternsError,
21
21
  OPENCODE_PROVIDERS_VARIABLE,
22
- openCodeProvidersOfModels,
22
+ openCodeProvidersOfPerson,
23
23
  runCiSetup,
24
24
  writeRepoReviewConfig,
25
25
  } from "#ci/setup";
@@ -186,6 +186,8 @@ interface WorkflowVariables {
186
186
  readonly configLabel: string;
187
187
  readonly hasModels: boolean;
188
188
  readonly hasCredentials: boolean;
189
+ // The person's `profile` (openai-profile S6), set as vars.CRYSK_PROFILE.
190
+ readonly profile?: string;
189
191
  // The OpenCode providers the models name, as secret tokens (DEEPSEEK), sorted.
190
192
  readonly openCodeTokens: readonly string[];
191
193
  }
@@ -202,8 +204,9 @@ async function readWorkflowVariables(
202
204
  ? `~/${path.relative(home, filePath)}`
203
205
  : filePath;
204
206
  // The judge is skipped and every fallback counts, the providers the setup step
205
- // builds the auth file for (openCodeProvidersOfModels).
206
- const providers = openCodeProvidersOfModels(layer?.models);
207
+ // builds the auth file for (openCodeProvidersOfPerson): the models', and the
208
+ // profile's for the roles models does not set.
209
+ const providers = openCodeProvidersOfPerson(layer ?? {});
207
210
  const unnamed = providers.filter(
208
211
  (provider) => opencodeSecretToken(provider) === undefined,
209
212
  );
@@ -229,6 +232,7 @@ async function readWorkflowVariables(
229
232
  variables: {
230
233
  configLabel,
231
234
  hasModels: layer?.models !== undefined,
235
+ ...(layer?.profile === undefined ? {} : { profile: layer.profile }),
232
236
  hasCredentials: layer?.credentials !== undefined,
233
237
  openCodeTokens,
234
238
  },
@@ -247,6 +251,11 @@ export function workflowVariableCommands(
247
251
  `$ gh variable set CRYSK_MODELS --body "$(jq -c .models ${variables.configLabel})"`,
248
252
  );
249
253
  }
254
+ if (variables.profile !== undefined) {
255
+ commands.push(
256
+ `$ gh variable set CRYSK_PROFILE --body ${variables.profile}`,
257
+ );
258
+ }
250
259
  if (variables.hasCredentials) {
251
260
  commands.push(
252
261
  `$ gh variable set CRYSK_CREDENTIALS --body "$(jq -c .credentials ${variables.configLabel})"`,
@@ -1,12 +1,13 @@
1
1
  import os from "node:os";
2
- import { loadEffectiveConfig, resolveOptionalRepoRoot } from "#config/config";
3
- import { type ModelsConfig, modelsNeedOpenCode } from "#model/model-name";
2
+ import { resolveOptionalRepoRoot } from "#config/config";
3
+ import { routingNeedsOpenCode } from "#model/model-name";
4
4
  import type { CliOptions } from "#review/preflight";
5
5
  import { styleEnabled, terminalWidth } from "#ui/primitives";
6
6
  import {
7
7
  type DoctorCheckItem,
8
8
  type DoctorReport,
9
9
  evaluateDoctorReport,
10
+ loadDoctorRouting,
10
11
  openCodeRoutingSdkCheck,
11
12
  renderDoctorReport,
12
13
  runDoctor,
@@ -38,41 +39,41 @@ export async function runDoctorCommand(input: {
38
39
  // the loader share. Tests pass a version without resolving a package.
39
40
  readSdkVersion?: () => Promise<string | undefined>;
40
41
  }): Promise<{ report: DoctorReport; lines: string[] }> {
41
- let models: ModelsConfig | undefined;
42
+ // Required unless the configuration loads and proves otherwise: a config
43
+ // that fails to load must not quietly excuse a missing Claude CLI.
44
+ const routing = await loadDoctorRouting({
45
+ home: input.home,
46
+ repoRoot: input.repoRoot,
47
+ configFlag: input.configFlag,
48
+ });
49
+ const { models, profile, claudeRequired } = routing;
42
50
  let configCheck: DoctorCheckItem | undefined;
43
- try {
44
- const loaded = await loadEffectiveConfig({
45
- root: input.repoRoot,
46
- home: input.home,
47
- configFlag: input.configFlag,
48
- });
49
- models = loaded.effective.models;
51
+ if (routing.error !== undefined) {
52
+ configCheck = {
53
+ name: "config",
54
+ severity: "blocking",
55
+ message: `configuration failed to load: ${routing.error}`,
56
+ };
57
+ } else if (routing.warnings.length > 0) {
50
58
  // A config that loads with warnings works today and will not after the
51
59
  // key it uses is removed: degraded, with the warning as its message.
52
- if (loaded.warnings.length > 0) {
53
- configCheck = {
54
- name: "config",
55
- severity: "degraded",
56
- message: loaded.warnings.join("\n"),
57
- };
58
- }
59
- } catch (error) {
60
60
  configCheck = {
61
61
  name: "config",
62
- severity: "blocking",
63
- message: `configuration failed to load: ${
64
- error instanceof Error ? error.message : String(error)
65
- }`,
62
+ severity: "degraded",
63
+ message: routing.warnings.join("\n"),
66
64
  };
67
65
  }
68
66
  const runDoctorFn = input.runDoctorFn ?? runDoctor;
69
67
  const doctorReport = await runDoctorFn({
70
68
  repoRoot: input.repoRoot,
71
69
  cwd: input.repoRoot,
70
+ claudeRequired,
72
71
  probeExactBindings: () =>
73
72
  collectDoctorExactBindingReports({
74
73
  workspaceRoot: input.workspaceRoot,
75
74
  models,
75
+ claudeRequired,
76
+ profile,
76
77
  }),
77
78
  });
78
79
  // Same home the command was given. The no-arg reader uses os.homedir().
@@ -82,9 +83,10 @@ export async function runDoctorCommand(input: {
82
83
  readInstalledOpenCodeSdkVersion({
83
84
  nodeModulesDir: prheroLayout(input.home).nodeModulesDir,
84
85
  }));
85
- const sdkCheck = modelsNeedOpenCode(models)
86
+ const sdkCheck = routingNeedsOpenCode(models, profile)
86
87
  ? openCodeRoutingSdkCheck({
87
88
  models,
89
+ profile,
88
90
  sdkVersion: await readSdkVersion(),
89
91
  })
90
92
  : undefined;
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { modelNameFromAlias } from "#model/model-name";
3
3
  import {
4
4
  agentStepKey,
5
+ type ResolvedModelRoute,
5
6
  type ResolvedStepRoute,
6
7
  resolveStepRoute,
7
8
  } from "#model/routing";
@@ -26,6 +27,11 @@ export interface DiversityLeg {
26
27
  readonly logicalModel: string;
27
28
  readonly model: string;
28
29
  readonly routeFingerprint: string;
30
+ // The route the leg resolved to, the one its routeFingerprint names. Not
31
+ // part of the plan payload (the fingerprint already is), so legIds and the
32
+ // plan fingerprint stay what they were. Provenance reads it when a step
33
+ // carries no executed route (S2).
34
+ readonly route: ResolvedModelRoute;
29
35
  readonly executionKey: string;
30
36
  readonly stepKey: string;
31
37
  }
@@ -130,7 +136,10 @@ export function buildDiversityPlan(
130
136
  const specialty = resolveSpecialty(agent);
131
137
  for (const model of models) {
132
138
  // A leg's model is internal: a bare alias or a full model name. Its
133
- // own model always wins over `models`, so the plan needs no `models`.
139
+ // own model is the step's spec model, which outranks `models`, the
140
+ // frontmatter and the profile in resolveStepChoices; only `--model`
141
+ // outranks it, and it is passed. So this is the route the run plan
142
+ // gives the leg's step, which assertDiversityLegRoutes checks (S2).
134
143
  const parsed = { canonical: modelNameFromAlias(model).raw };
135
144
  const provisionalKey = diversityLegAgentKey(
136
145
  agent.key,
@@ -158,6 +167,7 @@ export function buildDiversityPlan(
158
167
  logicalModel: model,
159
168
  model: parsed.canonical,
160
169
  routeFingerprint: stepRoute.routeFingerprint,
170
+ route: stepRoute.route,
161
171
  executionKey,
162
172
  stepKey,
163
173
  });
@@ -245,6 +245,24 @@ export function recordDiversityHunterFailure(
245
245
  return appendAttempt(ledger, attempt);
246
246
  }
247
247
 
248
+ // The route an observation names. A step carries no executed route only on
249
+ // the no-plan path, which runs every step on the Claude CLI, so the leg's own
250
+ // resolved route stands in when it is a Claude one. A non-Claude leg there has
251
+ // no observed execution to name, and labelling it Anthropic (as this did
252
+ // before S2) or with a route nobody ran would both be false: refuse.
253
+ function provenanceRoute(
254
+ leg: DiversityLeg,
255
+ executedRoute: ResolvedModelRoute | undefined,
256
+ ): ResolvedModelRoute {
257
+ if (executedRoute !== undefined) return executedRoute;
258
+ if (leg.route.backend !== "claude-code") {
259
+ throw new DiversityAdmissionError(
260
+ `no executed route for ${leg.route.backend} leg ${leg.legId}`,
261
+ );
262
+ }
263
+ return leg.route;
264
+ }
265
+
248
266
  export function recordDiversityHunterResult(
249
267
  ledger: DiversityLedger,
250
268
  plan: DiversityPlan,
@@ -290,12 +308,7 @@ export function recordDiversityHunterResult(
290
308
  }
291
309
  if (result.status !== "ok") return next;
292
310
  const terminalAttemptId = `${resolvedLeg.legId}-a${totalAttempts}`;
293
- const routeProvenance: ResolvedModelRoute = executedRoute ?? {
294
- backend: "claude-code",
295
- provider: "anthropic",
296
- modelFamily: resolvedLeg.model.split("/")[0] ?? "unknown",
297
- modelSnapshot: resolvedLeg.model,
298
- };
311
+ const routeProvenance = provenanceRoute(resolvedLeg, executedRoute);
299
312
  const output = result.output as { findings?: DraftFinding[] } | undefined;
300
313
  const findings = output?.findings ?? [];
301
314
  for (const [index, finding] of findings.entries()) {
package/src/doctor.ts CHANGED
@@ -1,17 +1,25 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
- import { type ModelsConfig, modelsNeedOpenCode } from "#model/model-name";
4
+ import { loadEffectiveConfig } from "#config/config";
5
+ import { type ModelsConfig, routingNeedsOpenCode } from "#model/model-name";
6
+ import {
7
+ FALLBACK_PROFILE,
8
+ type ModelProfile,
9
+ resolveProfile,
10
+ } from "#model/profiles";
5
11
  import {
6
12
  exactBindingCapabilityIssues,
7
13
  type ProviderCapabilityReport,
8
14
  } from "#model/provider-capabilities";
15
+ import { buildResolvedRoutePlan, planRoutes } from "#model/routing";
9
16
  import {
10
17
  agentFilePath,
11
18
  GOTCHAS_PLACEHOLDER_MARKER,
12
19
  gotchasUnusableReason,
13
20
  localReviewSpec,
14
21
  resolveAgentsDirSetting,
22
+ resolveMaterialityGate,
15
23
  } from "#review/preflight";
16
24
  import {
17
25
  REVIEW_MD_FILE_NAME,
@@ -30,6 +38,7 @@ import {
30
38
  resolveEngineAssets,
31
39
  selfInvocation,
32
40
  } from "./assets";
41
+ import { readBrandEnv } from "./brand";
33
42
  import { REPO_DIR_NAME, resolveHomeDir, resolveRepoDir } from "./brand-paths";
34
43
  import {
35
44
  gitIsTracked,
@@ -93,6 +102,108 @@ export interface RunDoctorOptions {
93
102
  // Legacy injectable ProviderCapabilityReport. Ignored when
94
103
  // probeExactBindings is provided.
95
104
  produceCapabilityReport?: () => Promise<ProviderCapabilityReport>;
105
+ // Whether any step the configuration resolves runs on the Claude CLI
106
+ // (reviewNeedsClaude). Absent: required, as every caller that does not
107
+ // resolve the configuration (the updater, the menu) has always had it.
108
+ claudeRequired?: boolean;
109
+ }
110
+
111
+ // Whether a review under this configuration sends any step to the Claude CLI
112
+ // (model-profiles S6): the route plan a review would build, every hunter of
113
+ // the bundled spec, the refuter, consolidate, scout, summarizer and, with the
114
+ // gate on, the materiality judge, resolved through `models` and the active
115
+ // profile. True whenever the answer is not proven: neither `models` nor a
116
+ // `profile`, a plan that fails to build, or a bad CRYSK_EXTRA_HUNTERS. So zero-config and
117
+ // every configuration naming a Claude model keep the CLI required.
118
+ export function reviewNeedsClaude(input: {
119
+ models: ModelsConfig | undefined;
120
+ // The config's `profile` (openai-profile S6). Absent: the fallback profile.
121
+ profile?: string;
122
+ // Whether a custom agents_dir applies (PR #521 R003). Its frontmatter
123
+ // outranks the profile's seat and is not read here, so with no
124
+ // `models.default` the answer stays "Claude required".
125
+ customAgents?: boolean;
126
+ materialityGate?: boolean;
127
+ env?: Record<string, string | undefined>;
128
+ }): boolean {
129
+ if (input.models === undefined && input.profile === undefined) return true;
130
+ if (input.customAgents === true && input.models?.default === undefined) {
131
+ return true;
132
+ }
133
+ try {
134
+ const plan = buildResolvedRoutePlan({
135
+ agents: localReviewSpec(input.env ?? process.env).agents,
136
+ models: input.models,
137
+ profile: resolveProfile(input.profile),
138
+ bundledAgents: true,
139
+ summarizer: { bundled: true },
140
+ scout: { bundled: true },
141
+ consolidate: { bundled: true },
142
+ // Unknown counts as on: the judge then joins only when it shares a
143
+ // backend with another step or `models.judge` names it.
144
+ ...(input.materialityGate === false
145
+ ? {}
146
+ : { materiality: true as const }),
147
+ });
148
+ // Fallbacks included: a step that falls back to Claude can start the CLI.
149
+ return planRoutes(plan).some(
150
+ (step) => step.route.backend === "claude-code",
151
+ );
152
+ } catch {
153
+ return true;
154
+ }
155
+ }
156
+
157
+ // What a doctor run reads from the configuration: whether any step needs the
158
+ // Claude CLI, and the models and profile its binding probe resolves
159
+ // (openai-profile S6). One reading for `crysk doctor`, `crysk update`, the
160
+ // menu and the wizard, so none of them asks a person who chose a profile with
161
+ // no Claude step for the Claude CLI. A config that fails to load keeps Claude
162
+ // required on the fallback profile, and `error` says why.
163
+ export interface DoctorRouting {
164
+ readonly claudeRequired: boolean;
165
+ readonly models?: ModelsConfig;
166
+ readonly profile: ModelProfile;
167
+ readonly warnings: readonly string[];
168
+ readonly error?: string;
169
+ }
170
+
171
+ export async function loadDoctorRouting(input: {
172
+ home: string;
173
+ repoRoot?: string | undefined;
174
+ configFlag?: string | undefined;
175
+ // The environment the AGENTS_DIR override is read from. Absent: the process's.
176
+ env?: Record<string, string | undefined>;
177
+ }): Promise<DoctorRouting> {
178
+ try {
179
+ const loaded = await loadEffectiveConfig({
180
+ root: input.repoRoot,
181
+ home: input.home,
182
+ configFlag: input.configFlag,
183
+ });
184
+ const { models, profile } = loaded.effective;
185
+ return {
186
+ claudeRequired: reviewNeedsClaude({
187
+ models,
188
+ ...(profile === undefined ? {} : { profile }),
189
+ customAgents:
190
+ loaded.effective.agents_dir !== undefined ||
191
+ (readBrandEnv(input.env ?? process.env, "AGENTS_DIR")?.value ??
192
+ "") !== "",
193
+ materialityGate: resolveMaterialityGate(loaded.effective),
194
+ }),
195
+ ...(models === undefined ? {} : { models }),
196
+ profile: resolveProfile(profile),
197
+ warnings: loaded.warnings,
198
+ };
199
+ } catch (error) {
200
+ return {
201
+ claudeRequired: true,
202
+ profile: FALLBACK_PROFILE,
203
+ warnings: [],
204
+ error: error instanceof Error ? error.message : String(error),
205
+ };
206
+ }
96
207
  }
97
208
 
98
209
  // Remediation hints for the report's known non-blocking codes; blocking
@@ -162,9 +273,13 @@ function pushProviderIssues(
162
273
 
163
274
  export function openCodeRoutingSdkCheck(input: {
164
275
  models: ModelsConfig | undefined;
276
+ // The configuration's profile (openai-profile S6). Absent: the fallback.
277
+ profile?: ModelProfile;
165
278
  sdkVersion: string | undefined;
166
279
  }): DoctorCheckItem | undefined {
167
- if (!modelsNeedOpenCode(input.models)) return undefined;
280
+ if (!routingNeedsOpenCode(input.models, input.profile ?? FALLBACK_PROFILE)) {
281
+ return undefined;
282
+ }
168
283
  const version =
169
284
  typeof input.sdkVersion === "string" ? input.sdkVersion.trim() : "";
170
285
  if (version === SUPPORTED_OPENCODE_SDK_VERSION) return undefined;
@@ -254,8 +369,22 @@ export async function runDoctor(
254
369
  });
255
370
  }
256
371
 
257
- // Claude (required + auth)
258
- if (!tools.claude.installed) {
372
+ // Claude (required + auth). Required unless the caller resolved the
373
+ // configuration and found no step on the Claude CLI (model-profiles S6,
374
+ // reviewNeedsClaude): then a missing or signed-out CLI is reported, but it
375
+ // blocks nothing, because no review would start it.
376
+ const claudeRequired = options.claudeRequired !== false;
377
+ if (!claudeRequired && !(tools.claude.installed && tools.claude.authOk)) {
378
+ checks.push({
379
+ name: "claude",
380
+ severity: "healthy",
381
+ message: `${
382
+ tools.claude.installed
383
+ ? `Claude Code CLI is installed (${tools.claude.version ?? "unknown"}) but not authenticated`
384
+ : "Claude Code CLI is not installed"
385
+ }; not needed, since no configured step runs on it`,
386
+ });
387
+ } else if (!tools.claude.installed) {
259
388
  checks.push({
260
389
  name: "claude",
261
390
  severity: "blocking",
@@ -237,12 +237,24 @@ export interface TransportOutcome {
237
237
  readonly exitCode?: number;
238
238
  }
239
239
 
240
- // The GitHub secrets a Claude review can run on (see TransportOutcome.failureCredential).
241
- // The CI record mirrors this list in src/ci/outcome.ts, tied by `satisfies`.
242
- export type FailureCredential =
240
+ // The secret a failed attempt ran on (see TransportOutcome.failureCredential).
241
+ //
242
+ // A Claude route names the Claude CLI's own variable; in the action the CI texts map it
243
+ // to the CRYSK_CLAUDE_* secret that filled it. The CI record mirrors this list in
244
+ // src/ci/outcome.ts, tied by `satisfies`.
245
+ export type ClaudeFailureCredential =
243
246
  | "ANTHROPIC_API_KEY"
244
247
  | "ANTHROPIC_AUTH_TOKEN"
245
248
  | "CLAUDE_CODE_OAUTH_TOKEN";
249
+ // An OpenCode route names its CRYSK_OPENCODE_* secret directly (S7): the name is per
250
+ // provider, built by opencodeSecretName (src/ci/crysk-secrets.ts) from the route's
251
+ // provider and credential kind. The CI record checks it against that grammar.
252
+ export type OpenCodeFailureCredential =
253
+ | `CRYSK_OPENCODE_${string}_API_KEY`
254
+ | `CRYSK_OPENCODE_${string}_OAUTH`;
255
+ export type FailureCredential =
256
+ | ClaudeFailureCredential
257
+ | OpenCodeFailureCredential;
246
258
 
247
259
  export type TransportFailureCause =
248
260
  | "auth_invalid"