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
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readFile, realpath } from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { chooseOpenCodeSecret } from "#ci/crysk-secrets";
4
5
  import type {
5
6
  ClaudeBinaryResolutionDeps,
6
7
  ExecutableAllowlistEntry,
@@ -9,7 +10,8 @@ import {
9
10
  resolveClaudeCanonicalBinary,
10
11
  verifyExecutableBinding,
11
12
  } from "#model/provider-capabilities";
12
- import type { ResolvedRoutePlan } from "#model/routing";
13
+ import { planRoutes, type ResolvedRoutePlan } from "#model/routing";
14
+ import type { ClaudeCredentialKind } from "#review/preflight";
13
15
  import type { CredentialKind, RunnerBackend } from "./execution/contracts";
14
16
  // #161: the SAME predicate the Claude CLI transport files usage on
15
17
  // (`claudeCliCostBasis` -> `envBillsMetered`) is the one `credentialKindForRoute`
@@ -34,8 +36,33 @@ export interface RunnerAuthorityOptions {
34
36
  // `credentialKindForRoute` reads to decide a claude-code route's credential
35
37
  // kind, so it has to be able to carry ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN,
36
38
  // not just PATH.
39
+ //
40
+ // S5: in a review run this is the RUN env (security/claude-credential.ts): the
41
+ // process environment with every Claude credential removed but the one chosen at
42
+ // run start. It is also what the harness hands the child (`childEnv`), so the
43
+ // binding's kind and the child's credential are read from the same object.
37
44
  readonly env?: Readonly<Record<string, string | undefined>>;
45
+ // S5: the Claude credential chosen at run start. `api_key` attaches no Keychain
46
+ // broker: a broker would project the subscription and strip the key the run chose.
47
+ // Absent (tests, probes, doctor) keeps the pre-S5 decision below.
48
+ readonly claudeCredential?: ClaudeCredentialKind;
49
+ // U3 (S8, L12): the CRYSK_OPENCODE_* secret names the CI setup step built the
50
+ // OpenCode auth file from, read once per run from its manifest
51
+ // (security/opencode-secret-manifest.ts). An OpenCode route's kind follows them
52
+ // (credentialKindForRoute). Absent (no manifest: the old opencode-auth input, a
53
+ // local store, tests) keeps the provider literal.
54
+ readonly openCodeSecretNames?: readonly string[];
55
+ // `credentialBrokers.opencode` is ONE broker for every OpenCode route: a test
56
+ // seam, and what admission seeds when the plan names exactly one OpenCode
57
+ // credential. It cannot serve a plan with several (U4), so routes there take
58
+ // theirs from `openCodeBrokerFor`.
38
59
  readonly credentialBrokers?: Partial<Record<RunnerBackend, CredentialBroker>>;
60
+ // U4 (S9, L12): the broker for one OpenCode credential (kind + provider), per
61
+ // route. Admission builds one pool per run (createOpenCodeBrokerPool) so the
62
+ // bindings, the free-verdict upgrade and the server each route launches all
63
+ // hold the same instance for the same credential. Absent: a fresh
64
+ // `openCodeCredentialBrokerForKind` per binding, as before.
65
+ readonly openCodeBrokerFor?: OpenCodeBrokerFor;
39
66
  /** Independent executable authority — never derived from the candidate binary. */
40
67
  readonly executableAllowlists?: Partial<
41
68
  Record<RunnerBackend, readonly ExecutableAllowlistEntry[]>
@@ -47,6 +74,8 @@ export interface ResolvedRunnerOptions {
47
74
  readonly workspaceRoot: string;
48
75
  readonly executableAllowlist: readonly ExecutableAllowlistEntry[];
49
76
  readonly credentialBroker?: CredentialBroker;
77
+ // S5: the run env, when the caller gave one, for the legacy runner's harness.
78
+ readonly childEnv?: Readonly<Record<string, string | undefined>>;
50
79
  }
51
80
 
52
81
  export type RunnerAuthorityResolution =
@@ -220,7 +249,9 @@ function planUsesBackend(
220
249
  backend: RunnerBackend,
221
250
  ): boolean {
222
251
  const seen = new Set<RunnerBackend>();
223
- for (const step of plan.steps) {
252
+ // Fallbacks included (S4): an OpenCode model listed only as a fallback still
253
+ // needs its executable resolved before the run.
254
+ for (const step of planRoutes(plan)) {
224
255
  if (!seen.has(step.route.backend)) {
225
256
  seen.add(step.route.backend);
226
257
  if (step.route.backend === backend) {
@@ -359,15 +390,35 @@ export async function withClaudeDiscoveryAllowlist(
359
390
  // (claude-code-cli.ts) by construction. #279 is the one path where that
360
391
  // equality breaks.
361
392
  //
393
+ // S5 (2026-11-06): in a review run both inputs already follow the credential chosen at
394
+ // run start (security/claude-credential.ts). `env` is the run env, holding only that
395
+ // credential, and `hasBroker` is false when the API key was chosen
396
+ // (`RunnerAuthorityOptions.claudeCredential`), so this predicate answers metered
397
+ // exactly when the run uses the API key and needs no knowledge of the order itself.
398
+ // One side effect on #279: with the subscription chosen, the run env carries no key,
399
+ // so a degraded projection runs on no credential and fails, instead of quietly
400
+ // switching to a key mid-run.
401
+ //
362
402
  // Both arguments default to the "nothing is known" case (`env: {}`,
363
403
  // `hasBroker: false`) so a caller that omits them — every existing call site
364
404
  // that never threaded either through, and every test that does not care
365
405
  // about this dimension — keeps today's answer: subscription.
406
+ //
407
+ // U3 (S8, L12, 2026-11-06): `openCodeSecretNames` lifts the provider-keyed limit
408
+ // above for an auth file the CI setup step built from CRYSK_OPENCODE_* secrets.
409
+ // The names (never the store) say which secret built the provider's record, and
410
+ // chooseOpenCodeSecret, the same rule the setup step chose with, turns them into
411
+ // the kind: `_OAUTH` (openai only, subscription first) is the ChatGPT OAuth kind,
412
+ // `_API_KEY` is a metered API token, so `openai` on an API key now binds metered
413
+ // instead of being refused. Still pure: the caller read the names. Absent or
414
+ // silent names keep the provider literal, which the old `opencode-auth` input and
415
+ // a local store still get.
366
416
  export function credentialKindForRoute(
367
417
  backend: RunnerBackend,
368
418
  provider: string,
369
419
  env: Readonly<Record<string, string | undefined>> = {},
370
420
  hasBroker = false,
421
+ openCodeSecretNames?: readonly string[],
371
422
  ): CredentialKind {
372
423
  if (backend === "claude-code") {
373
424
  return !hasBroker && envBillsMetered(env)
@@ -375,6 +426,12 @@ export function credentialKindForRoute(
375
426
  : "claude_subscription_oauth";
376
427
  }
377
428
  if (backend === "opencode") {
429
+ const choice =
430
+ openCodeSecretNames === undefined
431
+ ? undefined
432
+ : chooseOpenCodeSecret(provider, openCodeSecretNames);
433
+ if (choice?.kind === "api_key") return "provider_api_token";
434
+ if (choice?.kind === "oauth") return "opencode_chatgpt_oauth";
378
435
  return provider === OPENCODE_OAUTH_PROVIDER
379
436
  ? "opencode_chatgpt_oauth"
380
437
  : "provider_api_token";
@@ -432,6 +489,51 @@ export function openCodeCredentialBrokerForKind(
432
489
  return new OpenCodeAuthBroker();
433
490
  }
434
491
 
492
+ // U4 (S9, L12): the broker for one OpenCode credential, keyed by its kind and
493
+ // provider. A pool memoises it per credential so every route on that credential
494
+ // shares ONE instance (#149's "one broker, never two diverging in silence", now
495
+ // scoped per credential instead of per plan) while routes on different
496
+ // credentials never share one: each broker projects only its own provider's
497
+ // record, so no server is ever handed another credential's.
498
+ export type OpenCodeBrokerFor = (
499
+ kind: CredentialKind,
500
+ provider: string,
501
+ ) => CredentialBroker;
502
+
503
+ export function createOpenCodeBrokerPool(
504
+ make: OpenCodeBrokerFor = openCodeCredentialBrokerForKind,
505
+ ): OpenCodeBrokerFor {
506
+ const brokers = new Map<string, CredentialBroker>();
507
+ return (kind, provider) => {
508
+ // JSON, not a joined string: no separator can make two pairs collide.
509
+ const key = JSON.stringify([kind, provider]);
510
+ let broker = brokers.get(key);
511
+ if (broker === undefined) {
512
+ broker = make(kind, provider);
513
+ brokers.set(key, broker);
514
+ }
515
+ return broker;
516
+ };
517
+ }
518
+
519
+ // The broker an OpenCode route of this credential runs on: the caller's single
520
+ // injected broker first (tests, and admission's seed for a one-credential plan),
521
+ // then the run's pool, then a fresh default.
522
+ export function openCodeBrokerForRoute(
523
+ options: Pick<
524
+ RunnerAuthorityOptions,
525
+ "credentialBrokers" | "openCodeBrokerFor"
526
+ >,
527
+ kind: CredentialKind,
528
+ provider: string,
529
+ ): CredentialBroker {
530
+ return (
531
+ options.credentialBrokers?.opencode ??
532
+ options.openCodeBrokerFor?.(kind, provider) ??
533
+ openCodeCredentialBrokerForKind(kind, provider)
534
+ );
535
+ }
536
+
435
537
  export function openCodeCredentialBroker(provider: string): CredentialBroker {
436
538
  return openCodeCredentialBrokerForKind(
437
539
  credentialKindForRoute("opencode", provider),
@@ -469,8 +571,15 @@ export async function resolveBindingAuthority(
469
571
  // around: see the WHY block on `credentialKindForRoute` above for the
470
572
  // full reasoning, including the one known exception where a broker is
471
573
  // present but its projection degrades (#279).
574
+ //
575
+ // S5: an API key chosen at run start attaches no broker at all, on any host. The
576
+ // run env then carries ANTHROPIC_API_KEY and nothing else, so the kind below is
577
+ // metered by the same predicate, and the child spends the key the run chose.
472
578
  const broker =
473
- options.credentialBrokers?.["claude-code"] ?? claudeCredentialBroker();
579
+ options.claudeCredential === "api_key"
580
+ ? undefined
581
+ : (options.credentialBrokers?.["claude-code"] ??
582
+ claudeCredentialBroker());
474
583
  // Falls back to `process.env` exactly like the opencode PATH lookup a few
475
584
  // lines below (`resolveOpenCodeCanonicalBinary`'s
476
585
  // `lookup.env?.PATH ?? process.env.PATH`) — nothing in the real CLI
@@ -531,7 +640,13 @@ export async function resolveBindingAuthority(
531
640
  if ("error" in verified) {
532
641
  return { error: verified.error };
533
642
  }
534
- const credentialKind = credentialKindForRoute(backend, provider);
643
+ const credentialKind = credentialKindForRoute(
644
+ backend,
645
+ provider,
646
+ {},
647
+ false,
648
+ options.openCodeSecretNames,
649
+ );
535
650
  return {
536
651
  binding: {
537
652
  backend,
@@ -547,11 +662,13 @@ export async function resolveBindingAuthority(
547
662
  // subscription's quota and a metered token's quota into one bucket
548
663
  // and make both wrong.
549
664
  credentialRef: `opencode-auth:${provider}`,
550
- credentialBroker:
551
- options.credentialBrokers?.opencode ??
552
- // #182: the kind above, not a second derivation — deriving again
553
- // here is how the broker and the kind drift apart unobserved.
554
- openCodeCredentialBrokerForKind(credentialKind, provider),
665
+ // #182: the kind above, not a second derivation — deriving again
666
+ // here is how the broker and the kind drift apart unobserved.
667
+ credentialBroker: openCodeBrokerForRoute(
668
+ options,
669
+ credentialKind,
670
+ provider,
671
+ ),
555
672
  bucketId: "opencode",
556
673
  },
557
674
  };
@@ -591,6 +708,7 @@ export async function resolveRunnerAuthority(
591
708
  ...(binding.credentialBroker
592
709
  ? { credentialBroker: binding.credentialBroker }
593
710
  : {}),
711
+ ...(options.env === undefined ? {} : { childEnv: options.env }),
594
712
  },
595
713
  };
596
714
  }
@@ -24,8 +24,7 @@ export function routesMatch(
24
24
  a.provider === b.provider &&
25
25
  a.modelFamily === b.modelFamily &&
26
26
  a.modelSnapshot === b.modelSnapshot &&
27
- a.modelVariant === b.modelVariant &&
28
- (a.gateway ?? "") === (b.gateway ?? "")
27
+ a.modelVariant === b.modelVariant
29
28
  );
30
29
  }
31
30
 
@@ -0,0 +1,355 @@
1
+ // Which Claude credential a run uses (odd/tasks/role-model-routing.md, S5, S8, L6 items 2-3, L12 "E-e").
2
+ //
3
+ // Before S5 nobody chose: the Claude CLI prefers a per-token key to the subscription
4
+ // token, so a non-empty ANTHROPIC_API_KEY silently won over CLAUDE_CODE_OAUTH_TOKEN and
5
+ // the review billed per token. Now `credentials.claude` names the order (default
6
+ // `["subscription", "api_key"]`), the run uses the FIRST listed credential that is
7
+ // present, decided once at run start and never switched mid-run, and the child sees
8
+ // exactly that one credential under the CLI's own variable name.
9
+ //
10
+ // Three halves, kept apart so the decision is pure and testable:
11
+ // * claudeCredentialPresence: which credentials exist, and where each came from.
12
+ // * selectClaudeCredential: the order applied to that presence. Pure.
13
+ // * claudeRunEnv: the run's environment with every Claude credential variable
14
+ // removed and only the chosen one put back. Every reader downstream (the binding's
15
+ // credential kind, the CI ceiling, the usage record's billing mode, the failure's
16
+ // credential) reads this env, so they all follow the choice without a second copy
17
+ // of it.
18
+ //
19
+ // WHY the env is rebuilt rather than `process.env` edited: Bun.spawn without an
20
+ // explicit `env` hands the child the environment the process STARTED with, so a
21
+ // `delete process.env.X` never reaches it (L14 (a)). The run env is passed explicitly
22
+ // to the runner authority and as the harness's `childEnv`.
23
+
24
+ import { existsSync } from "node:fs";
25
+ import { homedir } from "node:os";
26
+ import path from "node:path";
27
+ import type { CliErrorClass, ErrorParams } from "#ci/outcome";
28
+ import {
29
+ claudeCredentialProjectionReady,
30
+ defaultKeychainCredentialPresent,
31
+ } from "#model/provider-capabilities";
32
+ import type {
33
+ ClaudeCredentialKind,
34
+ CredentialsConfig,
35
+ } from "#review/preflight";
36
+ import { CliError } from "../errors";
37
+
38
+ export const DEFAULT_CLAUDE_CREDENTIAL_ORDER: readonly ClaudeCredentialKind[] =
39
+ ["subscription", "api_key"];
40
+
41
+ // Where each credential may come from in the environment, the CRYSK_* secret first
42
+ // (S8). The old names are the Claude CLI's own variables, which a local run exports;
43
+ // in CI the action reads only the crysk-secrets input (the intake below, U5).
44
+ const ENV_SOURCES = {
45
+ subscription: ["CRYSK_CLAUDE_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"],
46
+ api_key: ["CRYSK_CLAUDE_API_KEY", "ANTHROPIC_API_KEY"],
47
+ } as const satisfies Record<ClaudeCredentialKind, readonly string[]>;
48
+
49
+ type EnvSource = (typeof ENV_SOURCES)[ClaudeCredentialKind][number];
50
+
51
+ // "login" is a subscription the machine already holds outside the environment: the
52
+ // macOS Keychain item the credential broker projects, or the CLI's OAuth store
53
+ // `~/.claude/.credentials.json`.
54
+ export type ClaudeCredentialSource = EnvSource | "login";
55
+
56
+ // The variable the Claude CLI reads for each kind. The child gets exactly one.
57
+ export const CLAUDE_CHILD_VARIABLE = {
58
+ subscription: "CLAUDE_CODE_OAUTH_TOKEN",
59
+ api_key: "ANTHROPIC_API_KEY",
60
+ } as const satisfies Record<ClaudeCredentialKind, string>;
61
+
62
+ // Every variable that can carry a Claude credential. All of them leave the run env.
63
+ // ANTHROPIC_AUTH_TOKEN is one too (a bearer token the CLI also bills per token), but no
64
+ // `credentials.claude` kind names it, so it is removed and never chosen.
65
+ export const CLAUDE_CREDENTIAL_VARIABLES = [
66
+ "CRYSK_CLAUDE_OAUTH_TOKEN",
67
+ "CRYSK_CLAUDE_API_KEY",
68
+ "CLAUDE_CODE_OAUTH_TOKEN",
69
+ "ANTHROPIC_API_KEY",
70
+ "ANTHROPIC_AUTH_TOKEN",
71
+ ] as const;
72
+
73
+ export interface ClaudeCredentialPresence {
74
+ readonly subscription?: ClaudeCredentialSource;
75
+ readonly api_key?: ClaudeCredentialSource;
76
+ // Set when ANTHROPIC_AUTH_TOKEN holds a value: it is stripped, and a refusal says so.
77
+ readonly authTokenIgnored?: true;
78
+ // Set when the env came from the crysk-secrets intake (the action, U5): the only
79
+ // sources were the CRYSK_* secrets in that input, so a refusal names those.
80
+ readonly fromCryskSecrets?: true;
81
+ }
82
+
83
+ export type ClaudeCredentialSelection =
84
+ | {
85
+ readonly status: "chosen";
86
+ readonly kind: ClaudeCredentialKind;
87
+ readonly source: ClaudeCredentialSource;
88
+ readonly order: readonly ClaudeCredentialKind[];
89
+ readonly orderDefaulted: boolean;
90
+ }
91
+ | {
92
+ readonly status: "none";
93
+ readonly order: readonly ClaudeCredentialKind[];
94
+ readonly orderDefaulted: boolean;
95
+ readonly presence: ClaudeCredentialPresence;
96
+ };
97
+
98
+ function hasValue(value: string | undefined): value is string {
99
+ return value !== undefined && value.trim() !== "";
100
+ }
101
+
102
+ // Which credentials exist. The trim matches envBillsMetered: a whitespace-only value is
103
+ // no credential (GitHub renders an unset input as "", and a stray space must not count).
104
+ export function claudeCredentialPresence(
105
+ env: Readonly<Record<string, string | undefined>>,
106
+ loginPresent: boolean,
107
+ ): ClaudeCredentialPresence {
108
+ const found = (kind: ClaudeCredentialKind): EnvSource | undefined =>
109
+ ENV_SOURCES[kind].find((name) => hasValue(env[name]));
110
+ const subscription =
111
+ found("subscription") ?? (loginPresent ? "login" : undefined);
112
+ const apiKey = found("api_key");
113
+ return {
114
+ ...(subscription === undefined ? {} : { subscription }),
115
+ ...(apiKey === undefined ? {} : { api_key: apiKey }),
116
+ ...(hasValue(env.ANTHROPIC_AUTH_TOKEN)
117
+ ? { authTokenIgnored: true as const }
118
+ : {}),
119
+ };
120
+ }
121
+
122
+ // The first listed credential that is present. A present credential that the order
123
+ // does not list is never used: listing is consent to pay with it.
124
+ export function selectClaudeCredential(
125
+ order: readonly ClaudeCredentialKind[] | undefined,
126
+ presence: ClaudeCredentialPresence,
127
+ ): ClaudeCredentialSelection {
128
+ const effective = order ?? DEFAULT_CLAUDE_CREDENTIAL_ORDER;
129
+ const orderDefaulted = order === undefined;
130
+ for (const kind of effective) {
131
+ const source = presence[kind];
132
+ if (source !== undefined) {
133
+ return {
134
+ status: "chosen",
135
+ kind,
136
+ source,
137
+ order: effective,
138
+ orderDefaulted,
139
+ };
140
+ }
141
+ }
142
+ return { status: "none", order: effective, orderDefaulted, presence };
143
+ }
144
+
145
+ function describeSources(
146
+ kind: ClaudeCredentialKind,
147
+ fromCryskSecrets: boolean,
148
+ ): string {
149
+ const names = fromCryskSecrets
150
+ ? `${ENV_SOURCES[kind][0]} in the crysk-secrets input`
151
+ : ENV_SOURCES[kind].join(" or ");
152
+ return kind === "subscription"
153
+ ? `${names}, or a Claude login on this machine`
154
+ : names;
155
+ }
156
+
157
+ // A run refused at admission because a route has no credential it may use. It stops
158
+ // before any binding or provider call (the OpenCode refusal follows only the free
159
+ // model probe, which spends no tokens), so it spent nothing: a CI run settles its
160
+ // admission row as an unspent gate skip, with `ledgerReason`
161
+ // (settleClaudeCredentialRefusal, pr/admission.ts). It names its record class and params,
162
+ // so cli.json carries the code and the route's fixes (classifyCliError,
163
+ // cliErrorParams in ci/classify-error.ts). The CLI still prints it as the one line it
164
+ // prints any CliError.
165
+ export class CredentialRefusalError extends CliError {
166
+ readonly params: ErrorParams;
167
+ readonly ledgerReason: string;
168
+
169
+ constructor(
170
+ message: string,
171
+ cls: CliErrorClass,
172
+ params: ErrorParams,
173
+ ledgerReason: string,
174
+ ) {
175
+ super(message, { cls });
176
+ this.params = params;
177
+ this.ledgerReason = ledgerReason;
178
+ }
179
+ }
180
+
181
+ // The Claude refusal (claudeCredentialRefusal below): no listed Claude credential
182
+ // reached the run, which is CRYSK-CRED-MISSING, the code the trigger records for a run
183
+ // with no credential at all.
184
+ export class ClaudeCredentialRefusalError extends CredentialRefusalError {
185
+ constructor(message: string) {
186
+ super(
187
+ message,
188
+ { kind: "trigger", check: "no-credential" },
189
+ { backend: "claude" },
190
+ "no Claude credential the run may use is set; refused before any provider spend",
191
+ );
192
+ }
193
+ }
194
+
195
+ // The admission refusal for a plan that has a Claude route and no listed credential
196
+ // present, or undefined when the run can go ahead. A plan with no Claude route ignores
197
+ // Claude credentials, so it is never refused here. The message names the order and what
198
+ // is set, never a value.
199
+ export function claudeCredentialRefusal(
200
+ selection: ClaudeCredentialSelection,
201
+ planHasClaudeRoute: boolean,
202
+ ): string | undefined {
203
+ if (selection.status === "chosen" || !planHasClaudeRoute) return undefined;
204
+ const order = `credentials.claude is [${selection.order.join(", ")}]${selection.orderDefaulted ? " (the default)" : ""}`;
205
+ const missing = selection.order
206
+ .map(
207
+ (kind) =>
208
+ `${kind} (${describeSources(kind, selection.presence.fromCryskSecrets === true)})`,
209
+ )
210
+ .join("; ");
211
+ const unlisted = (["subscription", "api_key"] as const).filter(
212
+ (kind) =>
213
+ !selection.order.includes(kind) && selection.presence[kind] !== undefined,
214
+ );
215
+ const parts = [
216
+ `no Claude credential this run may use is set: ${order}, and none of those is set: ${missing}`,
217
+ ];
218
+ if (unlisted.length > 0) {
219
+ parts.push(
220
+ `${unlisted.join(" and ")} ${unlisted.length === 1 ? "is" : "are"} set but not listed, so ${unlisted.length === 1 ? "it is" : "they are"} not used`,
221
+ );
222
+ }
223
+ if (selection.presence.authTokenIgnored) {
224
+ parts.push(
225
+ "ANTHROPIC_AUTH_TOKEN is set but no longer used: put an API key in CRYSK_CLAUDE_API_KEY or ANTHROPIC_API_KEY",
226
+ );
227
+ }
228
+ parts.push(
229
+ "Set a listed credential, or change credentials.claude in your person config",
230
+ );
231
+ return parts.join(". ");
232
+ }
233
+
234
+ // The run's environment: every Claude credential variable removed, then only the
235
+ // chosen credential put back under the CLI's own name. A subscription that comes from
236
+ // the machine's login puts nothing back: the broker projects it, or the CLI reads its
237
+ // own store. With no credential chosen, every Claude credential is gone.
238
+ export function claudeRunEnv(
239
+ env: Readonly<Record<string, string | undefined>>,
240
+ selection: ClaudeCredentialSelection,
241
+ ): Record<string, string | undefined> {
242
+ const run: Record<string, string | undefined> = { ...env };
243
+ for (const name of CLAUDE_CREDENTIAL_VARIABLES) delete run[name];
244
+ if (selection.status === "chosen" && selection.source !== "login") {
245
+ run[CLAUDE_CHILD_VARIABLE[selection.kind]] = env[selection.source];
246
+ }
247
+ return run;
248
+ }
249
+
250
+ // U5: the Claude values the Run Crysk step took from the crysk-secrets input
251
+ // (src/ci/run.ts, which reads the input on stdin), keyed by kind. Undefined until
252
+ // run.ts takes them, which only the action does; a local run never sets it.
253
+ let cryskClaudeIntake:
254
+ | { readonly subscription?: string; readonly api_key?: string }
255
+ | undefined;
256
+
257
+ // Called once by src/ci/run.ts, before the CLI starts, with the parsed input's
258
+ // Claude secrets (parseCryskSecrets's `secrets.claude`). Nothing is written to
259
+ // process.env: Bun hands a child the environment it started with, and readers of
260
+ // the startup env (the transport's billingMode getter, a `{...process.env}` copy)
261
+ // would see a value assigned there. resolveRunClaudeCredential reads the intake.
262
+ export function takeCryskClaudeSecrets(claude: {
263
+ readonly subscription?: string;
264
+ readonly api_key?: string;
265
+ }): void {
266
+ cryskClaudeIntake = { ...claude };
267
+ }
268
+
269
+ // For tests: forget the intake, so a later test reads the process env again.
270
+ export function clearCryskClaudeIntake(): void {
271
+ cryskClaudeIntake = undefined;
272
+ }
273
+
274
+ // The env a CI run reads its Claude credential from: every Claude variable of the
275
+ // process env removed (a job-level ANTHROPIC_API_KEY nobody passed through the
276
+ // crysk-secrets input must not be chosen), then the intake's values under their
277
+ // CRYSK_* names. Pure; the run env (claudeRunEnv) is built from it as from any env.
278
+ export function cryskIntakeEnv(
279
+ env: Readonly<Record<string, string | undefined>>,
280
+ claude: { readonly subscription?: string; readonly api_key?: string },
281
+ ): Record<string, string | undefined> {
282
+ const out: Record<string, string | undefined> = { ...env };
283
+ for (const name of CLAUDE_CREDENTIAL_VARIABLES) delete out[name];
284
+ for (const kind of ["subscription", "api_key"] as const) {
285
+ const value = claude[kind];
286
+ if (value !== undefined) out[ENV_SOURCES[kind][0]] = value;
287
+ }
288
+ return out;
289
+ }
290
+
291
+ export interface RunClaudeCredential {
292
+ readonly selection: ClaudeCredentialSelection;
293
+ // The environment every runner, binding and gate of this run reads.
294
+ readonly env: Record<string, string | undefined>;
295
+ // The chosen kind, for the runner authority (an API key attaches no Keychain broker).
296
+ readonly kind?: ClaudeCredentialKind;
297
+ }
298
+
299
+ // The probes behind defaultClaudeLoginPresent. Tests inject all three, so no test
300
+ // reads the real Keychain or HOME.
301
+ export interface ClaudeLoginProbe {
302
+ readonly platform?: NodeJS.Platform;
303
+ readonly existsFn?: (p: string) => boolean;
304
+ readonly keychainProbe?: () => boolean;
305
+ }
306
+
307
+ // The machine's own Claude login: a Keychain item the broker can project (macOS), or
308
+ // the CLI's OAuth store. `~/.claude.json` does not count: every Claude user has it,
309
+ // API-key users included, and counting it would strip their key.
310
+ // WHY the item and not only the broker (R001, #494): `security` is on every Mac, so
311
+ // counting the broker alone chose the login on a Mac that has only an API key; the
312
+ // key was stripped, the projection found no item (`source_read_failed`) and every
313
+ // step failed. The item check is metadata-only (no `-w`, no secret read).
314
+ export function defaultClaudeLoginPresent(
315
+ env: Readonly<Record<string, string | undefined>> = process.env,
316
+ probe: ClaudeLoginProbe = {},
317
+ ): boolean {
318
+ const exists = probe.existsFn ?? existsSync;
319
+ const home = hasValue(env.HOME) ? env.HOME : homedir();
320
+ if (exists(path.join(home, ".claude", ".credentials.json"))) return true;
321
+ return (
322
+ claudeCredentialProjectionReady({
323
+ ...(probe.platform === undefined ? {} : { platform: probe.platform }),
324
+ existsFn: exists,
325
+ }) && (probe.keychainProbe ?? defaultKeychainCredentialPresent)()
326
+ );
327
+ }
328
+
329
+ // Called once at run start, before any plan is admitted. With no env given it reads
330
+ // the process env, or, in the action, the crysk-secrets intake over it (U5).
331
+ export function resolveRunClaudeCredential(input: {
332
+ readonly credentials?: CredentialsConfig;
333
+ readonly env?: Readonly<Record<string, string | undefined>>;
334
+ readonly loginPresent?: boolean;
335
+ }): RunClaudeCredential {
336
+ const fromIntake = input.env === undefined && cryskClaudeIntake !== undefined;
337
+ const env =
338
+ input.env ??
339
+ (cryskClaudeIntake === undefined
340
+ ? process.env
341
+ : cryskIntakeEnv(process.env, cryskClaudeIntake));
342
+ const found = claudeCredentialPresence(
343
+ env,
344
+ input.loginPresent ?? defaultClaudeLoginPresent(env),
345
+ );
346
+ const presence: ClaudeCredentialPresence = fromIntake
347
+ ? { ...found, fromCryskSecrets: true }
348
+ : found;
349
+ const selection = selectClaudeCredential(input.credentials?.claude, presence);
350
+ return {
351
+ selection,
352
+ env: claudeRunEnv(env, selection),
353
+ ...(selection.status === "chosen" ? { kind: selection.kind } : {}),
354
+ };
355
+ }