crysk 0.5.1 → 0.6.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 (67) hide show
  1. package/README.md +15 -1
  2. package/dist/SKILL-nncgwkx7.md +553 -0
  3. package/dist/cli.js +6379 -5561
  4. package/dist/index.js +967 -467
  5. package/dist/workflow-ag62s87j.yml +163 -0
  6. package/package.json +3 -2
  7. package/skills/crysk-ci-setup/assets/workflow.yml +3 -0
  8. package/skills/crysk-loop/SKILL.md +2 -2
  9. package/src/asset-manifest.ts +11 -0
  10. package/src/assets.ts +34 -11
  11. package/src/ci/credential-refresh.ts +524 -0
  12. package/src/ci/crysk-secrets.ts +20 -6
  13. package/src/ci/gates.ts +2 -24
  14. package/src/ci/outcome.ts +165 -15
  15. package/src/ci/platform.ts +205 -7
  16. package/src/ci/setup.ts +64 -6
  17. package/src/ci/trigger.ts +84 -8
  18. package/src/commands/ci-setup.ts +12 -3
  19. package/src/commands/doctor.ts +25 -23
  20. package/src/commands/status.ts +2 -0
  21. package/src/diversity/identity.ts +11 -1
  22. package/src/diversity/pipeline-integration.ts +19 -6
  23. package/src/doctor.ts +133 -4
  24. package/src/execution/contracts.ts +15 -3
  25. package/src/harness/materiality-judge.ts +153 -0
  26. package/src/harness/pipeline-plan.ts +133 -0
  27. package/src/harness/replay-rows.ts +172 -0
  28. package/src/harness/route-runner.ts +288 -0
  29. package/src/harness/single-step.ts +153 -0
  30. package/src/index.ts +1 -1
  31. package/src/model/catalog.ts +10 -7
  32. package/src/model/model-name.ts +14 -0
  33. package/src/model/profiles/claude.ts +34 -0
  34. package/src/model/profiles/openai.ts +44 -0
  35. package/src/model/profiles.ts +213 -0
  36. package/src/model/routing.ts +155 -50
  37. package/src/pr/answered-findings.ts +3 -0
  38. package/src/pr/ci-admission-gate.ts +1 -0
  39. package/src/pr/discovery.ts +1 -0
  40. package/src/pr/plan.ts +6 -1
  41. package/src/pr/pr-status.ts +18 -3
  42. package/src/pr/publish-outcome.ts +14 -13
  43. package/src/pr/review-pr.ts +49 -8
  44. package/src/pr/target.ts +16 -7
  45. package/src/production-runtime.ts +100 -13
  46. package/src/rereview/prepare.ts +13 -2
  47. package/src/review/exit-code.ts +60 -0
  48. package/src/review/findings.ts +3 -3
  49. package/src/review/pipeline.ts +193 -58
  50. package/src/review/preflight.ts +100 -10
  51. package/src/review/prompt-set.ts +73 -0
  52. package/src/review/review.ts +32 -13
  53. package/src/review/route-preflight.ts +117 -67
  54. package/src/review/run.ts +34 -4
  55. package/src/security/credential-broker.ts +21 -9
  56. package/src/security/oauth-providers.ts +101 -0
  57. package/src/transport-registry.ts +33 -0
  58. package/src/transports/opencode-sdk.ts +33 -1
  59. package/src/triage/adjudication.ts +35 -2
  60. package/src/ui/config-edit.ts +9 -0
  61. package/src/ui/config.ts +1 -0
  62. package/src/ui/menu.ts +9 -2
  63. package/src/ui/result.ts +1 -1
  64. package/src/updater.ts +21 -13
  65. package/src/watch/preflight.ts +34 -8
  66. package/src/watch/watch.ts +8 -4
  67. package/src/wizard.ts +23 -0
package/src/ci/outcome.ts CHANGED
@@ -23,7 +23,9 @@
23
23
 
24
24
  import { commandHint, MARKER_OPEN, matchMarkerPrefix } from "../brand";
25
25
  import type {
26
+ ClaudeFailureCredential,
26
27
  FailureCredential,
28
+ OpenCodeFailureCredential,
27
29
  TransportFailureCause,
28
30
  } from "../execution/contracts";
29
31
  import type { CredentialProjectionFailureClass } from "../security/credential-broker";
@@ -45,11 +47,12 @@ export type ErrorClass =
45
47
  }
46
48
  | {
47
49
  kind: "config-parse";
48
- // `models-input` and `credentials-input`: the setup step's reading of the
49
- // `models` and `credentials` inputs (D1), never the CLI's.
50
+ // `models-input`, `credentials-input` and `profile-input`: the setup
51
+ // step's reading of those inputs (D1), never the CLI's.
50
52
  source:
51
53
  | "models-input"
52
54
  | "credentials-input"
55
+ | "profile-input"
53
56
  | "repo-config"
54
57
  | "person-config"
55
58
  | "extra-hunters";
@@ -253,7 +256,10 @@ export type CliErrorClass =
253
256
  | { kind: "trigger"; check: "no-credential" }
254
257
  | {
255
258
  kind: "credential";
256
- failureClass: "missing_provider_record" | "missing_subscription_record";
259
+ failureClass:
260
+ | "missing_provider_record"
261
+ | "missing_subscription_record"
262
+ | "subscription_expiring";
257
263
  }
258
264
  | { kind: "capability"; issue: "sdk_unavailable" | "version_unsupported" }
259
265
  | {
@@ -324,7 +330,8 @@ export interface HunterFailureRecord {
324
330
  // One short line saying why the hunter failed, in the provider's words (see
325
331
  // safeFailureDetail). Present only when the transport knew it.
326
332
  detail?: string;
327
- // The secret the hunter ran on (ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN), so a
333
+ // The secret the hunter ran on (ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN for a
334
+ // Claude route, CRYSK_OPENCODE_<P>_API_KEY or _OAUTH for an OpenCode one), so a
328
335
  // credential or quota failure can name which one to replace or top up.
329
336
  credential?: FailureCredential;
330
337
  }
@@ -379,21 +386,51 @@ export function safeModelName(value: unknown): string | undefined {
379
386
  : undefined;
380
387
  }
381
388
 
382
- // Every FailureCredential, as a runtime lookup (tied to the union by `satisfies`, like the
383
- // cause list above: this file cannot import the runtime list from execution/contracts).
389
+ // Every Claude FailureCredential, as a runtime lookup (tied to the union by `satisfies`,
390
+ // like the cause list above: this file cannot import the runtime list from
391
+ // execution/contracts).
384
392
  const FAILURE_CREDENTIAL_LOOKUP = {
385
393
  ANTHROPIC_API_KEY: true,
386
394
  ANTHROPIC_AUTH_TOKEN: true,
387
395
  CLAUDE_CODE_OAUTH_TOKEN: true,
388
- } satisfies Record<FailureCredential, true>;
396
+ } satisfies Record<ClaudeFailureCredential, true>;
397
+
398
+ // An OpenCode FailureCredential: a CRYSK_OPENCODE_<P>_API_KEY or _OAUTH secret name. A
399
+ // COPY of OPENCODE_SECRET_NAME_RE in crysk-secrets.ts, which this module cannot import at
400
+ // runtime (the builtins-only guard); test/ci/opencode-failure-credential.test.ts pins the
401
+ // two to the same answers.
402
+ const OPENCODE_FAILURE_CREDENTIAL_RE =
403
+ /^CRYSK_OPENCODE_([A-Z0-9]+(?:_[A-Z0-9]+)*)_(API_KEY|OAUTH)$/;
404
+
405
+ function isOpenCodeCredential(
406
+ value: string,
407
+ ): value is OpenCodeFailureCredential {
408
+ return OPENCODE_FAILURE_CREDENTIAL_RE.test(value);
409
+ }
389
410
 
390
411
  export function knownFailureCredential(
391
412
  value: unknown,
392
413
  ): FailureCredential | undefined {
393
- return typeof value === "string" &&
394
- Object.hasOwn(FAILURE_CREDENTIAL_LOOKUP, value)
395
- ? (value as FailureCredential)
396
- : undefined;
414
+ if (typeof value !== "string") return undefined;
415
+ if (Object.hasOwn(FAILURE_CREDENTIAL_LOOKUP, value)) {
416
+ return value as ClaudeFailureCredential;
417
+ }
418
+ return isOpenCodeCredential(value) ? value : undefined;
419
+ }
420
+
421
+ // The OpenCode variant of a credential's fix, or undefined for a Claude credential. An
422
+ // `_OAUTH` secret is a subscription record (openai only, crysk-secrets.ts), so its fix is
423
+ // a new `opencode auth login`; an `_API_KEY` secret is replaced with a new key.
424
+ function openCodeCredentialVariant(
425
+ secret: string | undefined,
426
+ ): "opencode_api_key" | "opencode_oauth" | undefined {
427
+ const kind =
428
+ secret === undefined
429
+ ? undefined
430
+ : OPENCODE_FAILURE_CREDENTIAL_RE.exec(secret)?.[2];
431
+ if (kind === "API_KEY") return "opencode_api_key";
432
+ if (kind === "OAUTH") return "opencode_oauth";
433
+ return undefined;
397
434
  }
398
435
 
399
436
  // A failure detail, as the record may carry it. Unlike a provider or model name it is the
@@ -472,7 +509,9 @@ function parseSetupClass(value: unknown): ErrorClass | undefined {
472
509
  if (!isRecordObject(value)) return undefined;
473
510
  if (
474
511
  value.kind === "config-parse" &&
475
- (value.source === "models-input" || value.source === "credentials-input")
512
+ (value.source === "models-input" ||
513
+ value.source === "credentials-input" ||
514
+ value.source === "profile-input")
476
515
  ) {
477
516
  return { kind: "config-parse", source: value.source };
478
517
  }
@@ -634,7 +673,8 @@ function parseCliClass(value: unknown): CliErrorClass | undefined {
634
673
  if (value.kind === "credential") {
635
674
  if (
636
675
  value.failureClass === "missing_provider_record" ||
637
- value.failureClass === "missing_subscription_record"
676
+ value.failureClass === "missing_subscription_record" ||
677
+ value.failureClass === "subscription_expiring"
638
678
  ) {
639
679
  return { kind: "credential", failureClass: value.failureClass };
640
680
  }
@@ -827,6 +867,7 @@ export function codeOf(cls: ErrorClass): ErrorCode {
827
867
  switch (cls.source) {
828
868
  case "models-input":
829
869
  case "credentials-input":
870
+ case "profile-input":
830
871
  case "repo-config":
831
872
  case "person-config":
832
873
  return "CRYSK-CONFIG-INVALID";
@@ -853,6 +894,7 @@ export function codeOf(cls: ErrorClass): ErrorCode {
853
894
  switch (cls.failureClass) {
854
895
  case "missing_provider_record":
855
896
  case "missing_subscription_record":
897
+ case "subscription_expiring":
856
898
  case "malformed_payload":
857
899
  case "source_read_failed":
858
900
  case "env-absent":
@@ -961,6 +1003,7 @@ export function ownerOf(cls: ErrorClass, ctx: OutcomeContext): Owner {
961
1003
  switch (cls.source) {
962
1004
  case "models-input":
963
1005
  case "credentials-input":
1006
+ case "profile-input":
964
1007
  case "repo-config":
965
1008
  case "person-config":
966
1009
  case "extra-hunters":
@@ -975,6 +1018,7 @@ export function ownerOf(cls: ErrorClass, ctx: OutcomeContext): Owner {
975
1018
  switch (cls.failureClass) {
976
1019
  case "missing_provider_record":
977
1020
  case "missing_subscription_record":
1021
+ case "subscription_expiring":
978
1022
  case "malformed_payload":
979
1023
  case "source_read_failed":
980
1024
  case "env-absent":
@@ -1106,6 +1150,8 @@ const CREDENTIAL_PHRASE: Record<
1106
1150
  "the expected subscription login is missing or of the wrong kind",
1107
1151
  missing_provider_record:
1108
1152
  "the OpenCode auth store has no entry for this provider",
1153
+ subscription_expiring:
1154
+ "the subscription login expires before the review would finish",
1109
1155
  "env-absent": "the secret is not set",
1110
1156
  };
1111
1157
 
@@ -1166,6 +1212,10 @@ const CLAUDE_SUBSCRIPTION_FIXES = [
1166
1212
  "Log in again with `claude setup-token`, then set `CRYSK_CLAUDE_OAUTH_TOKEN`:",
1167
1213
  "$ claude setup-token && gh secret set CRYSK_CLAUDE_OAUTH_TOKEN",
1168
1214
  ];
1215
+ // An OpenCode route uses an OpenAI subscription record while its _OAUTH secret is passed
1216
+ // (chooseOpenCodeSecret, subscription first), so billing per token needs both steps.
1217
+ const OPENAI_API_KEY_INSTEAD =
1218
+ "Or bill per token: set CRYSK_OPENCODE_OPENAI_API_KEY and stop passing {secret} in the crysk-secrets input (the subscription is used while it is passed):";
1169
1219
  const OPENCODE_SUBSCRIPTION_FIXES = [
1170
1220
  "Provider `openai` expects a ChatGPT login: run `opencode auth login` and choose ChatGPT, then set its record, base64 on one line (on macOS, drop -w0):",
1171
1221
  "$ opencode auth login",
@@ -1305,6 +1355,7 @@ const OPENCODE_CREDENTIAL_FIXES = [
1305
1355
  // the inputs above. The scaffolded workflow (src/ci/setup.ts) writes these lines, so
1306
1356
  // a fix that quotes them cannot disagree with the file the person has.
1307
1357
  export const MODELS_INPUT_LINE = "models: $" + "{{ vars.CRYSK_MODELS }}";
1358
+ export const PROFILE_INPUT_LINE = "profile: $" + "{{ vars.CRYSK_PROFILE }}";
1308
1359
  export const CREDENTIALS_INPUT_LINE =
1309
1360
  "credentials: $" + "{{ vars.CRYSK_CREDENTIALS }}";
1310
1361
  // One line of the crysk-secrets input as a workflow writes it, spliced like the
@@ -1429,6 +1480,19 @@ export const ERROR_CATALOG: Readonly<Record<ErrorCode, CatalogEntry>> = {
1429
1480
  ? "run `opencode auth login` and choose ChatGPT for provider `openai`, then set CRYSK_OPENCODE_OPENAI_OAUTH from its record, or set CRYSK_OPENCODE_OPENAI_API_KEY to bill per token"
1430
1481
  : "log in again with `claude setup-token` and set `CRYSK_CLAUDE_OAUTH_TOKEN` (`gh secret set CRYSK_CLAUDE_OAUTH_TOKEN`)",
1431
1482
  },
1483
+ // The review would outlive the login's access token, and a review never renews
1484
+ // a rotating provider's login itself (src/security/oauth-providers.ts).
1485
+ subscription_expiring: {
1486
+ what: "The {provider} subscription login for {step} expires before the review would finish",
1487
+ why: "A review never renews a subscription login whose provider rotates its refresh token: renewing it inside the run would spend the stored login and lose the new one with the run's copy",
1488
+ fixes: [
1489
+ "On a repository connected to Crysk, the platform renews the login before it expires. If it did not, reconnect the provider in the Crysk dashboard.",
1490
+ "On a workflow you manage yourself, run `opencode auth login` again and set the `CRYSK_OPENCODE_<PROVIDER>_OAUTH` secret from its new record: the secret is a snapshot, and nothing renews it for you.",
1491
+ "Locally, run any `opencode` request once (it renews your login in place), or `opencode auth login` again.",
1492
+ ],
1493
+ annotationFix:
1494
+ "reconnect {provider} in the Crysk dashboard, or on a self-managed workflow run `opencode auth login` and set its `_OAUTH` secret again",
1495
+ },
1432
1496
  malformed_payload: {
1433
1497
  // WHY no route in the sentence: this class is raised for the OpenCode auth
1434
1498
  // store and for a Claude keychain payload alike, and {detail} names which.
@@ -1487,6 +1551,35 @@ export const ERROR_CATALOG: Readonly<Record<ErrorCode, CatalogEntry>> = {
1487
1551
  annotationFix:
1488
1552
  "log in again with `claude setup-token` and set `{secret}` (`gh secret set {secret}`)",
1489
1553
  },
1554
+ // S7: an OpenCode route names its CRYSK_OPENCODE_* secret, so the fix is that
1555
+ // provider's, never a Claude login.
1556
+ opencode_api_key: {
1557
+ why: "the provider refused the API key in that secret: it is invalid, expired or revoked",
1558
+ fixes: [
1559
+ "Create a new key with the provider and set it:",
1560
+ "$ gh secret set {secret}",
1561
+ "Then ask for a new review:",
1562
+ REVIEW_AGAIN,
1563
+ LEGACY_REVIEW_NOTE,
1564
+ ],
1565
+ annotationFix:
1566
+ "create a new key with the provider and run `gh secret set {secret}`",
1567
+ },
1568
+ opencode_oauth: {
1569
+ why: "the ChatGPT login recorded in that secret is expired or revoked",
1570
+ fixes: [
1571
+ "Log in again with `opencode auth login` and choose ChatGPT, then set the provider's record, base64 on one line (on macOS, drop -w0):",
1572
+ "$ opencode auth login",
1573
+ OPENAI_OAUTH_SECRET,
1574
+ OPENAI_API_KEY_INSTEAD,
1575
+ "$ gh secret set CRYSK_OPENCODE_OPENAI_API_KEY",
1576
+ "Then ask for a new review:",
1577
+ REVIEW_AGAIN,
1578
+ LEGACY_REVIEW_NOTE,
1579
+ ],
1580
+ annotationFix:
1581
+ "log in again with `opencode auth login`, choose ChatGPT and set {secret} from its record, or set CRYSK_OPENCODE_OPENAI_API_KEY and stop passing {secret} to bill per token",
1582
+ },
1490
1583
  default: {
1491
1584
  why: "it is expired, revoked, or a short-lived /login session token",
1492
1585
  fixes: [
@@ -1588,6 +1681,20 @@ export const ERROR_CATALOG: Readonly<Record<ErrorCode, CatalogEntry>> = {
1588
1681
  annotationFix:
1589
1682
  "fix the credentials JSON ({detail}) and set it again with `gh variable set CRYSK_CREDENTIALS`, the variable the workflow passes as `vars.CRYSK_CREDENTIALS`",
1590
1683
  },
1684
+ // The `profile` input, from vars.CRYSK_PROFILE (openai-profile S6).
1685
+ "profile-input": {
1686
+ what: "The profile input is invalid: {detail}",
1687
+ why: "Crysk refuses to guess which models the review should run",
1688
+ fixes: [
1689
+ "Set the variable to a known profile, for example:",
1690
+ "$ gh variable set CRYSK_PROFILE --body openai",
1691
+ `The workflow passes it as \`${PROFILE_INPUT_LINE}\`.`,
1692
+ "Then re-run the workflow:",
1693
+ "$ gh run rerun {runId}",
1694
+ ],
1695
+ annotationFix:
1696
+ "set a known profile ({detail}) with `gh variable set CRYSK_PROFILE`, the variable the workflow passes as `vars.CRYSK_PROFILE`",
1697
+ },
1591
1698
  },
1592
1699
  },
1593
1700
  "CRYSK-TOKEN-PERMISSION": {
@@ -1779,6 +1886,34 @@ export const ERROR_CATALOG: Readonly<Record<ErrorCode, CatalogEntry>> = {
1779
1886
  annotationFix:
1780
1887
  "re-run after the limit resets, or set CRYSK_CLAUDE_API_KEY and put api_key first in `credentials.claude` to bill per token",
1781
1888
  },
1889
+ // S7: the OpenCode secret every failed hunter ran on. The OpenCode transport reports
1890
+ // no provider words, so these sentences name the secret instead of quoting them.
1891
+ opencode_api_key: {
1892
+ what: "the account behind {secret} reached a rate limit or quota",
1893
+ why: "the provider refuses requests on this key until the limit resets or the account has credit again, so an immediate retry would fail the same way",
1894
+ fixes: [
1895
+ "Wait for the limit to reset, or add credit or raise the quota on the provider account behind the key, then ask for a new review:",
1896
+ REVIEW_AGAIN,
1897
+ LEGACY_REVIEW_NOTE,
1898
+ "Or set a key from an account that has quota:",
1899
+ "$ gh secret set {secret}",
1900
+ ],
1901
+ annotationFix:
1902
+ "wait for the limit to reset or add credit to the provider account behind {secret}, or set another key with `gh secret set {secret}`",
1903
+ },
1904
+ opencode_oauth: {
1905
+ what: "the ChatGPT subscription behind {secret} reached its usage limit",
1906
+ why: "the subscription refuses requests until its usage window resets, so an immediate retry would fail the same way",
1907
+ fixes: [
1908
+ "Re-run after the limit resets:",
1909
+ REVIEW_AGAIN,
1910
+ LEGACY_REVIEW_NOTE,
1911
+ OPENAI_API_KEY_INSTEAD,
1912
+ "$ gh secret set CRYSK_OPENCODE_OPENAI_API_KEY",
1913
+ ],
1914
+ annotationFix:
1915
+ "re-run after the limit resets, or set CRYSK_OPENCODE_OPENAI_API_KEY and stop passing {secret} to bill per token",
1916
+ },
1782
1917
  },
1783
1918
  },
1784
1919
  "CRYSK-PROVIDER-UNAVAILABLE": {
@@ -1932,6 +2067,18 @@ export function renderHunterCause(
1932
2067
  // subscription window by waiting for its reset. Without the words the default wording
1933
2068
  // stands.
1934
2069
  if (cause === "quota_exhausted") {
2070
+ // An OpenCode secret names its own fix with or without the provider's words: the
2071
+ // OpenCode transport reports no detail today, and the Claude variants below would
2072
+ // send the user to the Anthropic account.
2073
+ const openCode = openCodeCredentialVariant(shared.credential);
2074
+ if (openCode !== undefined && shared.credential !== undefined) {
2075
+ return renderCode(
2076
+ "CRYSK-PROVIDER-LIMITED",
2077
+ { ...params, secret: secretNameOf(shared.credential, ctx) },
2078
+ ctx,
2079
+ openCode,
2080
+ );
2081
+ }
1935
2082
  if (shared.detail === undefined) {
1936
2083
  return renderCode("CRYSK-PROVIDER-LIMITED", params, ctx);
1937
2084
  }
@@ -1963,8 +2110,9 @@ export function renderHunterCause(
1963
2110
  // variable was filled from the CRYSK_* secret the workflow passes in the
1964
2111
  // crysk-secrets input (S8, U5), so `gh secret set` must name that secret. A local
1965
2112
  // run exports the CLI's variable itself, so it keeps that name.
2113
+ // An OpenCode credential already is the CRYSK_* secret (S7), so it is named as it is.
1966
2114
  const CRYSK_SECRET_OF_CREDENTIAL: Readonly<
1967
- Partial<Record<FailureCredential, string>>
2115
+ Partial<Record<ClaudeFailureCredential, string>>
1968
2116
  > = {
1969
2117
  ANTHROPIC_API_KEY: "CRYSK_CLAUDE_API_KEY",
1970
2118
  CLAUDE_CODE_OAUTH_TOKEN: "CRYSK_CLAUDE_OAUTH_TOKEN",
@@ -1973,7 +2121,7 @@ function secretNameOf(
1973
2121
  credential: FailureCredential,
1974
2122
  ctx: OutcomeContext,
1975
2123
  ): string {
1976
- if (ctx !== "action") return credential;
2124
+ if (ctx !== "action" || isOpenCodeCredential(credential)) return credential;
1977
2125
  return CRYSK_SECRET_OF_CREDENTIAL[credential] ?? credential;
1978
2126
  }
1979
2127
 
@@ -2058,6 +2206,8 @@ function paramVariant(
2058
2206
  ) {
2059
2207
  return "oauth";
2060
2208
  }
2209
+ const openCode = openCodeCredentialVariant(params.secret);
2210
+ if (openCode !== undefined) return openCode;
2061
2211
  }
2062
2212
  // A caller that names a variant keeps it, so the default wording stays
2063
2213
  // reachable with a detail present.
@@ -19,8 +19,24 @@
19
19
  // WHY ONLY BUILTINS: like the trigger, this runs before `bun install`. Keep
20
20
  // every import `node:` or `bun`, and `fetch` is the runtime's own.
21
21
 
22
- import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
22
+ import {
23
+ appendFileSync,
24
+ existsSync,
25
+ mkdirSync,
26
+ readFileSync,
27
+ writeFileSync,
28
+ } from "node:fs";
23
29
  import path from "node:path";
30
+ // Import-free, like the registry below.
31
+ import { readBrandEnv } from "../brand";
32
+ // The profile registry: data modules with no runtime imports of their own
33
+ // (test/architecture/profile-registry.test.ts), so the builtins-only rule still
34
+ // holds, and the step reads the same profiles the review runs.
35
+ import {
36
+ FALLBACK_PROFILE_ID,
37
+ MODEL_PROFILES,
38
+ profileModels,
39
+ } from "../model/profiles";
24
40
  // A sibling with no imports of its own, so the builtins-only rule still holds.
25
41
  import {
26
42
  PLATFORM_ESTIMATE_CAPABILITY,
@@ -31,6 +47,18 @@ import {
31
47
 
32
48
  export const PLATFORM_API_URL = "https://api.crysk.dev";
33
49
 
50
+ // The engine accepts the person config's `profile` key (openai-profile S7). An
51
+ // engine without it refuses the key as unknown, so the platform sends a
52
+ // profile only to a run that names this capability.
53
+ export const PLATFORM_PROFILE_CAPABILITY = "profile";
54
+
55
+ // What this engine reads from the `/runs/token` response, as the platform's
56
+ // comma-separated `X-Crysk-Capabilities` list.
57
+ export const PLATFORM_CAPABILITIES = [
58
+ PLATFORM_ESTIMATE_CAPABILITY,
59
+ PLATFORM_PROFILE_CAPABILITY,
60
+ ].join(",");
61
+
34
62
  // The audience the platform verifies. An OIDC token minted for any other
35
63
  // audience is refused with a 401.
36
64
  const OIDC_AUDIENCE = "crysk";
@@ -105,6 +133,39 @@ export function parsePlatformConfig(
105
133
  // says. `full` is the only value that lets the report step send finding text.
106
134
  export type PlatformDataMode = "full" | "metadata_only";
107
135
 
136
+ // The PR comment command the platform dispatched this run for (odd/tasks/platform-commands.md
137
+ // in the platform repo, S2-S4). A platform-managed repository has no issue_comment trigger, so the
138
+ // platform checks the comment and its author, and names the command here; the trigger reads it
139
+ // from this step's outputs. Absent for an ordinary review, and for a name this engine does not know.
140
+ // An override keeps its name when the actor or head is unusable, so the trigger refuses it instead
141
+ // of running a review nobody asked for.
142
+ export type PlatformCommandAnswer =
143
+ | { name: "recheck" }
144
+ | { name: "override"; actor?: string; headSha?: string };
145
+
146
+ const SAFE_SHA = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
147
+ // The override's actor is a commenter, who may be an Enterprise Managed User (`handle_shortcode`):
148
+ // the trigger's own GITHUB_LOGIN grammar (src/ci/trigger.ts), not SAFE_LOGIN, which is the App's.
149
+ const COMMAND_ACTOR = /^(?=.{1,91}$)[A-Za-z0-9][A-Za-z0-9_-]{0,90}(\[bot\])?$/;
150
+
151
+ function parsePlatformCommand(
152
+ value: unknown,
153
+ ): PlatformCommandAnswer | undefined {
154
+ if (typeof value !== "object" || value === null) return undefined;
155
+ const { name, actor, head_sha: headSha } = value as Record<string, unknown>;
156
+ if (name === "recheck") return { name };
157
+ if (name !== "override") return undefined;
158
+ return {
159
+ name,
160
+ ...(typeof actor === "string" && COMMAND_ACTOR.test(actor)
161
+ ? { actor }
162
+ : {}),
163
+ ...(typeof headSha === "string" && SAFE_SHA.test(headSha)
164
+ ? { headSha }
165
+ : {}),
166
+ };
167
+ }
168
+
108
169
  export type PlatformTokenResult =
109
170
  // `githubActor` is the login the platform says posts as the App's bot. It is
110
171
  // absent when the platform sent none or one that is not a plausible login.
@@ -124,6 +185,7 @@ export type PlatformTokenResult =
124
185
  traceContent?: true;
125
186
  config?: PlatformConfig;
126
187
  estimate?: PlatformEstimate;
188
+ command?: PlatformCommandAnswer;
127
189
  }
128
190
  // `message` names the HTTP status and the API's own `message` when there was
129
191
  // one. It never carries a token.
@@ -246,10 +308,11 @@ export async function exchangePlatformToken(
246
308
  Authorization: `Bearer ${oidc}`,
247
309
  "X-Crysk-Dispatch-Id": dispatchId,
248
310
  // Only the first connect step asks: its estimate is the one the budget
249
- // gate reads, and the platform records each estimate it sends.
311
+ // gate reads, the platform records each estimate it sends, and only
312
+ // that step reads the config a profile arrives in.
250
313
  ...(deps.ignoreConfig === true
251
314
  ? {}
252
- : { "X-Crysk-Capabilities": PLATFORM_ESTIMATE_CAPABILITY }),
315
+ : { "X-Crysk-Capabilities": PLATFORM_CAPABILITIES }),
253
316
  },
254
317
  signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
255
318
  });
@@ -268,6 +331,7 @@ export async function exchangePlatformToken(
268
331
  trace_content?: unknown;
269
332
  config?: unknown;
270
333
  estimate?: unknown;
334
+ command?: unknown;
271
335
  };
272
336
  const {
273
337
  github_token: githubToken,
@@ -303,6 +367,7 @@ export async function exchangePlatformToken(
303
367
  }
304
368
  // An estimate is advice: one that does not parse is dropped and the
305
369
  // engine's own band decides, never a failed exchange.
370
+ const command = parsePlatformCommand(body.command);
306
371
  const estimate =
307
372
  deps.ignoreConfig === true
308
373
  ? undefined
@@ -323,6 +388,7 @@ export async function exchangePlatformToken(
323
388
  ...(body.trace_content === true ? { traceContent: true as const } : {}),
324
389
  ...(config.config === undefined ? {} : { config: config.config }),
325
390
  ...(estimate === undefined ? {} : { estimate }),
391
+ ...(command === undefined ? {} : { command }),
326
392
  };
327
393
  } catch (error) {
328
394
  const detail = error instanceof Error ? error.message : String(error);
@@ -425,6 +491,19 @@ export async function runPlatformConnect(
425
491
  if (result.githubActor !== undefined) {
426
492
  deps.appendOutput(`github-actor=${result.githubActor}\n`);
427
493
  }
494
+ // Not a secret: a known command name, a validated login and a validated sha. The trigger
495
+ // reads them as PLATFORM_COMMAND* (action.yml), from the first connect step only.
496
+ if (result.command !== undefined) {
497
+ deps.appendOutput(`command=${result.command.name}\n`);
498
+ if (result.command.name === "override") {
499
+ if (result.command.actor !== undefined) {
500
+ deps.appendOutput(`command-actor=${result.command.actor}\n`);
501
+ }
502
+ if (result.command.headSha !== undefined) {
503
+ deps.appendOutput(`command-head=${result.command.headSha}\n`);
504
+ }
505
+ }
506
+ }
428
507
  // Not a secret: two validated numbers and a basis. The run step's budget
429
508
  // gate reads it as CRYSK_PLATFORM_ESTIMATE in place of the engine's band.
430
509
  if (result.estimate !== undefined) {
@@ -449,10 +528,21 @@ export async function runPlatformConnect(
449
528
  // platform `routing` is refused by the setup step's person parser.
450
529
  const person = result.config?.person ?? {};
451
530
  if (Object.keys(person).length > 0) {
452
- const models = person.models;
453
- const opencode =
454
- models !== undefined && JSON.stringify(models).includes('"opencode:');
455
- deps.appendOutput(`routing-opencode=${opencode}\n`);
531
+ const customAgents = customAgentsMayApply(
532
+ person,
533
+ result.config?.repo ?? {},
534
+ deps.env,
535
+ );
536
+ deps.appendOutput(
537
+ `routing-opencode=${personMayNeedOpenCode(person)}\n`,
538
+ );
539
+ // Whether any step may run on the Claude CLI (model-profiles S6). The
540
+ // Install Claude Code CLI step skips only on exactly `false`, so an
541
+ // absent output (a standalone run, an empty person layer, an older
542
+ // engine) installs it, as every run always did.
543
+ deps.appendOutput(
544
+ `routing-claude=${personMayNeedClaude(person, { customAgents })}\n`,
545
+ );
456
546
  }
457
547
  }
458
548
  } catch (error) {
@@ -465,6 +555,114 @@ export async function runPlatformConnect(
465
555
  return 0;
466
556
  }
467
557
 
558
+ // Whether the person layer's `models` may send any step to the Claude CLI.
559
+ // `false` only when it is proven not to: a `default` list, so no role falls
560
+ // through to the `claude` profile, and every entry of every role, fallbacks and
561
+ // the judge included, an `opencode:` model. With no `models.judge` the judge
562
+ // joins a plan only beside a step on its own backend (routing.ts), so it stays
563
+ // off Claude here whatever `materiality_gate` says. Anything else, a shape this
564
+ // walk does not know included, is `true`: the engine's parser stays the
565
+ // authority (this step cannot import it), and a wrong `false` would leave a
566
+ // Claude run without its CLI. src/doctor.ts reviewNeedsClaude answers the same
567
+ // question from the real route plan; test/ci/platform.test.ts holds both to
568
+ // one table.
569
+ //
570
+ // A role `models` does not set runs the person's `profile` (openai-profile S6),
571
+ // so with no `models.default` the answer is the profile's: `false` only for a
572
+ // registered profile whose every route is OpenCode. No profile is the fallback
573
+ // profile, `claude`; an unknown one is `true`, and the engine refuses it.
574
+ export function personModelsMayNeedClaude(
575
+ models: unknown,
576
+ profile?: unknown,
577
+ ): boolean {
578
+ if (models !== undefined) {
579
+ if (!isPlainObject(models)) return true;
580
+ for (const list of Object.values(models)) {
581
+ if (!Array.isArray(list) || list.length === 0) return true;
582
+ for (const entry of list) {
583
+ const name = isPlainObject(entry) ? entry.model : entry;
584
+ if (typeof name !== "string" || !name.startsWith("opencode:")) {
585
+ return true;
586
+ }
587
+ }
588
+ }
589
+ if (Array.isArray(models.default)) return false;
590
+ }
591
+ const routes = profileRouteModels(profile);
592
+ return routes === undefined || routes.some((m) => !m.startsWith("opencode:"));
593
+ }
594
+
595
+ // Whether the models in effect run any step on OpenCode: an `opencode:` model
596
+ // in `models`, or, for a role `models` does not set, in the profile's routes.
597
+ export function personMayNeedOpenCode(
598
+ person: Record<string, unknown>,
599
+ ): boolean {
600
+ const models = person.models;
601
+ if (models !== undefined && JSON.stringify(models).includes('"opencode:')) {
602
+ return true;
603
+ }
604
+ if (isPlainObject(models) && Array.isArray(models.default)) return false;
605
+ return (profileRouteModels(person.profile) ?? []).some((m) =>
606
+ m.startsWith("opencode:"),
607
+ );
608
+ }
609
+
610
+ // The registered profile's route models, or undefined for one this step does
611
+ // not know (the engine's parser refuses it).
612
+ function profileRouteModels(profile: unknown): string[] | undefined {
613
+ const id = profile ?? FALLBACK_PROFILE_ID;
614
+ if (typeof id !== "string" || !Object.hasOwn(MODEL_PROFILES, id)) {
615
+ return undefined;
616
+ }
617
+ const registered = MODEL_PROFILES[id];
618
+ return registered === undefined ? undefined : profileModels(registered);
619
+ }
620
+
621
+ // The person layer's answer: its `models`, plus the one other way a person
622
+ // layer names a model. A legacy `summary.model` (only "haiku" parses) becomes
623
+ // `models.summary: claude:haiku-latest` when `models.summary` is absent
624
+ // (preflight.ts parseSummaryConfig), so any `summary.model` keeps the CLI.
625
+ //
626
+ // `customAgents` (PR #521 R003): a custom agents_dir's frontmatter outranks
627
+ // the profile's seat (routing.ts resolveStepChoices), and this step cannot
628
+ // read those prompts, so with no `models.default` the CLI stays required.
629
+ export function personMayNeedClaude(
630
+ person: Record<string, unknown>,
631
+ context: { customAgents?: boolean } = {},
632
+ ): boolean {
633
+ if (isPlainObject(person.summary) && "model" in person.summary) return true;
634
+ const coversEveryRole =
635
+ isPlainObject(person.models) && Array.isArray(person.models.default);
636
+ if (context.customAgents === true && !coversEveryRole) return true;
637
+ return personModelsMayNeedClaude(person.models, person.profile);
638
+ }
639
+
640
+ // Whether a custom agents_dir may apply to this run: named in the platform's
641
+ // person or repo layer, in the checkout's own repo config (read raw, since this
642
+ // step runs before `bun install`), or in the AGENTS_DIR env. A repo config this
643
+ // step cannot read counts as one: the answer must never be a wrong `false`.
644
+ export function customAgentsMayApply(
645
+ person: Record<string, unknown>,
646
+ repo: Record<string, unknown>,
647
+ env: Readonly<Record<string, string | undefined>>,
648
+ ): boolean {
649
+ if ("agents_dir" in person || "agents_dir" in repo) return true;
650
+ if ((readBrandEnv(env, "AGENTS_DIR")?.value ?? "") !== "") return true;
651
+ const workspace = env.GITHUB_WORKSPACE ?? "";
652
+ if (workspace === "") return false;
653
+ for (const dir of [".crysk", ".prhero"]) {
654
+ const file = path.join(workspace, dir, "config.json");
655
+ if (!existsSync(file)) continue;
656
+ try {
657
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
658
+ return !isPlainObject(parsed) || "agents_dir" in parsed;
659
+ } catch {
660
+ return true;
661
+ }
662
+ }
663
+ return false;
664
+ }
665
+
468
666
  // Appends to the file the runner named in GITHUB_OUTPUT. Unset or empty is an
469
667
  // error, not a no-op: see runPlatformConnect.
470
668
  export function appendGithubOutput(