crysk 0.3.3 → 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 (116) hide show
  1. package/README.md +26 -17
  2. package/config/models/anthropic.json +1 -1
  3. package/dist/SKILL-dsnffnfp.md +140 -0
  4. package/dist/SKILL-gnrbph72.md +140 -0
  5. package/dist/SKILL-k4k0zn1w.md +143 -0
  6. package/dist/SKILL-kq0xejn3.md +553 -0
  7. package/dist/SKILL-qaqsbygw.md +66 -0
  8. package/dist/SKILL-vhb4c3vv.md +553 -0
  9. package/dist/SKILL-vws0aqb8.md +553 -0
  10. package/dist/SKILL-xpf6kmdw.md +74 -0
  11. package/dist/ci-admission-0ken6ehx.md +128 -0
  12. package/dist/ci-admission-t0f5qwth.md +128 -0
  13. package/dist/cli.js +3366 -1680
  14. package/dist/index.js +1884 -947
  15. package/dist/opencode-ci-ac5zksdn.md +106 -0
  16. package/dist/workflow-4pkyck01.yml +160 -0
  17. package/package.json +2 -2
  18. package/prompts/default/PROVENANCE.md +1 -0
  19. package/skills/crysk/SKILL.md +16 -16
  20. package/skills/crysk-ci-setup/SKILL.md +42 -39
  21. package/skills/crysk-ci-setup/assets/workflow.yml +31 -22
  22. package/skills/crysk-ci-setup/references/ci-admission.md +2 -2
  23. package/skills/crysk-ci-setup/references/opencode-ci.md +53 -88
  24. package/skills/crysk-loop/SKILL.md +20 -9
  25. package/skills/crysk-pr/SKILL.md +1 -1
  26. package/src/asset-manifest.ts +0 -4
  27. package/src/assets.ts +2 -2
  28. package/src/ci/admission-ledger.ts +4 -0
  29. package/src/ci/classify-error.ts +21 -24
  30. package/src/ci/cli-record.ts +53 -1
  31. package/src/ci/crysk-secrets.ts +409 -0
  32. package/src/ci/gates.ts +31 -42
  33. package/src/ci/outcome.ts +421 -330
  34. package/src/ci/platform-config.ts +127 -0
  35. package/src/ci/platform-report.ts +935 -0
  36. package/src/ci/platform-trace.ts +551 -0
  37. package/src/ci/platform.ts +465 -0
  38. package/src/ci/publish.ts +19 -6
  39. package/src/ci/reporter.ts +9 -7
  40. package/src/ci/review-admission.ts +8 -4
  41. package/src/ci/review-levels.ts +8 -7
  42. package/src/ci/run.ts +88 -0
  43. package/src/ci/setup.ts +547 -109
  44. package/src/ci/trace-bundle.ts +1282 -0
  45. package/src/ci/trace-transcripts.ts +415 -0
  46. package/src/ci/trigger.ts +176 -33
  47. package/src/cli.ts +11 -3
  48. package/src/commands/ci-setup-questions.ts +3 -3
  49. package/src/commands/ci-setup.ts +152 -6
  50. package/src/commands/config.ts +3 -0
  51. package/src/commands/doctor.ts +15 -6
  52. package/src/compare/loop.ts +9 -1
  53. package/src/compare/martian-adapter.ts +1 -1
  54. package/src/config/config.ts +16 -3
  55. package/src/diversity/clustering.ts +0 -1
  56. package/src/diversity/identity.ts +4 -5
  57. package/src/diversity/pipeline-integration.ts +1 -9
  58. package/src/doctor.ts +3 -3
  59. package/src/execution/attempt-evidence.ts +10 -5
  60. package/src/execution/claude-session-trace.ts +480 -0
  61. package/src/execution/contracts.ts +21 -4
  62. package/src/execution/harness.ts +105 -8
  63. package/src/execution/model-fallback.ts +239 -0
  64. package/src/execution/usage-normalized.ts +6 -4
  65. package/src/home-preflight.ts +1 -1
  66. package/src/index.ts +1 -1
  67. package/src/model/catalog.ts +13 -37
  68. package/src/model/free-discovery.ts +117 -8
  69. package/src/model/model-name.ts +404 -0
  70. package/src/model/provider-capabilities.ts +22 -7
  71. package/src/model/routing.ts +346 -467
  72. package/src/pr/admission.ts +71 -11
  73. package/src/pr/ci-admission-gate.ts +2 -1
  74. package/src/pr/finding-state-record.ts +58 -0
  75. package/src/pr/gate-record.ts +22 -0
  76. package/src/pr/inline.ts +3 -0
  77. package/src/pr/plan.ts +20 -4
  78. package/src/pr/posting.ts +4 -0
  79. package/src/pr/pr-status.ts +27 -7
  80. package/src/pr/pr.ts +39 -8
  81. package/src/pr/preflight.ts +44 -2
  82. package/src/pr/publish-outcome.ts +11 -3
  83. package/src/pr/review-pr.ts +20 -4
  84. package/src/pr/target.ts +12 -3
  85. package/src/production-runtime.ts +760 -331
  86. package/src/rereview/classify.ts +4 -0
  87. package/src/rereview/prepare.ts +47 -22
  88. package/src/rereview/state.ts +34 -8
  89. package/src/review/pipeline.ts +277 -101
  90. package/src/review/preflight.ts +201 -294
  91. package/src/review/report.ts +60 -40
  92. package/src/review/review.ts +20 -3
  93. package/src/review/route-preflight.ts +79 -11
  94. package/src/review/run.ts +28 -6
  95. package/src/review/scout.ts +1 -1
  96. package/src/review/spec.ts +3 -3
  97. package/src/review/step-runner.ts +70 -1
  98. package/src/runner-authority.ts +127 -9
  99. package/src/security/binding-policy.ts +1 -2
  100. package/src/security/claude-credential.ts +355 -0
  101. package/src/security/credential-broker.ts +56 -40
  102. package/src/security/evidence-redaction.ts +179 -4
  103. package/src/security/opencode-secret-manifest.ts +114 -0
  104. package/src/security/published-text.ts +161 -0
  105. package/src/security/redact.ts +45 -0
  106. package/src/system-tools.ts +48 -21
  107. package/src/transport-registry.ts +12 -2
  108. package/src/transports/claude-code-cli.ts +21 -2
  109. package/src/transports/opencode-sdk.ts +11 -9
  110. package/src/transports/opencode-server.ts +7 -10
  111. package/src/triage/triage.ts +2 -1
  112. package/src/ui/config-edit.ts +9 -20
  113. package/src/ui/config.ts +32 -27
  114. package/src/ui/plan.ts +76 -47
  115. package/src/updater.ts +10 -7
  116. package/prompts/default/deep-review-lifecycle.md +0 -362
package/src/ci/setup.ts CHANGED
@@ -37,7 +37,29 @@ 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";
56
+ import { appendGithubOutput } from "#ci/platform";
57
+ import {
58
+ assertPlatformPerson,
59
+ deliverPlatformRepoLayer,
60
+ PlatformConfigError,
61
+ readPlatformConfig,
62
+ } from "#ci/platform-config";
41
63
  import type { ConfigPlan } from "#ci/review-levels";
42
64
  import {
43
65
  OVERRIDE_COMMAND,
@@ -45,7 +67,14 @@ import {
45
67
  REVIEW_COMMAND,
46
68
  recordTempPath,
47
69
  } from "#ci/trigger";
48
- import { parseLocalConfig, parseRoutingConfig } from "#review/preflight";
70
+ import { resolveRepoRoot } from "#git/git";
71
+ import {
72
+ type ModelsConfig,
73
+ modelEntry,
74
+ parseModelName,
75
+ parseModelsConfig,
76
+ } from "#model/model-name";
77
+ import { parseGlobalConfig, parseLocalConfig } from "#review/preflight";
49
78
  import { commandForms } from "../brand";
50
79
  import {
51
80
  duplicateWorkflowProblem,
@@ -59,6 +88,11 @@ import { CliError } from "../errors";
59
88
  import { prheroLayout } from "../home-preflight";
60
89
  import { parseIgnoreFile } from "../ignore-file";
61
90
  import { resolveOpenCodeAuthPath } from "../security/credential-broker";
91
+ import {
92
+ type OpenCodeSecretManifestEntry,
93
+ openCodeSecretManifestPath,
94
+ serializeOpenCodeSecretManifest,
95
+ } from "../security/opencode-secret-manifest";
62
96
 
63
97
  // The file a repo with no workflow yet gets. A repo that already has the
64
98
  // pre-rename `pr-hero.yml` keeps it: use resolveWorkflowRelativePath to find the
@@ -136,6 +170,12 @@ export interface CiWorkflowTemplateOptions {
136
170
  // scaffolded file names the gate and does not inherit it silently. `advisory`
137
171
  // keeps the status green whatever the review finds, as before S4.
138
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[];
139
179
  }
140
180
 
141
181
  export const DEFAULT_CI_ACTION_REF = "cryskai/crysk@v0";
@@ -157,14 +197,92 @@ export const DEFAULT_CI_ACTION_REF = "cryskai/crysk@v0";
157
197
  // no dollar cost to cap, so this repo opts out explicitly; fixing the
158
198
  // billing-mode resolution itself is a separate issue. `maxChangedLines`
159
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.
160
204
  export const OWN_CI_WORKFLOW_OPTIONS: CiWorkflowTemplateOptions = {
161
205
  actionRef: "./",
162
206
  maxChangedLines: "5000",
163
207
  budgetUsd: "0",
164
208
  mode: "gate",
165
209
  forceEngineFromPr: true,
210
+ cryskSecrets: ["CRYSK_CLAUDE_OAUTH_TOKEN", "CRYSK_CLAUDE_API_KEY"],
166
211
  };
167
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
+
168
286
  export function generateCiWorkflowTemplate(
169
287
  options: CiWorkflowTemplateOptions = {},
170
288
  ): string {
@@ -438,28 +556,7 @@ ${gateStep} - name: Checkout${checkoutGate}
438
556
  uses: ${actionRef}
439
557
  with:
440
558
  github-token: \${{ secrets.GITHUB_TOKEN }}
441
- # Provide a Claude credential and/or OpenCode auth (never leave every
442
- # credential blank). Inputs are wired unconditionally: an unset secret
443
- # or var expands to empty, which the action treats as absent, so
444
- # leaving the one you do not use in place costs nothing. Deleting the
445
- # line for the secret you DID set is what breaks — the credential
446
- # never reaches the action, and it fails to authenticate silently.
447
- # ANTHROPIC_API_KEY — pay-as-you-go key (billed per token via Anthropic Console), or
448
- # CLAUDE_CODE_OAUTH_TOKEN — from \`claude setup-token\`: a long-lived
449
- # (~1 year) token that draws on your Claude subscription at no
450
- # extra API cost. It must come from that command. The session
451
- # token \`/login\` leaves in the keychain expires in HOURS and is
452
- # kept alive by a refresh token CI does not have, so pasting that
453
- # one here yields a secret that works for a day and then breaks
454
- # reviews with no signal.
455
- # OPENCODE_AUTH_JSON — whole OpenCode auth.json store
456
- # vars.CRYSK_ROUTING — person-layer routing JSON; quoted so an
457
- # unset var is the empty string rather than broken YAML. The
458
- # older vars.PRHERO_ROUTING is read when this one is unset.
459
- anthropic-api-key: \${{ secrets.ANTHROPIC_API_KEY }}
460
- claude-token: \${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
461
- routing: "\${{ vars.CRYSK_ROUTING || vars.PRHERO_ROUTING }}"
462
- opencode-auth: \${{ secrets.OPENCODE_AUTH_JSON }}${sizeGateLine}${filesGateLine}${budgetLine}${modeLine}
559
+ ${credentialWithLines(options)}${sizeGateLine}${filesGateLine}${budgetLine}${modeLine}
463
560
  `;
464
561
  }
465
562
 
@@ -645,28 +742,63 @@ export async function appendIgnorePatterns(
645
742
  }
646
743
 
647
744
  export interface MaterializeCiOpenCodeDataOptions {
648
- routing?: string;
649
- 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;
650
751
  home?: string;
651
752
  env?: Readonly<Record<string, string | undefined>>;
753
+ // Platform mode: the person layer the Crysk platform returned (`{}` when it
754
+ // sent none), written as the personal file. Present means platform mode, in which the
755
+ // personal file belongs to this run: a file an earlier run left behind is
756
+ // removed when nothing is to be written, so it can never be read as this run's
757
+ // person layer on a runner whose HOME outlives the job.
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;
652
778
  }
653
779
 
654
780
  // The file the publisher reads when this step fails on a malformed input, and
655
781
  // the outcome directory the workflow binds for it (odd/tasks/agent-first-ci.md, A1).
656
782
  const SETUP_RECORD_FILE = "setup.json";
657
- const ROUTING_CLASS: ErrorClass = { kind: "config-parse", source: "routing" };
658
783
  const AUTH_CLASS: ErrorClass = {
659
784
  kind: "credential",
660
785
  failureClass: "malformed_payload",
661
786
  };
662
- // The details the record carries. Each names the input that is wrong and never
663
- // its content, so a secret or a routing value cannot reach the PR.
664
- const ROUTING_NOT_JSON = "the routing input is not valid JSON";
665
- const ROUTING_NOT_OBJECT = "the routing input is not a valid routing object";
666
- const AUTH_NOT_JSON = "the opencode-auth input is not valid JSON";
667
- const AUTH_NOT_OBJECT = "the opencode-auth input must be a JSON object";
668
-
669
- // 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
670
802
  // line stderr has always printed; `cls` and `detail` are what the record carries.
671
803
  class SetupInputError extends Error {
672
804
  readonly cls: ErrorClass;
@@ -684,13 +816,161 @@ function messageOf(error: unknown): string {
684
816
  return error instanceof Error ? error.message : "unknown error";
685
817
  }
686
818
 
687
- // 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
688
956
  // directory — empty/unset fails loud with no cwd fallback, because falling
689
- // back would write routing into the checkout (.prhero/config.json), which
957
+ // back would write person keys into the checkout (.prhero/config.json), which
690
958
  // the repo parser rejects. Never log the auth blob; never inject readerFn.
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.
691
971
  export async function materializeCiOpenCodeData(
692
972
  options: MaterializeCiOpenCodeDataOptions = {},
693
- ): Promise<void> {
973
+ ): Promise<MaterializeCiOpenCodeDataResult> {
694
974
  const env = options.env ?? process.env;
695
975
  const home = options.home ?? env.HOME ?? "";
696
976
  if (home.trim() === "") {
@@ -699,87 +979,146 @@ export async function materializeCiOpenCodeData(
699
979
  );
700
980
  }
701
981
 
702
- const routingRaw = options.routing ?? env.ROUTING_INPUT ?? "";
703
- const authRaw = options.opencodeAuth ?? env.OPENCODE_AUTH_INPUT ?? "";
982
+ const platformMode = options.platformPerson !== undefined;
983
+ const platformPerson = options.platformPerson ?? {};
984
+ const platformLayer = Object.keys(platformPerson).length > 0;
985
+ const personFile = prheroLayout(home).reviewConfigPath;
704
986
 
705
- let routingConfig: ReturnType<typeof parseRoutingConfig> | null = null;
706
- if (routingRaw.trim() !== "") {
707
- let parsed: unknown;
708
- try {
709
- parsed = JSON.parse(routingRaw);
710
- } catch (error) {
711
- throw new SetupInputError(
712
- ROUTING_CLASS,
713
- ROUTING_NOT_JSON,
714
- `CI routing input is not valid JSON: ${messageOf(error)}`,
715
- );
716
- }
717
- try {
718
- routingConfig = parseRoutingConfig(parsed, "~/.crysk/config.json");
719
- } catch (error) {
720
- // parseRoutingConfig names the offending key in its message: that message
721
- // stays on stderr, and the record carries only the fixed detail.
722
- throw new SetupInputError(
723
- ROUTING_CLASS,
724
- ROUTING_NOT_OBJECT,
725
- messageOf(error),
726
- );
727
- }
728
- if (routingConfig === undefined) {
729
- throw new SetupInputError(
730
- ROUTING_CLASS,
731
- ROUTING_NOT_OBJECT,
732
- "CI routing input must be a JSON object",
733
- );
734
- }
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
+ };
735
1009
  }
736
1010
 
737
- let authBody: string | undefined;
738
- if (authRaw.trim() !== "") {
739
- let parsed: unknown;
740
- try {
741
- parsed = JSON.parse(authRaw);
742
- } catch {
743
- throw new SetupInputError(
744
- AUTH_CLASS,
745
- AUTH_NOT_JSON,
746
- "CI opencode-auth is not valid JSON",
747
- );
748
- }
749
- if (
750
- typeof parsed !== "object" ||
751
- parsed === null ||
752
- Array.isArray(parsed)
753
- ) {
754
- throw new SetupInputError(
755
- AUTH_CLASS,
756
- AUTH_NOT_OBJECT,
757
- "CI opencode-auth must be a JSON object",
758
- );
759
- }
760
- 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
+ );
761
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);
762
1032
 
763
- if (routingConfig !== null) {
764
- const layout = prheroLayout(home);
765
- await mkdir(layout.dir, { recursive: true });
766
- await writeFile(
767
- layout.reviewConfigPath,
768
- `${JSON.stringify({ routing: routingConfig }, null, 2)}\n`,
769
- );
1033
+ if (Object.keys(personBody).length > 0) {
1034
+ await mkdir(path.dirname(personFile), { recursive: true });
1035
+ await writeFile(personFile, `${JSON.stringify(personBody, null, 2)}\n`);
1036
+ } else if (platformMode) {
1037
+ await rm(personFile, { force: true });
770
1038
  }
771
1039
 
772
- if (authBody !== undefined) {
773
- const authPath = resolveOpenCodeAuthPath(env, home);
774
- await mkdir(path.dirname(authPath), { recursive: true });
775
- await writeFile(authPath, authBody, { mode: 0o600 });
776
- 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 });
777
1053
  }
1054
+ return {
1055
+ notices,
1056
+ warnings,
1057
+ openCodeAuthWritten: fromSecrets !== undefined,
1058
+ openCodeModels: providers.length > 0,
1059
+ };
778
1060
  }
779
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
+
780
1073
  interface CiOpenCodeSetupDeps {
781
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;
782
1079
  stderr: (text: string) => void;
1080
+ // Where the checkout is (the engine resolves its operator root from here).
1081
+ cwd: string;
1082
+ appendOutput: (text: string) => void;
1083
+ }
1084
+
1085
+ // Workflow-command data escaping, as the runner's own toolkit does it.
1086
+ function escapeCommandData(text: string): string {
1087
+ return text.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
1088
+ }
1089
+
1090
+ // Platform mode only (the connect step announced a config file): the repo layer
1091
+ // the platform sent reaches the run step as the `repo-config` output, which it
1092
+ // passes as `--config`, but ONLY when the checkout has no repo config of its own.
1093
+ // Returns whether the layer it delivered sets `post`.
1094
+ async function deliverPlatformRepo(
1095
+ deps: CiOpenCodeSetupDeps,
1096
+ platformFile: string,
1097
+ repo: Record<string, unknown>,
1098
+ ): Promise<boolean> {
1099
+ if (Object.keys(repo).length === 0) return false;
1100
+ let root: string;
1101
+ try {
1102
+ root = await resolveRepoRoot(deps.cwd);
1103
+ } catch (error) {
1104
+ throw new PlatformConfigError(
1105
+ `the checked-out repository could not be found to decide whether it has its own config: ${messageOf(error)}`,
1106
+ );
1107
+ }
1108
+ const result = await deliverPlatformRepoLayer({
1109
+ repo,
1110
+ root,
1111
+ dir: path.dirname(platformFile),
1112
+ });
1113
+ if (result.status === "repo-file-wins") {
1114
+ deps.stderr(
1115
+ `::notice::${escapeCommandData(`Crysk platform config: this repository has its own ${path.relative(root, result.file)}, so it is used as is and the platform's repository settings are ignored.`)}\n`,
1116
+ );
1117
+ } else if (result.status === "written") {
1118
+ deps.appendOutput(`repo-config=${result.file}\n`);
1119
+ return repo.post !== undefined;
1120
+ }
1121
+ return false;
783
1122
  }
784
1123
 
785
1124
  // WHY tmp then rename, the same as the trigger's record: the publisher reads the
@@ -802,17 +1141,100 @@ async function writeSetupRecord(
802
1141
  }
803
1142
  }
804
1143
 
805
- // The step's whole job. Returns the exit code. A malformed routing or auth input
806
- // 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;
807
1181
  // any other failure (HOME, a write) stays unclassified, with no record.
808
1182
  async function runCiOpenCodeSetup(deps: CiOpenCodeSetupDeps): Promise<number> {
809
1183
  try {
810
- await materializeCiOpenCodeData({ env: deps.env });
1184
+ const cryskSecrets = intakeCryskSecrets(deps);
1185
+ const platformFile = deps.env.CRYSK_PLATFORM_CONFIG_FILE ?? "";
1186
+ const platform =
1187
+ platformFile === "" ? undefined : readPlatformConfig(platformFile);
1188
+ // The connect step announces a config file only when the platform sent
1189
+ // configuration, so a connected run with none is told apart by this
1190
+ // presence boolean: it still owns the personal file (see the option).
1191
+ const platformMode =
1192
+ platform !== undefined || deps.env.CRYSK_PLATFORM_CONNECTED === "true";
1193
+ const materialized = await materializeCiOpenCodeData({
1194
+ env: deps.env,
1195
+ modelsInput: deps.env.MODELS_INPUT ?? "",
1196
+ credentialsInput: deps.env.CREDENTIALS_INPUT ?? "",
1197
+ ...(platformMode ? { platformPerson: platform?.person ?? {} } : {}),
1198
+ ...(cryskSecrets === undefined ? {} : { cryskSecrets }),
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
+ }
1215
+ // WHY the run step needs to know: it passes `--post` whenever the `post`
1216
+ // input is true (the default), and an explicit CLI option outranks the
1217
+ // config, so a `post` the platform set would never take effect.
1218
+ let postFromPlatform = platform?.person.post !== undefined;
1219
+ if (platform !== undefined) {
1220
+ const repoPost = await deliverPlatformRepo(
1221
+ deps,
1222
+ platformFile,
1223
+ platform.repo,
1224
+ );
1225
+ postFromPlatform ||= repoPost;
1226
+ }
1227
+ if (postFromPlatform) deps.appendOutput("post-from-platform=true\n");
811
1228
  return 0;
812
1229
  } catch (error) {
813
1230
  deps.stderr(
814
1231
  `crysk: failed to materialize OpenCode CI data: ${messageOf(error)}\n`,
815
1232
  );
1233
+ if (error instanceof PlatformConfigError) {
1234
+ deps.stderr(
1235
+ `::error::${escapeCommandData(`Crysk platform mode failed: ${messageOf(error)}`)}\n`,
1236
+ );
1237
+ }
816
1238
  const outcomeDir = deps.env.CRYSK_OUTCOME_DIR ?? "";
817
1239
  if (error instanceof SetupInputError && outcomeDir !== "") {
818
1240
  try {
@@ -832,12 +1254,28 @@ async function runCiOpenCodeSetup(deps: CiOpenCodeSetupDeps): Promise<number> {
832
1254
  }
833
1255
 
834
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
+ : "";
835
1266
  process.exit(
836
1267
  await runCiOpenCodeSetup({
837
1268
  env: process.env,
1269
+ cryskSecrets,
1270
+ stdout: (text) => {
1271
+ process.stdout.write(text);
1272
+ },
838
1273
  stderr: (text) => {
839
1274
  process.stderr.write(text);
840
1275
  },
1276
+ cwd: process.cwd(),
1277
+ appendOutput: (text) =>
1278
+ appendGithubOutput(process.env.GITHUB_OUTPUT, text),
841
1279
  }),
842
1280
  );
843
1281
  }