crysk 0.4.0 → 0.5.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 (93) 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/gates.ts +22 -36
  26. package/src/ci/outcome.ts +421 -330
  27. package/src/ci/platform-config.ts +2 -2
  28. package/src/ci/platform-report.ts +274 -41
  29. package/src/ci/platform-trace.ts +551 -0
  30. package/src/ci/platform.ts +28 -12
  31. package/src/ci/publish.ts +19 -6
  32. package/src/ci/review-levels.ts +8 -7
  33. package/src/ci/run.ts +88 -0
  34. package/src/ci/setup.ts +453 -118
  35. package/src/ci/trace-bundle.ts +1282 -0
  36. package/src/ci/trace-transcripts.ts +415 -0
  37. package/src/ci/trigger.ts +176 -33
  38. package/src/cli.ts +11 -3
  39. package/src/commands/ci-setup-questions.ts +3 -3
  40. package/src/commands/ci-setup.ts +152 -6
  41. package/src/commands/config.ts +3 -0
  42. package/src/commands/doctor.ts +15 -6
  43. package/src/config/config.ts +16 -3
  44. package/src/diversity/clustering.ts +0 -1
  45. package/src/diversity/identity.ts +4 -5
  46. package/src/diversity/pipeline-integration.ts +1 -9
  47. package/src/doctor.ts +3 -3
  48. package/src/execution/attempt-evidence.ts +10 -5
  49. package/src/execution/claude-session-trace.ts +480 -0
  50. package/src/execution/contracts.ts +21 -4
  51. package/src/execution/harness.ts +105 -8
  52. package/src/execution/model-fallback.ts +239 -0
  53. package/src/execution/usage-normalized.ts +6 -4
  54. package/src/home-preflight.ts +1 -1
  55. package/src/index.ts +1 -1
  56. package/src/model/catalog.ts +13 -37
  57. package/src/model/free-discovery.ts +117 -8
  58. package/src/model/model-name.ts +404 -0
  59. package/src/model/provider-capabilities.ts +22 -7
  60. package/src/model/routing.ts +346 -467
  61. package/src/pr/admission.ts +18 -0
  62. package/src/pr/plan.ts +20 -4
  63. package/src/pr/preflight.ts +1 -1
  64. package/src/pr/publish-outcome.ts +1 -1
  65. package/src/pr/review-pr.ts +15 -1
  66. package/src/pr/target.ts +12 -3
  67. package/src/production-runtime.ts +760 -331
  68. package/src/review/pipeline.ts +277 -101
  69. package/src/review/preflight.ts +201 -294
  70. package/src/review/report.ts +26 -26
  71. package/src/review/review.ts +20 -3
  72. package/src/review/route-preflight.ts +79 -11
  73. package/src/review/run.ts +28 -6
  74. package/src/review/scout.ts +1 -1
  75. package/src/review/spec.ts +3 -3
  76. package/src/review/step-runner.ts +70 -1
  77. package/src/runner-authority.ts +127 -9
  78. package/src/security/binding-policy.ts +1 -2
  79. package/src/security/claude-credential.ts +355 -0
  80. package/src/security/credential-broker.ts +56 -40
  81. package/src/security/evidence-redaction.ts +179 -4
  82. package/src/security/opencode-secret-manifest.ts +114 -0
  83. package/src/security/redact.ts +45 -0
  84. package/src/system-tools.ts +48 -21
  85. package/src/transport-registry.ts +12 -2
  86. package/src/transports/claude-code-cli.ts +21 -2
  87. package/src/transports/opencode-sdk.ts +11 -9
  88. package/src/transports/opencode-server.ts +7 -10
  89. package/src/ui/config-edit.ts +9 -20
  90. package/src/ui/config.ts +32 -27
  91. package/src/ui/plan.ts +76 -47
  92. package/src/updater.ts +10 -7
  93. 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,
@@ -67,6 +88,11 @@ import { CliError } from "../errors";
67
88
  import { prheroLayout } from "../home-preflight";
68
89
  import { parseIgnoreFile } from "../ignore-file";
69
90
  import { resolveOpenCodeAuthPath } from "../security/credential-broker";
91
+ import {
92
+ type OpenCodeSecretManifestEntry,
93
+ openCodeSecretManifestPath,
94
+ serializeOpenCodeSecretManifest,
95
+ } from "../security/opencode-secret-manifest";
70
96
 
71
97
  // The file a repo with no workflow yet gets. A repo that already has the
72
98
  // pre-rename `pr-hero.yml` keeps it: use resolveWorkflowRelativePath to find the
@@ -144,6 +170,12 @@ export interface CiWorkflowTemplateOptions {
144
170
  // scaffolded file names the gate and does not inherit it silently. `advisory`
145
171
  // keeps the status green whatever the review finds, as before S4.
146
172
  mode?: "gate" | "advisory";
173
+ // U5 (odd/tasks/role-model-routing.md, S8): the only CRYSK_* secrets this
174
+ // workflow passes in the action's `crysk-secrets` input, one line each, with no
175
+ // OpenCode slots and no models or credentials input. Only THIS repo's own
176
+ // workflow sets it; unset, the scaffolded block (E-f F4) names the Claude pair,
177
+ // the OpenAI OAuth record, the OpenCode slots and the two variables.
178
+ cryskSecrets?: readonly string[];
147
179
  }
148
180
 
149
181
  export const DEFAULT_CI_ACTION_REF = "cryskai/crysk@v0";
@@ -165,14 +197,92 @@ export const DEFAULT_CI_ACTION_REF = "cryskai/crysk@v0";
165
197
  // no dollar cost to cap, so this repo opts out explicitly; fixing the
166
198
  // billing-mode resolution itself is a separate issue. `maxChangedLines`
167
199
  // stays: that gate is real on any route.
200
+ //
201
+ // `cryskSecrets` names the Claude pair (U5): the action stops a run that passes the
202
+ // removed inputs, so this repo's own review passes CRYSK_* secrets. The repository
203
+ // must hold them before the PR that brings this file runs its review.
168
204
  export const OWN_CI_WORKFLOW_OPTIONS: CiWorkflowTemplateOptions = {
169
205
  actionRef: "./",
170
206
  maxChangedLines: "5000",
171
207
  budgetUsd: "0",
172
208
  mode: "gate",
173
209
  forceEngineFromPr: true,
210
+ cryskSecrets: ["CRYSK_CLAUDE_OAUTH_TOKEN", "CRYSK_CLAUDE_API_KEY"],
174
211
  };
175
212
 
213
+ // The secrets every scaffolded workflow names: the Claude pair and the one OpenCode
214
+ // OAuth record the engine reads (OPENCODE_OAUTH_SECRET_PROVIDER), as the platform's
215
+ // stub names them. A secret the repository does not have arrives empty.
216
+ const SCAFFOLD_FIXED_SECRETS: readonly string[] = [
217
+ "CRYSK_CLAUDE_OAUTH_TOKEN",
218
+ "CRYSK_CLAUDE_API_KEY",
219
+ `CRYSK_OPENCODE_${opencodeSecretToken(OPENCODE_OAUTH_SECRET_PROVIDER)}_OAUTH`,
220
+ ];
221
+
222
+ // The repository variable listing the OpenCode providers a scaffolded workflow
223
+ // forwards keys for, as a JSON array of secret tokens (["DEEPSEEK"]). `crysk ci init`
224
+ // prints the command that sets it.
225
+ export const OPENCODE_PROVIDERS_VARIABLE = "CRYSK_OPENCODE_PROVIDERS";
226
+
227
+ // D2 (odd/tasks/role-model-routing.md L40-L42): slot i forwards
228
+ // CRYSK_OPENCODE_<token i>_API_KEY, the token read from the variable above, so a
229
+ // new provider needs a variable change, not a workflow edit. With the variable
230
+ // unset, or fewer providers than slots, a slot renders as `CRYSK_OPENCODE__API_KEY=`
231
+ // (verified on GitHub, run 42559256131), which the intake skips. The `|| '[]'`
232
+ // keeps an unset variable valid JSON for fromJSON.
233
+ function openCodeSlotLine(index: number): string {
234
+ const token = `fromJSON(vars.${OPENCODE_PROVIDERS_VARIABLE} || '[]')[${index}]`;
235
+ return `CRYSK_OPENCODE_\${{ ${token} }}_API_KEY=\${{ secrets[format('CRYSK_OPENCODE_{0}_API_KEY', ${token})] }}`;
236
+ }
237
+
238
+ // The credential lines of the Run Crysk step's `with:` block. A scaffolded repo
239
+ // gets every Claude and OpenCode line plus the models and credentials inputs from
240
+ // repository variables (D1, D2); this repo's own workflow names its secrets
241
+ // (`cryskSecrets`) and nothing else.
242
+ function credentialWithLines(options: CiWorkflowTemplateOptions): string {
243
+ const names = options.cryskSecrets ?? SCAFFOLD_FIXED_SECRETS;
244
+ const lines = [
245
+ ...names.map((name) => `${name}=\${{ secrets.${name} }}`),
246
+ ...(options.cryskSecrets === undefined
247
+ ? Array.from({ length: MAX_OPENCODE_PROVIDER_SLOTS }, (_, i) =>
248
+ openCodeSlotLine(i),
249
+ )
250
+ : []),
251
+ ]
252
+ .map((line) => ` ${line}`)
253
+ .join("\n");
254
+ const block = ` # The Crysk credentials: one CRYSK_* secret per line, each named
255
+ # explicitly (never the whole secrets context, which would hand the
256
+ # action every secret of the repository). A secret the repository does not have
257
+ # arrives empty and counts as absent, so every line stays. With
258
+ # both Claude secrets set, credentials.claude picks one (the subscription first).
259
+ # CRYSK_CLAUDE_OAUTH_TOKEN — from \`claude setup-token\`: a long-lived
260
+ # (~1 year) token that draws on your Claude subscription. The
261
+ # session token \`/login\` leaves in the keychain expires in hours.
262
+ # CRYSK_CLAUDE_API_KEY — pay-as-you-go key (billed per token).`;
263
+ if (options.cryskSecrets !== undefined) {
264
+ return `${block}
265
+ crysk-secrets: |
266
+ ${lines}`;
267
+ }
268
+ return `${block}
269
+ # CRYSK_OPENCODE_OPENAI_OAUTH — an OpenAI (ChatGPT) subscription for
270
+ # OpenCode: the openai record of OpenCode's auth.json, base64 on one line.
271
+ # CRYSK_OPENCODE_<PROVIDER>_API_KEY — an OpenCode provider's API key,
272
+ # <PROVIDER> being its id uppercased with - and . as _. The ${MAX_OPENCODE_PROVIDER_SLOTS}
273
+ # lines after the fixed ones forward the providers listed in
274
+ # vars.${OPENCODE_PROVIDERS_VARIABLE} (a JSON array, e.g. ["DEEPSEEK"]);
275
+ # an unused line renders as CRYSK_OPENCODE__API_KEY= and is skipped.
276
+ # \`crysk ci init\` prints the commands that set these secrets and variables.
277
+ crysk-secrets: |
278
+ ${lines}
279
+ # The models per role and the Claude credential order, as JSON, from
280
+ # repository variables. Unset, every role runs the default Claude model
281
+ # and the subscription is tried first.
282
+ ${MODELS_INPUT_LINE}
283
+ ${CREDENTIALS_INPUT_LINE}`;
284
+ }
285
+
176
286
  export function generateCiWorkflowTemplate(
177
287
  options: CiWorkflowTemplateOptions = {},
178
288
  ): string {
@@ -446,28 +556,7 @@ ${gateStep} - name: Checkout${checkoutGate}
446
556
  uses: ${actionRef}
447
557
  with:
448
558
  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}
559
+ ${credentialWithLines(options)}${sizeGateLine}${filesGateLine}${budgetLine}${modeLine}
471
560
  `;
472
561
  }
473
562
 
@@ -653,35 +742,63 @@ export async function appendIgnorePatterns(
653
742
  }
654
743
 
655
744
  export interface MaterializeCiOpenCodeDataOptions {
656
- routing?: string;
657
- opencodeAuth?: string;
745
+ // E-f F3 (D1): the `models` and `credentials` inputs, raw JSON text, which a
746
+ // standalone workflow fills from vars.CRYSK_MODELS and vars.CRYSK_CREDENTIALS.
747
+ // Read with the engine's person parser and written as the personal file,
748
+ // unless a platform person layer exists, which wins whole.
749
+ modelsInput?: string;
750
+ credentialsInput?: string;
658
751
  home?: string;
659
752
  env?: Readonly<Record<string, string | undefined>>;
660
753
  // 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
754
+ // sent none), written as the personal file. Present means platform mode, in which the
663
755
  // personal file belongs to this run: a file an earlier run left behind is
664
756
  // removed when nothing is to be written, so it can never be read as this run's
665
757
  // person layer on a runner whose HOME outlives the job.
666
758
  platformPerson?: Record<string, unknown>;
759
+ // U3: the parsed `crysk-secrets` input, when it was given. Its CRYSK_OPENCODE_*
760
+ // secrets build the OpenCode auth file for the providers the models in effect
761
+ // name.
762
+ cryskSecrets?: CryskSecretsParse;
763
+ }
764
+
765
+ export interface MaterializeCiOpenCodeDataResult {
766
+ // Notices for the job log: names and provider ids only, never a value.
767
+ readonly notices: readonly string[];
768
+ // Warnings for the job log, the same rule: the inputs a platform layer overrode.
769
+ readonly warnings: readonly string[];
770
+ // Whether this step wrote the OpenCode auth file from the CRYSK_OPENCODE_*
771
+ // secrets for the providers the models name. The Install OpenCode CLI step
772
+ // runs then (U5).
773
+ readonly openCodeAuthWritten: boolean;
774
+ // Whether the models in effect, the platform's or the inputs', run an
775
+ // OpenCode model (the judge's entries aside). The Install OpenCode CLI step
776
+ // runs then too, so a free model with no credential still gets the CLI.
777
+ readonly openCodeModels: boolean;
667
778
  }
668
779
 
669
780
  // The file the publisher reads when this step fails on a malformed input, and
670
781
  // the outcome directory the workflow binds for it (odd/tasks/agent-first-ci.md, A1).
671
782
  const SETUP_RECORD_FILE = "setup.json";
672
- const ROUTING_CLASS: ErrorClass = { kind: "config-parse", source: "routing" };
673
783
  const AUTH_CLASS: ErrorClass = {
674
784
  kind: "credential",
675
785
  failureClass: "malformed_payload",
676
786
  };
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
787
+ // The models and credentials inputs (D1): CRYSK-CONFIG-INVALID's `models-input`
788
+ // and `credentials-input` variants, each naming its own input and variable. Their
789
+ // details name the input and never its content (the
790
+ // variable may hold anything, a pasted key included), so the publisher can put
791
+ // them on the PR. The parser's own message, which names the entry, goes to the
792
+ // step's log only, through F2's redaction; a JSON syntax error's text is never
793
+ // printed, since it can quote the input.
794
+ const INPUT_CLASS: Record<"models" | "credentials", ErrorClass> = {
795
+ models: { kind: "config-parse", source: "models-input" },
796
+ credentials: { kind: "config-parse", source: "credentials-input" },
797
+ };
798
+ const INPUTS_IGNORED_WARNING =
799
+ "The models and credentials inputs are ignored: this repository is connected to the Crysk platform, whose model settings apply.";
800
+
801
+ // A crysk-secrets, models or credentials input the user configured wrongly. `message` is the
685
802
  // line stderr has always printed; `cls` and `detail` are what the record carries.
686
803
  class SetupInputError extends Error {
687
804
  readonly cls: ErrorClass;
@@ -699,15 +816,161 @@ function messageOf(error: unknown): string {
699
816
  return error instanceof Error ? error.message : "unknown error";
700
817
  }
701
818
 
702
- // CI data plane: person-layer routing + 0600 auth.json. HOME must be a real
819
+ // One owner-only write for every credential file this step leaves: the mode on
820
+ // create, and again by chmod, since an existing file keeps its old mode through
821
+ // writeFile.
822
+ async function writeOwnerOnlyFile(file: string, body: string): Promise<void> {
823
+ await mkdir(path.dirname(file), { recursive: true });
824
+ await writeFile(file, body, { mode: 0o600 });
825
+ await chmod(file, 0o600);
826
+ }
827
+
828
+ // The OpenCode providers the person layer's models name, every role and every
829
+ // fallback, sorted. The judge is skipped: it runs only claude: models (L6 item 5),
830
+ // so an opencode: entry there is dropped and never reaches the plan. `default` is
831
+ // counted even when every role overrides it (a record nobody reads costs nothing).
832
+ // Read through parseModelsConfig, the engine's own parser, so a change to the
833
+ // shape of a list entry (E-g) is a type error here, never a silent skip. Models
834
+ // that do not parse yield none; assertPlatformPerson and readConfigInput refuse
835
+ // them by name before this runs.
836
+ export function openCodeProvidersOfModels(models: unknown): string[] {
837
+ if (models === undefined) return [];
838
+ let config: ModelsConfig;
839
+ try {
840
+ config = parseModelsConfig(models);
841
+ } catch {
842
+ return [];
843
+ }
844
+ const providers = new Set<string>();
845
+ for (const [role, list] of Object.entries(config)) {
846
+ if (role === "judge") continue;
847
+ for (const entry of list) {
848
+ const parsed = parseModelName(modelEntry(entry).name);
849
+ if (parsed.backend === "opencode") providers.add(parsed.provider);
850
+ }
851
+ }
852
+ return [...providers].sort();
853
+ }
854
+
855
+ interface OpenCodeAuthAssembly {
856
+ // provider id -> its auth.json record.
857
+ readonly records: Record<string, Record<string, unknown>>;
858
+ readonly manifest: OpenCodeSecretManifestEntry[];
859
+ readonly notices: string[];
860
+ readonly problems: string[];
861
+ }
862
+
863
+ // U3 (S8/S9, L12 "Building auth.json"): the OpenCode auth file from the
864
+ // CRYSK_OPENCODE_* secrets, one record per provider the models name. Which
865
+ // secret serves a provider is chooseOpenCodeSecret, the rule credentialKindForRoute
866
+ // applies to the manifest's names in the run, so the record and the bound kind
867
+ // agree. `_API_KEY` becomes OpenCode's own API record; `_OAUTH` is the provider's
868
+ // login record kept whole, refresh token included, so the child can renew it.
869
+ function assembleOpenCodeAuth(
870
+ parse: CryskSecretsParse,
871
+ providers: readonly string[],
872
+ ): OpenCodeAuthAssembly {
873
+ const records: Record<string, Record<string, unknown>> = {};
874
+ const manifest: OpenCodeSecretManifestEntry[] = [];
875
+ const notices: string[] = [];
876
+ const problems: string[] = [];
877
+ const missing: string[] = [];
878
+ for (const provider of providers) {
879
+ const choice = chooseOpenCodeSecret(provider, parse.names);
880
+ if (choice === undefined) {
881
+ const token = opencodeSecretToken(provider);
882
+ missing.push(
883
+ token === undefined
884
+ ? `OpenCode provider ${provider}: no CRYSK_OPENCODE_* secret name can carry this provider id, so the auth file has no record for it.`
885
+ : `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.`,
886
+ );
887
+ continue;
888
+ }
889
+ if (choice.kind === undefined) {
890
+ problems.push(choice.problem);
891
+ continue;
892
+ }
893
+ const secrets = opencodeSecretsFor(parse.secrets, provider);
894
+ if (choice.kind === "oauth" && secrets?.oauth !== undefined) {
895
+ records[provider] = { ...secrets.oauth };
896
+ } else if (choice.kind === "api_key" && secrets?.apiKey !== undefined) {
897
+ records[provider] = { type: "api", key: secrets.apiKey };
898
+ } else {
899
+ // The names and the values come from one parse, so this cannot happen.
900
+ continue;
901
+ }
902
+ manifest.push({
903
+ provider,
904
+ secret: choice.secret,
905
+ kind: choice.kind,
906
+ ...(choice.unused === undefined ? {} : { unused: choice.unused }),
907
+ });
908
+ const label = choice.kind === "oauth" ? "subscription" : "API key";
909
+ notices.push(
910
+ choice.unused === undefined
911
+ ? `OpenCode provider ${provider}: ${choice.secret} (${label}) builds its auth record.`
912
+ : `OpenCode provider ${provider}: ${choice.secret} (${label}) builds its auth record; ${choice.unused} is not used, because the subscription comes first.`,
913
+ );
914
+ }
915
+ // A provider with no secret is named whenever the crysk-secrets input was given,
916
+ // also when no provider got a record and this step writes no auth file: a metered
917
+ // model of that provider is then refused at admission (openCodeCredentialRefusal,
918
+ // production-runtime.ts), and this line says why in the setup step. A notice, not a
919
+ // failure: a free model of that provider runs with no record.
920
+ notices.push(...missing);
921
+ return { records, manifest, notices, problems };
922
+ }
923
+
924
+ // One of the two inputs (D1), read the way the person parser reads that key in
925
+ // ~/.crysk/config.json: the value is the key's own object, checked under that
926
+ // key alone. Returns undefined for an empty input.
927
+ function readConfigInput(
928
+ raw: string | undefined,
929
+ key: "models" | "credentials",
930
+ ): unknown {
931
+ if (raw === undefined || raw.trim() === "") return undefined;
932
+ const label = `the ${key} input`;
933
+ let value: unknown;
934
+ try {
935
+ value = JSON.parse(raw);
936
+ } catch {
937
+ throw new SetupInputError(
938
+ INPUT_CLASS[key],
939
+ `${label} is not valid JSON`,
940
+ `CI ${key} input is not valid JSON`,
941
+ );
942
+ }
943
+ try {
944
+ parseGlobalConfig(JSON.stringify({ [key]: value }), label);
945
+ } catch (error) {
946
+ throw new SetupInputError(
947
+ INPUT_CLASS[key],
948
+ `${label} does not follow the ${key} rules (the setup step's log names the entry)`,
949
+ messageOf(error),
950
+ );
951
+ }
952
+ return value;
953
+ }
954
+
955
+ // CI data plane: the person layer + 0600 auth.json. HOME must be a real
703
956
  // directory — empty/unset fails loud with no cwd fallback, because falling
704
- // back would write routing into the checkout (.prhero/config.json), which
957
+ // back would write person keys into the checkout (.prhero/config.json), which
705
958
  // 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.
959
+ //
960
+ // The person layer in effect (D1): the platform's when it sent one, whole, with
961
+ // the models and credentials inputs ignored and a warning; otherwise the inputs,
962
+ // read with the person parser before anything is written. The `routing` and
963
+ // `opencode-auth` inputs are gone (S2, D6): the trigger stops a workflow that
964
+ // passes either, and this step does not read them.
965
+ //
966
+ // U3: the CRYSK_OPENCODE_* secrets build auth.json for the providers the models
967
+ // in effect name. A manifest beside it names the secret behind each record, for
968
+ // the run's credential kind. When they serve none, a manifest an earlier run left
969
+ // is removed, so it never describes a file it did not build, and an auth file
970
+ // already on the runner (a self-hosted runner's own) is left alone.
708
971
  export async function materializeCiOpenCodeData(
709
972
  options: MaterializeCiOpenCodeDataOptions = {},
710
- ): Promise<void> {
973
+ ): Promise<MaterializeCiOpenCodeDataResult> {
711
974
  const env = options.env ?? process.env;
712
975
  const home = options.home ?? env.HOME ?? "";
713
976
  if (home.trim() === "") {
@@ -716,81 +979,57 @@ export async function materializeCiOpenCodeData(
716
979
  );
717
980
  }
718
981
 
719
- const routingRaw = options.routing ?? env.ROUTING_INPUT ?? "";
720
- const authRaw = options.opencodeAuth ?? env.OPENCODE_AUTH_INPUT ?? "";
721
982
  const platformMode = options.platformPerson !== undefined;
722
983
  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;
984
+ const platformLayer = Object.keys(platformPerson).length > 0;
985
+ const personFile = prheroLayout(home).reviewConfigPath;
726
986
 
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
- }
987
+ const warnings: string[] = [];
988
+ let personBody: Record<string, unknown>;
989
+ if (platformLayer) {
990
+ // Validated whole by the engine's person parser before anything is written.
991
+ assertPlatformPerson(platformPerson, personFile);
992
+ personBody = { ...platformPerson };
993
+ // The inputs are not even read: a value the platform overrides is not this
994
+ // run's configuration, so a malformed one must not fail it.
995
+ const inputGiven = [options.modelsInput, options.credentialsInput].some(
996
+ (raw) => raw !== undefined && raw.trim() !== "",
997
+ );
998
+ if (inputGiven) warnings.push(INPUTS_IGNORED_WARNING);
999
+ } else {
1000
+ const models = readConfigInput(options.modelsInput, "models");
1001
+ const credentials = readConfigInput(
1002
+ options.credentialsInput,
1003
+ "credentials",
1004
+ );
1005
+ personBody = {
1006
+ ...(models === undefined ? {} : { models }),
1007
+ ...(credentials === undefined ? {} : { credentials }),
1008
+ };
757
1009
  }
758
1010
 
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;
1011
+ const providers = openCodeProvidersOfModels(personBody.models);
1012
+ const notices: string[] = [];
1013
+ const assembly =
1014
+ options.cryskSecrets === undefined
1015
+ ? undefined
1016
+ : assembleOpenCodeAuth(options.cryskSecrets, providers);
1017
+ if (assembly !== undefined && assembly.problems.length > 0) {
1018
+ const detail = assembly.problems.join("; ");
1019
+ throw new SetupInputError(
1020
+ AUTH_CLASS,
1021
+ detail,
1022
+ `CI crysk-secrets input: ${detail}`,
1023
+ );
783
1024
  }
1025
+ const fromSecrets =
1026
+ assembly !== undefined && assembly.manifest.length > 0
1027
+ ? assembly
1028
+ : undefined;
1029
+ // Also when no record was built: the notices then name only the providers with no
1030
+ // secret (assembleOpenCodeAuth).
1031
+ if (assembly !== undefined) notices.push(...assembly.notices);
784
1032
 
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
1033
  if (Object.keys(personBody).length > 0) {
795
1034
  await mkdir(path.dirname(personFile), { recursive: true });
796
1035
  await writeFile(personFile, `${JSON.stringify(personBody, null, 2)}\n`);
@@ -798,16 +1037,45 @@ export async function materializeCiOpenCodeData(
798
1037
  await rm(personFile, { force: true });
799
1038
  }
800
1039
 
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);
1040
+ const authPath = resolveOpenCodeAuthPath(env, home);
1041
+ const manifestPath = openCodeSecretManifestPath(authPath);
1042
+ if (fromSecrets !== undefined) {
1043
+ await writeOwnerOnlyFile(
1044
+ authPath,
1045
+ `${JSON.stringify(fromSecrets.records, null, 2)}\n`,
1046
+ );
1047
+ await writeOwnerOnlyFile(
1048
+ manifestPath,
1049
+ serializeOpenCodeSecretManifest(fromSecrets.manifest),
1050
+ );
1051
+ } else {
1052
+ await rm(manifestPath, { force: true });
806
1053
  }
1054
+ return {
1055
+ notices,
1056
+ warnings,
1057
+ openCodeAuthWritten: fromSecrets !== undefined,
1058
+ openCodeModels: providers.length > 0,
1059
+ };
807
1060
  }
808
1061
 
1062
+ // The env variable action.yml binds the `crysk-secrets` input to, in this step
1063
+ // only, for its shell. The shell pipes it to this script on stdin (the flag
1064
+ // below) and runs bun with the variable emptied, so it never enters this
1065
+ // process's environment. WHY not read it here and `delete process.env[...]`:
1066
+ // Bun.spawn without an explicit `env` (git's, on the platform path) gives the
1067
+ // child the environment the process STARTED with, so a deleted variable still
1068
+ // reaches it (probed on Bun 1.4.4). A non-empty variable here means the step was
1069
+ // wired wrongly, and the script refuses to run.
1070
+ const CRYSK_SECRETS_ENV = "CRYSK_SECRETS_INPUT";
1071
+ const CRYSK_SECRETS_STDIN_FLAG = "--crysk-secrets-stdin";
1072
+
809
1073
  interface CiOpenCodeSetupDeps {
810
1074
  env: Readonly<Record<string, string | undefined>>;
1075
+ // The `crysk-secrets` input, already removed from `env` and process.env.
1076
+ cryskSecrets: string;
1077
+ // Workflow commands (`::add-mask::`) go here, the way platform.ts emits them.
1078
+ stdout: (text: string) => void;
811
1079
  stderr: (text: string) => void;
812
1080
  // Where the checkout is (the engine resolves its operator root from here).
813
1081
  cwd: string;
@@ -873,11 +1141,47 @@ async function writeSetupRecord(
873
1141
  }
874
1142
  }
875
1143
 
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;
1144
+ // The `crysk-secrets` input (S8, L13). Every value is masked before this step
1145
+ // writes anything else, a refused input fails the step with a setup record,
1146
+ // and later steps learn only which credentials exist: names, Claude
1147
+ // kinds and OpenCode provider tokens, never a value, and never GITHUB_ENV.
1148
+ // Empty input: nothing is printed or written, exactly as before the input
1149
+ // existed. The OpenCode secrets build the auth file (U3, materializeCiOpenCodeData);
1150
+ // the Claude ones are not read here yet (U5).
1151
+ function intakeCryskSecrets(
1152
+ deps: CiOpenCodeSetupDeps,
1153
+ ): CryskSecretsParse | undefined {
1154
+ if (deps.cryskSecrets.trim() === "") return undefined;
1155
+ const parsed = parseCryskSecrets(deps.cryskSecrets);
1156
+ for (const value of parsed.masks) {
1157
+ deps.stdout(`::add-mask::${escapeCommandData(value)}\n`);
1158
+ }
1159
+ for (const notice of parsed.notices) {
1160
+ deps.stderr(`::notice::${escapeCommandData(notice)}\n`);
1161
+ }
1162
+ if (parsed.problems.length > 0) {
1163
+ const detail = parsed.problems.join("; ");
1164
+ throw new SetupInputError(
1165
+ AUTH_CLASS,
1166
+ detail,
1167
+ `CI crysk-secrets input: ${detail}`,
1168
+ );
1169
+ }
1170
+ const presence = cryskSecretsPresence(parsed);
1171
+ deps.appendOutput(
1172
+ `crysk-secrets=${presence.names.join(",")}\n` +
1173
+ `claude-credentials=${presence.claude.join(",")}\n` +
1174
+ `opencode-providers=${presence.opencodeProviders.join(",")}\n`,
1175
+ );
1176
+ return parsed;
1177
+ }
1178
+
1179
+ // The step's whole job. Returns the exit code. A malformed secrets, models or
1180
+ // credentials input is the user's configuration, so it also leaves setup.json for the publisher;
878
1181
  // any other failure (HOME, a write) stays unclassified, with no record.
879
1182
  async function runCiOpenCodeSetup(deps: CiOpenCodeSetupDeps): Promise<number> {
880
1183
  try {
1184
+ const cryskSecrets = intakeCryskSecrets(deps);
881
1185
  const platformFile = deps.env.CRYSK_PLATFORM_CONFIG_FILE ?? "";
882
1186
  const platform =
883
1187
  platformFile === "" ? undefined : readPlatformConfig(platformFile);
@@ -886,10 +1190,28 @@ async function runCiOpenCodeSetup(deps: CiOpenCodeSetupDeps): Promise<number> {
886
1190
  // presence boolean: it still owns the personal file (see the option).
887
1191
  const platformMode =
888
1192
  platform !== undefined || deps.env.CRYSK_PLATFORM_CONNECTED === "true";
889
- await materializeCiOpenCodeData({
1193
+ const materialized = await materializeCiOpenCodeData({
890
1194
  env: deps.env,
1195
+ modelsInput: deps.env.MODELS_INPUT ?? "",
1196
+ credentialsInput: deps.env.CREDENTIALS_INPUT ?? "",
891
1197
  ...(platformMode ? { platformPerson: platform?.person ?? {} } : {}),
1198
+ ...(cryskSecrets === undefined ? {} : { cryskSecrets }),
892
1199
  });
1200
+ for (const warning of materialized.warnings) {
1201
+ deps.stderr(`::warning::${escapeCommandData(warning)}\n`);
1202
+ }
1203
+ for (const notice of materialized.notices) {
1204
+ deps.stderr(`::notice::${escapeCommandData(notice)}\n`);
1205
+ }
1206
+ // Presence only: the Install OpenCode CLI step keys on these, so the CLI is
1207
+ // installed when an OpenCode credential the run can use was written, or when
1208
+ // the models in effect run an OpenCode model (a free one needs none).
1209
+ if (materialized.openCodeAuthWritten) {
1210
+ deps.appendOutput("opencode-auth-file=true\n");
1211
+ }
1212
+ if (materialized.openCodeModels) {
1213
+ deps.appendOutput("opencode-models=true\n");
1214
+ }
893
1215
  // WHY the run step needs to know: it passes `--post` whenever the `post`
894
1216
  // input is true (the default), and an explicit CLI option outranks the
895
1217
  // config, so a `post` the platform set would never take effect.
@@ -932,9 +1254,22 @@ async function runCiOpenCodeSetup(deps: CiOpenCodeSetupDeps): Promise<number> {
932
1254
  }
933
1255
 
934
1256
  if (import.meta.main) {
1257
+ if ((process.env[CRYSK_SECRETS_ENV] ?? "") !== "") {
1258
+ process.stderr.write(
1259
+ `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`,
1260
+ );
1261
+ process.exit(1);
1262
+ }
1263
+ const cryskSecrets = process.argv.includes(CRYSK_SECRETS_STDIN_FLAG)
1264
+ ? await Bun.stdin.text()
1265
+ : "";
935
1266
  process.exit(
936
1267
  await runCiOpenCodeSetup({
937
1268
  env: process.env,
1269
+ cryskSecrets,
1270
+ stdout: (text) => {
1271
+ process.stdout.write(text);
1272
+ },
938
1273
  stderr: (text) => {
939
1274
  process.stderr.write(text);
940
1275
  },