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
package/src/ci/setup.ts CHANGED
@@ -37,7 +37,22 @@ import {
37
37
  writeFile,
38
38
  } from "node:fs/promises";
39
39
  import path from "node:path";
40
- import type { ErrorClass, SetupRecord } from "#ci/outcome";
40
+ import {
41
+ type CryskSecretsParse,
42
+ chooseOpenCodeSecret,
43
+ cryskSecretsPresence,
44
+ MAX_OPENCODE_PROVIDER_SLOTS,
45
+ OPENCODE_OAUTH_SECRET_PROVIDER,
46
+ opencodeSecretsFor,
47
+ opencodeSecretToken,
48
+ parseCryskSecrets,
49
+ } from "#ci/crysk-secrets";
50
+ import {
51
+ CREDENTIALS_INPUT_LINE,
52
+ type ErrorClass,
53
+ MODELS_INPUT_LINE,
54
+ type SetupRecord,
55
+ } from "#ci/outcome";
41
56
  import { appendGithubOutput } from "#ci/platform";
42
57
  import {
43
58
  assertPlatformPerson,
@@ -53,7 +68,13 @@ import {
53
68
  recordTempPath,
54
69
  } from "#ci/trigger";
55
70
  import { resolveRepoRoot } from "#git/git";
56
- import { parseLocalConfig, parseRoutingConfig } from "#review/preflight";
71
+ import {
72
+ type ModelsConfig,
73
+ modelEntry,
74
+ parseModelName,
75
+ parseModelsConfig,
76
+ } from "#model/model-name";
77
+ import { parseGlobalConfig, parseLocalConfig } from "#review/preflight";
57
78
  import { commandForms } from "../brand";
58
79
  import {
59
80
  duplicateWorkflowProblem,
@@ -66,7 +87,13 @@ import {
66
87
  import { CliError } from "../errors";
67
88
  import { prheroLayout } from "../home-preflight";
68
89
  import { parseIgnoreFile } from "../ignore-file";
90
+ import { credentialKindForRoute } from "../runner-authority";
69
91
  import { resolveOpenCodeAuthPath } from "../security/credential-broker";
92
+ import {
93
+ type OpenCodeSecretManifestEntry,
94
+ openCodeSecretManifestPath,
95
+ serializeOpenCodeSecretManifest,
96
+ } from "../security/opencode-secret-manifest";
70
97
 
71
98
  // The file a repo with no workflow yet gets. A repo that already has the
72
99
  // pre-rename `pr-hero.yml` keeps it: use resolveWorkflowRelativePath to find the
@@ -144,6 +171,12 @@ export interface CiWorkflowTemplateOptions {
144
171
  // scaffolded file names the gate and does not inherit it silently. `advisory`
145
172
  // keeps the status green whatever the review finds, as before S4.
146
173
  mode?: "gate" | "advisory";
174
+ // U5 (odd/tasks/role-model-routing.md, S8): the only CRYSK_* secrets this
175
+ // workflow passes in the action's `crysk-secrets` input, one line each, with no
176
+ // OpenCode slots and no models or credentials input. Only THIS repo's own
177
+ // workflow sets it; unset, the scaffolded block (E-f F4) names the Claude pair,
178
+ // the OpenAI OAuth record, the OpenCode slots and the two variables.
179
+ cryskSecrets?: readonly string[];
147
180
  }
148
181
 
149
182
  export const DEFAULT_CI_ACTION_REF = "cryskai/crysk@v0";
@@ -165,14 +198,92 @@ export const DEFAULT_CI_ACTION_REF = "cryskai/crysk@v0";
165
198
  // no dollar cost to cap, so this repo opts out explicitly; fixing the
166
199
  // billing-mode resolution itself is a separate issue. `maxChangedLines`
167
200
  // stays: that gate is real on any route.
201
+ //
202
+ // `cryskSecrets` names the Claude pair (U5): the action stops a run that passes the
203
+ // removed inputs, so this repo's own review passes CRYSK_* secrets. The repository
204
+ // must hold them before the PR that brings this file runs its review.
168
205
  export const OWN_CI_WORKFLOW_OPTIONS: CiWorkflowTemplateOptions = {
169
206
  actionRef: "./",
170
207
  maxChangedLines: "5000",
171
208
  budgetUsd: "0",
172
209
  mode: "gate",
173
210
  forceEngineFromPr: true,
211
+ cryskSecrets: ["CRYSK_CLAUDE_OAUTH_TOKEN", "CRYSK_CLAUDE_API_KEY"],
174
212
  };
175
213
 
214
+ // The secrets every scaffolded workflow names: the Claude pair and the one OpenCode
215
+ // OAuth record the engine reads (OPENCODE_OAUTH_SECRET_PROVIDER), as the platform's
216
+ // stub names them. A secret the repository does not have arrives empty.
217
+ const SCAFFOLD_FIXED_SECRETS: readonly string[] = [
218
+ "CRYSK_CLAUDE_OAUTH_TOKEN",
219
+ "CRYSK_CLAUDE_API_KEY",
220
+ `CRYSK_OPENCODE_${opencodeSecretToken(OPENCODE_OAUTH_SECRET_PROVIDER)}_OAUTH`,
221
+ ];
222
+
223
+ // The repository variable listing the OpenCode providers a scaffolded workflow
224
+ // forwards keys for, as a JSON array of secret tokens (["DEEPSEEK"]). `crysk ci init`
225
+ // prints the command that sets it.
226
+ export const OPENCODE_PROVIDERS_VARIABLE = "CRYSK_OPENCODE_PROVIDERS";
227
+
228
+ // D2 (odd/tasks/role-model-routing.md L40-L42): slot i forwards
229
+ // CRYSK_OPENCODE_<token i>_API_KEY, the token read from the variable above, so a
230
+ // new provider needs a variable change, not a workflow edit. With the variable
231
+ // unset, or fewer providers than slots, a slot renders as `CRYSK_OPENCODE__API_KEY=`
232
+ // (verified on GitHub, run 42559256131), which the intake skips. The `|| '[]'`
233
+ // keeps an unset variable valid JSON for fromJSON.
234
+ function openCodeSlotLine(index: number): string {
235
+ const token = `fromJSON(vars.${OPENCODE_PROVIDERS_VARIABLE} || '[]')[${index}]`;
236
+ return `CRYSK_OPENCODE_\${{ ${token} }}_API_KEY=\${{ secrets[format('CRYSK_OPENCODE_{0}_API_KEY', ${token})] }}`;
237
+ }
238
+
239
+ // The credential lines of the Run Crysk step's `with:` block. A scaffolded repo
240
+ // gets every Claude and OpenCode line plus the models and credentials inputs from
241
+ // repository variables (D1, D2); this repo's own workflow names its secrets
242
+ // (`cryskSecrets`) and nothing else.
243
+ function credentialWithLines(options: CiWorkflowTemplateOptions): string {
244
+ const names = options.cryskSecrets ?? SCAFFOLD_FIXED_SECRETS;
245
+ const lines = [
246
+ ...names.map((name) => `${name}=\${{ secrets.${name} }}`),
247
+ ...(options.cryskSecrets === undefined
248
+ ? Array.from({ length: MAX_OPENCODE_PROVIDER_SLOTS }, (_, i) =>
249
+ openCodeSlotLine(i),
250
+ )
251
+ : []),
252
+ ]
253
+ .map((line) => ` ${line}`)
254
+ .join("\n");
255
+ const block = ` # The Crysk credentials: one CRYSK_* secret per line, each named
256
+ # explicitly (never the whole secrets context, which would hand the
257
+ # action every secret of the repository). A secret the repository does not have
258
+ # arrives empty and counts as absent, so every line stays. With
259
+ # both Claude secrets set, credentials.claude picks one (the subscription first).
260
+ # CRYSK_CLAUDE_OAUTH_TOKEN — from \`claude setup-token\`: a long-lived
261
+ # (~1 year) token that draws on your Claude subscription. The
262
+ # session token \`/login\` leaves in the keychain expires in hours.
263
+ # CRYSK_CLAUDE_API_KEY — pay-as-you-go key (billed per token).`;
264
+ if (options.cryskSecrets !== undefined) {
265
+ return `${block}
266
+ crysk-secrets: |
267
+ ${lines}`;
268
+ }
269
+ return `${block}
270
+ # CRYSK_OPENCODE_OPENAI_OAUTH — an OpenAI (ChatGPT) subscription for
271
+ # OpenCode: the openai record of OpenCode's auth.json, base64 on one line.
272
+ # CRYSK_OPENCODE_<PROVIDER>_API_KEY — an OpenCode provider's API key,
273
+ # <PROVIDER> being its id uppercased with - and . as _. The ${MAX_OPENCODE_PROVIDER_SLOTS}
274
+ # lines after the fixed ones forward the providers listed in
275
+ # vars.${OPENCODE_PROVIDERS_VARIABLE} (a JSON array, e.g. ["DEEPSEEK"]);
276
+ # an unused line renders as CRYSK_OPENCODE__API_KEY= and is skipped.
277
+ # \`crysk ci init\` prints the commands that set these secrets and variables.
278
+ crysk-secrets: |
279
+ ${lines}
280
+ # The models per role and the Claude credential order, as JSON, from
281
+ # repository variables. Unset, every role runs the default Claude model
282
+ # and the subscription is tried first.
283
+ ${MODELS_INPUT_LINE}
284
+ ${CREDENTIALS_INPUT_LINE}`;
285
+ }
286
+
176
287
  export function generateCiWorkflowTemplate(
177
288
  options: CiWorkflowTemplateOptions = {},
178
289
  ): string {
@@ -446,28 +557,7 @@ ${gateStep} - name: Checkout${checkoutGate}
446
557
  uses: ${actionRef}
447
558
  with:
448
559
  github-token: \${{ secrets.GITHUB_TOKEN }}
449
- # Provide a Claude credential and/or OpenCode auth (never leave every
450
- # credential blank). Inputs are wired unconditionally: an unset secret
451
- # or var expands to empty, which the action treats as absent, so
452
- # leaving the one you do not use in place costs nothing. Deleting the
453
- # line for the secret you DID set is what breaks — the credential
454
- # never reaches the action, and it fails to authenticate silently.
455
- # ANTHROPIC_API_KEY — pay-as-you-go key (billed per token via Anthropic Console), or
456
- # CLAUDE_CODE_OAUTH_TOKEN — from \`claude setup-token\`: a long-lived
457
- # (~1 year) token that draws on your Claude subscription at no
458
- # extra API cost. It must come from that command. The session
459
- # token \`/login\` leaves in the keychain expires in HOURS and is
460
- # kept alive by a refresh token CI does not have, so pasting that
461
- # one here yields a secret that works for a day and then breaks
462
- # reviews with no signal.
463
- # OPENCODE_AUTH_JSON — whole OpenCode auth.json store
464
- # vars.CRYSK_ROUTING — person-layer routing JSON; quoted so an
465
- # unset var is the empty string rather than broken YAML. The
466
- # older vars.PRHERO_ROUTING is read when this one is unset.
467
- anthropic-api-key: \${{ secrets.ANTHROPIC_API_KEY }}
468
- claude-token: \${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
469
- routing: "\${{ vars.CRYSK_ROUTING || vars.PRHERO_ROUTING }}"
470
- opencode-auth: \${{ secrets.OPENCODE_AUTH_JSON }}${sizeGateLine}${filesGateLine}${budgetLine}${modeLine}
560
+ ${credentialWithLines(options)}${sizeGateLine}${filesGateLine}${budgetLine}${modeLine}
471
561
  `;
472
562
  }
473
563
 
@@ -653,35 +743,63 @@ export async function appendIgnorePatterns(
653
743
  }
654
744
 
655
745
  export interface MaterializeCiOpenCodeDataOptions {
656
- routing?: string;
657
- opencodeAuth?: string;
746
+ // E-f F3 (D1): the `models` and `credentials` inputs, raw JSON text, which a
747
+ // standalone workflow fills from vars.CRYSK_MODELS and vars.CRYSK_CREDENTIALS.
748
+ // Read with the engine's person parser and written as the personal file,
749
+ // unless a platform person layer exists, which wins whole.
750
+ modelsInput?: string;
751
+ credentialsInput?: string;
658
752
  home?: string;
659
753
  env?: Readonly<Record<string, string | undefined>>;
660
754
  // Platform mode: the person layer the Crysk platform returned (`{}` when it
661
- // sent none). Written into the same personal file as `routing`; its own
662
- // `routing` wins over the input. Present means platform mode, in which the
755
+ // sent none), written as the personal file. Present means platform mode, in which the
663
756
  // personal file belongs to this run: a file an earlier run left behind is
664
757
  // removed when nothing is to be written, so it can never be read as this run's
665
758
  // person layer on a runner whose HOME outlives the job.
666
759
  platformPerson?: Record<string, unknown>;
760
+ // U3: the parsed `crysk-secrets` input, when it was given. Its CRYSK_OPENCODE_*
761
+ // secrets build the OpenCode auth file for the providers the models in effect
762
+ // name.
763
+ cryskSecrets?: CryskSecretsParse;
764
+ }
765
+
766
+ export interface MaterializeCiOpenCodeDataResult {
767
+ // Notices for the job log: names and provider ids only, never a value.
768
+ readonly notices: readonly string[];
769
+ // Warnings for the job log, the same rule: the inputs a platform layer overrode.
770
+ readonly warnings: readonly string[];
771
+ // Whether this step wrote the OpenCode auth file from the CRYSK_OPENCODE_*
772
+ // secrets for the providers the models name. The Install OpenCode CLI step
773
+ // runs then (U5).
774
+ readonly openCodeAuthWritten: boolean;
775
+ // Whether the models in effect, the platform's or the inputs', run an
776
+ // OpenCode model (the judge's entries aside). The Install OpenCode CLI step
777
+ // runs then too, so a free model with no credential still gets the CLI.
778
+ readonly openCodeModels: boolean;
667
779
  }
668
780
 
669
781
  // The file the publisher reads when this step fails on a malformed input, and
670
782
  // the outcome directory the workflow binds for it (odd/tasks/agent-first-ci.md, A1).
671
783
  const SETUP_RECORD_FILE = "setup.json";
672
- const ROUTING_CLASS: ErrorClass = { kind: "config-parse", source: "routing" };
673
784
  const AUTH_CLASS: ErrorClass = {
674
785
  kind: "credential",
675
786
  failureClass: "malformed_payload",
676
787
  };
677
- // The details the record carries. Each names the input that is wrong and never
678
- // its content, so a secret or a routing value cannot reach the PR.
679
- const ROUTING_NOT_JSON = "the routing input is not valid JSON";
680
- const ROUTING_NOT_OBJECT = "the routing input is not a valid routing object";
681
- const AUTH_NOT_JSON = "the opencode-auth input is not valid JSON";
682
- const AUTH_NOT_OBJECT = "the opencode-auth input must be a JSON object";
683
-
684
- // A routing or OpenCode auth input the user configured wrongly. `message` is the
788
+ // The models and credentials inputs (D1): CRYSK-CONFIG-INVALID's `models-input`
789
+ // and `credentials-input` variants, each naming its own input and variable. Their
790
+ // details name the input and never its content (the
791
+ // variable may hold anything, a pasted key included), so the publisher can put
792
+ // them on the PR. The parser's own message, which names the entry, goes to the
793
+ // step's log only, through F2's redaction; a JSON syntax error's text is never
794
+ // printed, since it can quote the input.
795
+ const INPUT_CLASS: Record<"models" | "credentials", ErrorClass> = {
796
+ models: { kind: "config-parse", source: "models-input" },
797
+ credentials: { kind: "config-parse", source: "credentials-input" },
798
+ };
799
+ const INPUTS_IGNORED_WARNING =
800
+ "The models and credentials inputs are ignored: this repository is connected to the Crysk platform, whose model settings apply.";
801
+
802
+ // A crysk-secrets, models or credentials input the user configured wrongly. `message` is the
685
803
  // line stderr has always printed; `cls` and `detail` are what the record carries.
686
804
  class SetupInputError extends Error {
687
805
  readonly cls: ErrorClass;
@@ -699,15 +817,192 @@ function messageOf(error: unknown): string {
699
817
  return error instanceof Error ? error.message : "unknown error";
700
818
  }
701
819
 
702
- // CI data plane: person-layer routing + 0600 auth.json. HOME must be a real
820
+ // One owner-only write for every credential file this step leaves: the mode on
821
+ // create, and again by chmod, since an existing file keeps its old mode through
822
+ // writeFile.
823
+ async function writeOwnerOnlyFile(file: string, body: string): Promise<void> {
824
+ await mkdir(path.dirname(file), { recursive: true });
825
+ await writeFile(file, body, { mode: 0o600 });
826
+ await chmod(file, 0o600);
827
+ }
828
+
829
+ // The OpenCode providers the person layer's models name, every role and every
830
+ // fallback, sorted. The judge is skipped: it runs only claude: models (L6 item 5),
831
+ // so an opencode: entry there is dropped and never reaches the plan. `default` is
832
+ // counted even when every role overrides it (a record nobody reads costs nothing).
833
+ // Read through parseModelsConfig, the engine's own parser, so a change to the
834
+ // shape of a list entry (E-g) is a type error here, never a silent skip. Models
835
+ // that do not parse yield none; assertPlatformPerson and readConfigInput refuse
836
+ // them by name before this runs.
837
+ export function openCodeProvidersOfModels(models: unknown): string[] {
838
+ if (models === undefined) return [];
839
+ let config: ModelsConfig;
840
+ try {
841
+ config = parseModelsConfig(models);
842
+ } catch {
843
+ return [];
844
+ }
845
+ const providers = new Set<string>();
846
+ for (const [role, list] of Object.entries(config)) {
847
+ if (role === "judge") continue;
848
+ for (const entry of list) {
849
+ const parsed = parseModelName(modelEntry(entry).name);
850
+ if (parsed.backend === "opencode") providers.add(parsed.provider);
851
+ }
852
+ }
853
+ return [...providers].sort();
854
+ }
855
+
856
+ // Whether an OpenCode route this run takes bills per token (cryskai/platform#12
857
+ // item 5): an auth file exists AND some OpenCode provider among the run's
858
+ // resolved routes, any step or fallback, binds an API key, by the same rule the
859
+ // run binds it with (credentialKindForRoute over the secret manifest's names, the
860
+ // provider literal without one). `providers` comes from the run's own route plan,
861
+ // so every source routing reads counts (`models`, `--model`, `--scout-model`, a
862
+ // spec model, a prompt's frontmatter, the engine's defaults). Undefined means the
863
+ // routes could not be resolved here: the auth file decides, the old rule, which
864
+ // keeps the ceiling. The file alone is not enough otherwise: it also exists for a
865
+ // ChatGPT subscription, after an earlier run on a runner whose HOME persists, or
866
+ // from a local `opencode auth login`. And no file means no credential for a
867
+ // per-token route, as before: a free `opencode/*` model stays unmetered.
868
+ export function openCodeRoutesBillMetered(input: {
869
+ providers: readonly string[] | undefined;
870
+ authFilePresent: boolean;
871
+ openCodeSecretNames: readonly string[] | undefined;
872
+ }): boolean {
873
+ if (!input.authFilePresent) return false;
874
+ if (input.providers === undefined) return true;
875
+ return input.providers.some(
876
+ (provider) =>
877
+ credentialKindForRoute(
878
+ "opencode",
879
+ provider,
880
+ {},
881
+ false,
882
+ input.openCodeSecretNames,
883
+ ) === "provider_api_token",
884
+ );
885
+ }
886
+
887
+ interface OpenCodeAuthAssembly {
888
+ // provider id -> its auth.json record.
889
+ readonly records: Record<string, Record<string, unknown>>;
890
+ readonly manifest: OpenCodeSecretManifestEntry[];
891
+ readonly notices: string[];
892
+ readonly problems: string[];
893
+ }
894
+
895
+ // U3 (S8/S9, L12 "Building auth.json"): the OpenCode auth file from the
896
+ // CRYSK_OPENCODE_* secrets, one record per provider the models name. Which
897
+ // secret serves a provider is chooseOpenCodeSecret, the rule credentialKindForRoute
898
+ // applies to the manifest's names in the run, so the record and the bound kind
899
+ // agree. `_API_KEY` becomes OpenCode's own API record; `_OAUTH` is the provider's
900
+ // login record kept whole, refresh token included, so the child can renew it.
901
+ function assembleOpenCodeAuth(
902
+ parse: CryskSecretsParse,
903
+ providers: readonly string[],
904
+ ): OpenCodeAuthAssembly {
905
+ const records: Record<string, Record<string, unknown>> = {};
906
+ const manifest: OpenCodeSecretManifestEntry[] = [];
907
+ const notices: string[] = [];
908
+ const problems: string[] = [];
909
+ const missing: string[] = [];
910
+ for (const provider of providers) {
911
+ const choice = chooseOpenCodeSecret(provider, parse.names);
912
+ if (choice === undefined) {
913
+ const token = opencodeSecretToken(provider);
914
+ missing.push(
915
+ token === undefined
916
+ ? `OpenCode provider ${provider}: no CRYSK_OPENCODE_* secret name can carry this provider id, so the auth file has no record for it.`
917
+ : `OpenCode provider ${provider}: no CRYSK_OPENCODE_${token}_API_KEY or CRYSK_OPENCODE_${token}_OAUTH secret is set, so the auth file has no record for it.`,
918
+ );
919
+ continue;
920
+ }
921
+ if (choice.kind === undefined) {
922
+ problems.push(choice.problem);
923
+ continue;
924
+ }
925
+ const secrets = opencodeSecretsFor(parse.secrets, provider);
926
+ if (choice.kind === "oauth" && secrets?.oauth !== undefined) {
927
+ records[provider] = { ...secrets.oauth };
928
+ } else if (choice.kind === "api_key" && secrets?.apiKey !== undefined) {
929
+ records[provider] = { type: "api", key: secrets.apiKey };
930
+ } else {
931
+ // The names and the values come from one parse, so this cannot happen.
932
+ continue;
933
+ }
934
+ manifest.push({
935
+ provider,
936
+ secret: choice.secret,
937
+ kind: choice.kind,
938
+ ...(choice.unused === undefined ? {} : { unused: choice.unused }),
939
+ });
940
+ const label = choice.kind === "oauth" ? "subscription" : "API key";
941
+ notices.push(
942
+ choice.unused === undefined
943
+ ? `OpenCode provider ${provider}: ${choice.secret} (${label}) builds its auth record.`
944
+ : `OpenCode provider ${provider}: ${choice.secret} (${label}) builds its auth record; ${choice.unused} is not used, because the subscription comes first.`,
945
+ );
946
+ }
947
+ // A provider with no secret is named whenever the crysk-secrets input was given,
948
+ // also when no provider got a record and this step writes no auth file: a metered
949
+ // model of that provider is then refused at admission (openCodeCredentialRefusal,
950
+ // production-runtime.ts), and this line says why in the setup step. A notice, not a
951
+ // failure: a free model of that provider runs with no record.
952
+ notices.push(...missing);
953
+ return { records, manifest, notices, problems };
954
+ }
955
+
956
+ // One of the two inputs (D1), read the way the person parser reads that key in
957
+ // ~/.crysk/config.json: the value is the key's own object, checked under that
958
+ // key alone. Returns undefined for an empty input.
959
+ function readConfigInput(
960
+ raw: string | undefined,
961
+ key: "models" | "credentials",
962
+ ): unknown {
963
+ if (raw === undefined || raw.trim() === "") return undefined;
964
+ const label = `the ${key} input`;
965
+ let value: unknown;
966
+ try {
967
+ value = JSON.parse(raw);
968
+ } catch {
969
+ throw new SetupInputError(
970
+ INPUT_CLASS[key],
971
+ `${label} is not valid JSON`,
972
+ `CI ${key} input is not valid JSON`,
973
+ );
974
+ }
975
+ try {
976
+ parseGlobalConfig(JSON.stringify({ [key]: value }), label);
977
+ } catch (error) {
978
+ throw new SetupInputError(
979
+ INPUT_CLASS[key],
980
+ `${label} does not follow the ${key} rules (the setup step's log names the entry)`,
981
+ messageOf(error),
982
+ );
983
+ }
984
+ return value;
985
+ }
986
+
987
+ // CI data plane: the person layer + 0600 auth.json. HOME must be a real
703
988
  // directory — empty/unset fails loud with no cwd fallback, because falling
704
- // back would write routing into the checkout (.prhero/config.json), which
989
+ // back would write person keys into the checkout (.prhero/config.json), which
705
990
  // the repo parser rejects. Never log the auth blob; never inject readerFn.
706
- // In platform mode the platform's person layer joins the routing in that one
707
- // file; `routing` is the platform's when it sent one, else the input's, as today.
991
+ //
992
+ // The person layer in effect (D1): the platform's when it sent one, whole, with
993
+ // the models and credentials inputs ignored and a warning; otherwise the inputs,
994
+ // read with the person parser before anything is written. The `routing` and
995
+ // `opencode-auth` inputs are gone (S2, D6): the trigger stops a workflow that
996
+ // passes either, and this step does not read them.
997
+ //
998
+ // U3: the CRYSK_OPENCODE_* secrets build auth.json for the providers the models
999
+ // in effect name. A manifest beside it names the secret behind each record, for
1000
+ // the run's credential kind. When they serve none, a manifest an earlier run left
1001
+ // is removed, so it never describes a file it did not build, and an auth file
1002
+ // already on the runner (a self-hosted runner's own) is left alone.
708
1003
  export async function materializeCiOpenCodeData(
709
1004
  options: MaterializeCiOpenCodeDataOptions = {},
710
- ): Promise<void> {
1005
+ ): Promise<MaterializeCiOpenCodeDataResult> {
711
1006
  const env = options.env ?? process.env;
712
1007
  const home = options.home ?? env.HOME ?? "";
713
1008
  if (home.trim() === "") {
@@ -716,81 +1011,57 @@ export async function materializeCiOpenCodeData(
716
1011
  );
717
1012
  }
718
1013
 
719
- const routingRaw = options.routing ?? env.ROUTING_INPUT ?? "";
720
- const authRaw = options.opencodeAuth ?? env.OPENCODE_AUTH_INPUT ?? "";
721
1014
  const platformMode = options.platformPerson !== undefined;
722
1015
  const platformPerson = options.platformPerson ?? {};
723
- // The input is parsed only when it is the one that will be written: a
724
- // routing the platform overrides is not this run's configuration.
725
- const platformRouting = platformPerson.routing !== undefined;
1016
+ const platformLayer = Object.keys(platformPerson).length > 0;
1017
+ const personFile = prheroLayout(home).reviewConfigPath;
726
1018
 
727
- let routingConfig: ReturnType<typeof parseRoutingConfig> | null = null;
728
- if (routingRaw.trim() !== "" && !platformRouting) {
729
- let parsed: unknown;
730
- try {
731
- parsed = JSON.parse(routingRaw);
732
- } catch (error) {
733
- throw new SetupInputError(
734
- ROUTING_CLASS,
735
- ROUTING_NOT_JSON,
736
- `CI routing input is not valid JSON: ${messageOf(error)}`,
737
- );
738
- }
739
- try {
740
- routingConfig = parseRoutingConfig(parsed, "~/.crysk/config.json");
741
- } catch (error) {
742
- // parseRoutingConfig names the offending key in its message: that message
743
- // stays on stderr, and the record carries only the fixed detail.
744
- throw new SetupInputError(
745
- ROUTING_CLASS,
746
- ROUTING_NOT_OBJECT,
747
- messageOf(error),
748
- );
749
- }
750
- if (routingConfig === undefined) {
751
- throw new SetupInputError(
752
- ROUTING_CLASS,
753
- ROUTING_NOT_OBJECT,
754
- "CI routing input must be a JSON object",
755
- );
756
- }
1019
+ const warnings: string[] = [];
1020
+ let personBody: Record<string, unknown>;
1021
+ if (platformLayer) {
1022
+ // Validated whole by the engine's person parser before anything is written.
1023
+ assertPlatformPerson(platformPerson, personFile);
1024
+ personBody = { ...platformPerson };
1025
+ // The inputs are not even read: a value the platform overrides is not this
1026
+ // 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
+ );
1030
+ if (inputGiven) warnings.push(INPUTS_IGNORED_WARNING);
1031
+ } else {
1032
+ const models = readConfigInput(options.modelsInput, "models");
1033
+ const credentials = readConfigInput(
1034
+ options.credentialsInput,
1035
+ "credentials",
1036
+ );
1037
+ personBody = {
1038
+ ...(models === undefined ? {} : { models }),
1039
+ ...(credentials === undefined ? {} : { credentials }),
1040
+ };
757
1041
  }
758
1042
 
759
- let authBody: string | undefined;
760
- if (authRaw.trim() !== "") {
761
- let parsed: unknown;
762
- try {
763
- parsed = JSON.parse(authRaw);
764
- } catch {
765
- throw new SetupInputError(
766
- AUTH_CLASS,
767
- AUTH_NOT_JSON,
768
- "CI opencode-auth is not valid JSON",
769
- );
770
- }
771
- if (
772
- typeof parsed !== "object" ||
773
- parsed === null ||
774
- Array.isArray(parsed)
775
- ) {
776
- throw new SetupInputError(
777
- AUTH_CLASS,
778
- AUTH_NOT_OBJECT,
779
- "CI opencode-auth must be a JSON object",
780
- );
781
- }
782
- authBody = authRaw;
1043
+ const providers = openCodeProvidersOfModels(personBody.models);
1044
+ const notices: string[] = [];
1045
+ const assembly =
1046
+ options.cryskSecrets === undefined
1047
+ ? undefined
1048
+ : assembleOpenCodeAuth(options.cryskSecrets, providers);
1049
+ if (assembly !== undefined && assembly.problems.length > 0) {
1050
+ const detail = assembly.problems.join("; ");
1051
+ throw new SetupInputError(
1052
+ AUTH_CLASS,
1053
+ detail,
1054
+ `CI crysk-secrets input: ${detail}`,
1055
+ );
783
1056
  }
1057
+ const fromSecrets =
1058
+ assembly !== undefined && assembly.manifest.length > 0
1059
+ ? assembly
1060
+ : undefined;
1061
+ // Also when no record was built: the notices then name only the providers with no
1062
+ // secret (assembleOpenCodeAuth).
1063
+ if (assembly !== undefined) notices.push(...assembly.notices);
784
1064
 
785
- const personFile = prheroLayout(home).reviewConfigPath;
786
- // Validated whole by the engine's person parser before anything is written.
787
- if (Object.keys(platformPerson).length > 0) {
788
- assertPlatformPerson(platformPerson, personFile);
789
- }
790
- const personBody: Record<string, unknown> = {
791
- ...platformPerson,
792
- ...(routingConfig === null ? {} : { routing: routingConfig }),
793
- };
794
1065
  if (Object.keys(personBody).length > 0) {
795
1066
  await mkdir(path.dirname(personFile), { recursive: true });
796
1067
  await writeFile(personFile, `${JSON.stringify(personBody, null, 2)}\n`);
@@ -798,16 +1069,45 @@ export async function materializeCiOpenCodeData(
798
1069
  await rm(personFile, { force: true });
799
1070
  }
800
1071
 
801
- if (authBody !== undefined) {
802
- const authPath = resolveOpenCodeAuthPath(env, home);
803
- await mkdir(path.dirname(authPath), { recursive: true });
804
- await writeFile(authPath, authBody, { mode: 0o600 });
805
- await chmod(authPath, 0o600);
1072
+ const authPath = resolveOpenCodeAuthPath(env, home);
1073
+ const manifestPath = openCodeSecretManifestPath(authPath);
1074
+ if (fromSecrets !== undefined) {
1075
+ await writeOwnerOnlyFile(
1076
+ authPath,
1077
+ `${JSON.stringify(fromSecrets.records, null, 2)}\n`,
1078
+ );
1079
+ await writeOwnerOnlyFile(
1080
+ manifestPath,
1081
+ serializeOpenCodeSecretManifest(fromSecrets.manifest),
1082
+ );
1083
+ } else {
1084
+ await rm(manifestPath, { force: true });
806
1085
  }
1086
+ return {
1087
+ notices,
1088
+ warnings,
1089
+ openCodeAuthWritten: fromSecrets !== undefined,
1090
+ openCodeModels: providers.length > 0,
1091
+ };
807
1092
  }
808
1093
 
1094
+ // The env variable action.yml binds the `crysk-secrets` input to, in this step
1095
+ // only, for its shell. The shell pipes it to this script on stdin (the flag
1096
+ // below) and runs bun with the variable emptied, so it never enters this
1097
+ // process's environment. WHY not read it here and `delete process.env[...]`:
1098
+ // Bun.spawn without an explicit `env` (git's, on the platform path) gives the
1099
+ // child the environment the process STARTED with, so a deleted variable still
1100
+ // reaches it (probed on Bun 1.4.4). A non-empty variable here means the step was
1101
+ // wired wrongly, and the script refuses to run.
1102
+ const CRYSK_SECRETS_ENV = "CRYSK_SECRETS_INPUT";
1103
+ const CRYSK_SECRETS_STDIN_FLAG = "--crysk-secrets-stdin";
1104
+
809
1105
  interface CiOpenCodeSetupDeps {
810
1106
  env: Readonly<Record<string, string | undefined>>;
1107
+ // The `crysk-secrets` input, already removed from `env` and process.env.
1108
+ cryskSecrets: string;
1109
+ // Workflow commands (`::add-mask::`) go here, the way platform.ts emits them.
1110
+ stdout: (text: string) => void;
811
1111
  stderr: (text: string) => void;
812
1112
  // Where the checkout is (the engine resolves its operator root from here).
813
1113
  cwd: string;
@@ -873,11 +1173,47 @@ async function writeSetupRecord(
873
1173
  }
874
1174
  }
875
1175
 
876
- // The step's whole job. Returns the exit code. A malformed routing or auth input
877
- // is the user's configuration, so it also leaves setup.json for the publisher;
1176
+ // The `crysk-secrets` input (S8, L13). Every value is masked before this step
1177
+ // writes anything else, a refused input fails the step with a setup record,
1178
+ // and later steps learn only which credentials exist: names, Claude
1179
+ // kinds and OpenCode provider tokens, never a value, and never GITHUB_ENV.
1180
+ // Empty input: nothing is printed or written, exactly as before the input
1181
+ // existed. The OpenCode secrets build the auth file (U3, materializeCiOpenCodeData);
1182
+ // the Claude ones are not read here yet (U5).
1183
+ function intakeCryskSecrets(
1184
+ deps: CiOpenCodeSetupDeps,
1185
+ ): CryskSecretsParse | undefined {
1186
+ if (deps.cryskSecrets.trim() === "") return undefined;
1187
+ const parsed = parseCryskSecrets(deps.cryskSecrets);
1188
+ for (const value of parsed.masks) {
1189
+ deps.stdout(`::add-mask::${escapeCommandData(value)}\n`);
1190
+ }
1191
+ for (const notice of parsed.notices) {
1192
+ deps.stderr(`::notice::${escapeCommandData(notice)}\n`);
1193
+ }
1194
+ if (parsed.problems.length > 0) {
1195
+ const detail = parsed.problems.join("; ");
1196
+ throw new SetupInputError(
1197
+ AUTH_CLASS,
1198
+ detail,
1199
+ `CI crysk-secrets input: ${detail}`,
1200
+ );
1201
+ }
1202
+ const presence = cryskSecretsPresence(parsed);
1203
+ deps.appendOutput(
1204
+ `crysk-secrets=${presence.names.join(",")}\n` +
1205
+ `claude-credentials=${presence.claude.join(",")}\n` +
1206
+ `opencode-providers=${presence.opencodeProviders.join(",")}\n`,
1207
+ );
1208
+ return parsed;
1209
+ }
1210
+
1211
+ // The step's whole job. Returns the exit code. A malformed secrets, models or
1212
+ // credentials input is the user's configuration, so it also leaves setup.json for the publisher;
878
1213
  // any other failure (HOME, a write) stays unclassified, with no record.
879
1214
  async function runCiOpenCodeSetup(deps: CiOpenCodeSetupDeps): Promise<number> {
880
1215
  try {
1216
+ const cryskSecrets = intakeCryskSecrets(deps);
881
1217
  const platformFile = deps.env.CRYSK_PLATFORM_CONFIG_FILE ?? "";
882
1218
  const platform =
883
1219
  platformFile === "" ? undefined : readPlatformConfig(platformFile);
@@ -886,10 +1222,28 @@ async function runCiOpenCodeSetup(deps: CiOpenCodeSetupDeps): Promise<number> {
886
1222
  // presence boolean: it still owns the personal file (see the option).
887
1223
  const platformMode =
888
1224
  platform !== undefined || deps.env.CRYSK_PLATFORM_CONNECTED === "true";
889
- await materializeCiOpenCodeData({
1225
+ const materialized = await materializeCiOpenCodeData({
890
1226
  env: deps.env,
1227
+ modelsInput: deps.env.MODELS_INPUT ?? "",
1228
+ credentialsInput: deps.env.CREDENTIALS_INPUT ?? "",
891
1229
  ...(platformMode ? { platformPerson: platform?.person ?? {} } : {}),
1230
+ ...(cryskSecrets === undefined ? {} : { cryskSecrets }),
892
1231
  });
1232
+ for (const warning of materialized.warnings) {
1233
+ deps.stderr(`::warning::${escapeCommandData(warning)}\n`);
1234
+ }
1235
+ for (const notice of materialized.notices) {
1236
+ deps.stderr(`::notice::${escapeCommandData(notice)}\n`);
1237
+ }
1238
+ // Presence only: the Install OpenCode CLI step keys on these, so the CLI is
1239
+ // installed when an OpenCode credential the run can use was written, or when
1240
+ // the models in effect run an OpenCode model (a free one needs none).
1241
+ if (materialized.openCodeAuthWritten) {
1242
+ deps.appendOutput("opencode-auth-file=true\n");
1243
+ }
1244
+ if (materialized.openCodeModels) {
1245
+ deps.appendOutput("opencode-models=true\n");
1246
+ }
893
1247
  // WHY the run step needs to know: it passes `--post` whenever the `post`
894
1248
  // input is true (the default), and an explicit CLI option outranks the
895
1249
  // config, so a `post` the platform set would never take effect.
@@ -932,9 +1286,22 @@ async function runCiOpenCodeSetup(deps: CiOpenCodeSetupDeps): Promise<number> {
932
1286
  }
933
1287
 
934
1288
  if (import.meta.main) {
1289
+ if ((process.env[CRYSK_SECRETS_ENV] ?? "") !== "") {
1290
+ process.stderr.write(
1291
+ `crysk: the crysk-secrets input reached setup.ts through its environment, which every child it spawns would inherit; pipe it on stdin with ${CRYSK_SECRETS_STDIN_FLAG} and run bun with ${CRYSK_SECRETS_ENV} empty.\n`,
1292
+ );
1293
+ process.exit(1);
1294
+ }
1295
+ const cryskSecrets = process.argv.includes(CRYSK_SECRETS_STDIN_FLAG)
1296
+ ? await Bun.stdin.text()
1297
+ : "";
935
1298
  process.exit(
936
1299
  await runCiOpenCodeSetup({
937
1300
  env: process.env,
1301
+ cryskSecrets,
1302
+ stdout: (text) => {
1303
+ process.stdout.write(text);
1304
+ },
938
1305
  stderr: (text) => {
939
1306
  process.stderr.write(text);
940
1307
  },