crysk 0.0.0 → 0.3.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 (229) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +609 -3
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/adjudicator-dtg2axnh.md +86 -0
  10. package/dist/admission-config.example-a9vqmmad.json +9 -0
  11. package/dist/ci-admission-camfbx2b.md +122 -0
  12. package/dist/cli.js +42292 -0
  13. package/dist/consolidate-ac0mnfyj.md +24 -0
  14. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  15. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  16. package/dist/deep-review-parity-0ec904db.md +120 -0
  17. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  18. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  19. package/dist/index.js +20190 -0
  20. package/dist/opencode-ci-7b0be64p.md +141 -0
  21. package/dist/review-refuter-j4e9gezy.md +71 -0
  22. package/dist/scout-yvp153q7.md +140 -0
  23. package/dist/summarizer-zca44nxa.md +18 -0
  24. package/dist/workflow-w1g9szna.yml +151 -0
  25. package/package.json +81 -4
  26. package/prompts/consolidate.md +24 -0
  27. package/prompts/default/PROVENANCE.md +18 -0
  28. package/prompts/default/deep-review-lifecycle.md +362 -0
  29. package/prompts/default/deep-review-logic.md +156 -0
  30. package/prompts/default/deep-review-parity.md +120 -0
  31. package/prompts/default/deep-review-reliability.md +125 -0
  32. package/prompts/default/deep-review-resilience.md +118 -0
  33. package/prompts/default/review-refuter.md +71 -0
  34. package/prompts/scout.md +140 -0
  35. package/prompts/summarizer.md +18 -0
  36. package/skills/crysk/SKILL.md +74 -0
  37. package/skills/crysk-ci-setup/SKILL.md +134 -0
  38. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  39. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  40. package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
  41. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  42. package/skills/crysk-loop/SKILL.md +496 -0
  43. package/skills/crysk-loop/adjudicator.md +86 -0
  44. package/skills/crysk-pr/SKILL.md +66 -0
  45. package/src/agent-env.ts +1084 -0
  46. package/src/asset-manifest.ts +83 -0
  47. package/src/assets.d.ts +6 -0
  48. package/src/assets.ts +183 -0
  49. package/src/brand-paths.ts +155 -0
  50. package/src/brand.ts +255 -0
  51. package/src/ci/admission-ledger.ts +350 -0
  52. package/src/ci/classify-error.ts +73 -0
  53. package/src/ci/cli-record.ts +271 -0
  54. package/src/ci/force-comment.ts +39 -0
  55. package/src/ci/gates.ts +923 -0
  56. package/src/ci/outcome.ts +2181 -0
  57. package/src/ci/override.ts +187 -0
  58. package/src/ci/publish.ts +1639 -0
  59. package/src/ci/reporter.ts +626 -0
  60. package/src/ci/review-admission.ts +901 -0
  61. package/src/ci/review-levels.ts +310 -0
  62. package/src/ci/review-policy.ts +18 -0
  63. package/src/ci/review-risk.ts +184 -0
  64. package/src/ci/setup.ts +844 -0
  65. package/src/ci/trigger.ts +1353 -0
  66. package/src/cli.ts +348 -0
  67. package/src/commands/activity.ts +67 -0
  68. package/src/commands/ci-setup-questions.ts +397 -0
  69. package/src/commands/ci-setup.ts +381 -0
  70. package/src/commands/config.ts +99 -0
  71. package/src/commands/doctor.ts +108 -0
  72. package/src/commands/init.ts +139 -0
  73. package/src/commands/mcp.ts +10 -0
  74. package/src/commands/menu.ts +129 -0
  75. package/src/commands/post.ts +302 -0
  76. package/src/commands/skills.ts +83 -0
  77. package/src/commands/status.ts +173 -0
  78. package/src/commands/triage.ts +342 -0
  79. package/src/commands/uninstall.ts +37 -0
  80. package/src/commands/upgrade.ts +214 -0
  81. package/src/commands/usage.ts +98 -0
  82. package/src/compare/compare.ts +28 -0
  83. package/src/compare/floor-test.ts +471 -0
  84. package/src/compare/martian-adapter.ts +80 -0
  85. package/src/config/config.ts +267 -0
  86. package/src/corpus/corpus.ts +1094 -0
  87. package/src/corpus/preflight.ts +1789 -0
  88. package/src/diversity/accounting.ts +90 -0
  89. package/src/diversity/adjudication.ts +145 -0
  90. package/src/diversity/admission.ts +60 -0
  91. package/src/diversity/benchmark.ts +195 -0
  92. package/src/diversity/clustering.ts +285 -0
  93. package/src/diversity/errors.ts +7 -0
  94. package/src/diversity/identity.ts +285 -0
  95. package/src/diversity/index.ts +11 -0
  96. package/src/diversity/pipeline-integration.ts +448 -0
  97. package/src/diversity/projection.ts +57 -0
  98. package/src/diversity/self-contained.ts +68 -0
  99. package/src/diversity/target-validation.ts +179 -0
  100. package/src/doctor-migration.ts +209 -0
  101. package/src/doctor.ts +723 -0
  102. package/src/errors.ts +83 -0
  103. package/src/execution/admission.ts +75 -0
  104. package/src/execution/atomic-write.ts +35 -0
  105. package/src/execution/attempt-evidence.ts +415 -0
  106. package/src/execution/bucket-id.ts +136 -0
  107. package/src/execution/concurrency-limiter.ts +175 -0
  108. package/src/execution/contracts.ts +443 -0
  109. package/src/execution/failure-classification.ts +42 -0
  110. package/src/execution/failure-policy.ts +240 -0
  111. package/src/execution/harness.ts +2548 -0
  112. package/src/execution/settlement.ts +348 -0
  113. package/src/execution/spawned-process.ts +66 -0
  114. package/src/execution/spend-limiter.ts +424 -0
  115. package/src/execution/step-artifacts.ts +55 -0
  116. package/src/execution/usage-normalized.ts +469 -0
  117. package/src/git/git.ts +396 -0
  118. package/src/git/identity.ts +64 -0
  119. package/src/git/refs.ts +140 -0
  120. package/src/home-preflight.ts +443 -0
  121. package/src/home.ts +243 -0
  122. package/src/ignore-file.ts +336 -0
  123. package/src/ignore-read.ts +118 -0
  124. package/src/index.ts +34 -0
  125. package/src/legacy-launchd.ts +29 -0
  126. package/src/mcp/mcp.ts +150 -0
  127. package/src/mcp/preflight.ts +407 -0
  128. package/src/menu-context.ts +192 -0
  129. package/src/model/catalog.ts +251 -0
  130. package/src/model/exec-snapshots.ts +390 -0
  131. package/src/model/free-discovery.ts +302 -0
  132. package/src/model/provider-capabilities.ts +814 -0
  133. package/src/model/routing.ts +600 -0
  134. package/src/pr/admission.ts +847 -0
  135. package/src/pr/ci-admission-gate.ts +665 -0
  136. package/src/pr/ci-publish.ts +76 -0
  137. package/src/pr/discovery.ts +432 -0
  138. package/src/pr/inline.ts +507 -0
  139. package/src/pr/plan.ts +366 -0
  140. package/src/pr/posting.ts +115 -0
  141. package/src/pr/pr-status.ts +787 -0
  142. package/src/pr/pr.ts +3642 -0
  143. package/src/pr/preflight.ts +1031 -0
  144. package/src/pr/publish-outcome.ts +361 -0
  145. package/src/pr/range.ts +119 -0
  146. package/src/pr/reverts-preflight.ts +606 -0
  147. package/src/pr/reverts.ts +377 -0
  148. package/src/pr/review-pr.ts +927 -0
  149. package/src/pr/status.ts +154 -0
  150. package/src/pr/target.ts +388 -0
  151. package/src/pr/teardown.ts +437 -0
  152. package/src/pr/worktree-setup.ts +60 -0
  153. package/src/production-runtime.ts +1877 -0
  154. package/src/progress.ts +487 -0
  155. package/src/rereview/adjudicate.ts +89 -0
  156. package/src/rereview/classify.ts +362 -0
  157. package/src/rereview/identity.ts +211 -0
  158. package/src/rereview/plan.ts +308 -0
  159. package/src/rereview/prepare.ts +1025 -0
  160. package/src/rereview/state.ts +767 -0
  161. package/src/rereview/verify.ts +241 -0
  162. package/src/review/boundary.ts +105 -0
  163. package/src/review/consolidate.ts +246 -0
  164. package/src/review/dedupe.ts +368 -0
  165. package/src/review/drafts.ts +448 -0
  166. package/src/review/findings-conformance.ts +120 -0
  167. package/src/review/findings.ts +714 -0
  168. package/src/review/pipeline.ts +3977 -0
  169. package/src/review/preflight.ts +3575 -0
  170. package/src/review/prompt-set.ts +177 -0
  171. package/src/review/proof-refs.ts +187 -0
  172. package/src/review/report.ts +1821 -0
  173. package/src/review/review.ts +490 -0
  174. package/src/review/root-cause.ts +120 -0
  175. package/src/review/route-preflight.ts +289 -0
  176. package/src/review/run.ts +601 -0
  177. package/src/review/scout.ts +323 -0
  178. package/src/review/size-gate.ts +595 -0
  179. package/src/review/spec.ts +235 -0
  180. package/src/review/step-runner.ts +233 -0
  181. package/src/runner-authority.ts +596 -0
  182. package/src/security/binding-policy.ts +115 -0
  183. package/src/security/credential-broker.ts +773 -0
  184. package/src/security/evidence-redaction.ts +62 -0
  185. package/src/security/execution-authority.ts +27 -0
  186. package/src/security/redact.ts +71 -0
  187. package/src/security/workspace-read-broker.ts +466 -0
  188. package/src/server/client.ts +190 -0
  189. package/src/server/preflight.ts +217 -0
  190. package/src/server/server.ts +327 -0
  191. package/src/signal-handler.ts +50 -0
  192. package/src/store/activity.ts +413 -0
  193. package/src/store/backfill-preflight.ts +49 -0
  194. package/src/store/backfill.ts +141 -0
  195. package/src/store/gc-preflight.ts +206 -0
  196. package/src/store/gc.ts +424 -0
  197. package/src/store/metrics-preflight.ts +229 -0
  198. package/src/store/metrics.ts +236 -0
  199. package/src/store/preflight.ts +748 -0
  200. package/src/store/store.ts +693 -0
  201. package/src/system-tools.ts +355 -0
  202. package/src/transport-registry.ts +1124 -0
  203. package/src/transports/claude-code-cli.ts +1348 -0
  204. package/src/transports/opencode-admission.ts +515 -0
  205. package/src/transports/opencode-client.ts +3328 -0
  206. package/src/transports/opencode-evidence.ts +557 -0
  207. package/src/transports/opencode-mcp.ts +248 -0
  208. package/src/transports/opencode-sdk.ts +2294 -0
  209. package/src/transports/opencode-server.ts +535 -0
  210. package/src/triage/adjudication.ts +113 -0
  211. package/src/triage/reply.ts +125 -0
  212. package/src/triage/triage.ts +255 -0
  213. package/src/ui/activity.ts +173 -0
  214. package/src/ui/config-edit.ts +816 -0
  215. package/src/ui/config.ts +462 -0
  216. package/src/ui/menu.ts +1325 -0
  217. package/src/ui/plan.ts +1039 -0
  218. package/src/ui/primitives.ts +300 -0
  219. package/src/ui/progress.ts +298 -0
  220. package/src/ui/result.ts +552 -0
  221. package/src/ui/review-menu.ts +312 -0
  222. package/src/ui/select.ts +528 -0
  223. package/src/ui/tree.ts +178 -0
  224. package/src/uninstaller.ts +479 -0
  225. package/src/updater.ts +836 -0
  226. package/src/usage.ts +77 -0
  227. package/src/watch/preflight.ts +1389 -0
  228. package/src/watch/watch.ts +1235 -0
  229. package/src/wizard.ts +877 -0
@@ -0,0 +1,600 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { ResolvedModelRoute, RunnerBackend } from "../execution/contracts";
3
+ import { redactDiagnostic } from "../security/redact";
4
+ import {
5
+ isModelAlias,
6
+ lookupAlias,
7
+ type ModelAlias,
8
+ reverseAliasForCanonical,
9
+ } from "./catalog";
10
+
11
+ export type ModelGateway = "configured" | "direct" | "openrouter";
12
+ export type { ResolvedModelRoute, RunnerBackend };
13
+
14
+ export interface RouteMapping {
15
+ readonly logical?: string;
16
+ readonly backend: RunnerBackend;
17
+ readonly provider: string;
18
+ readonly gateway?: ModelGateway;
19
+ readonly modelFamily?: string;
20
+ readonly modelSnapshot?: string;
21
+ readonly modelVariant?: string;
22
+ readonly disabled?: boolean;
23
+ readonly allowSpend?: boolean;
24
+ }
25
+
26
+ export interface RoutingConfig {
27
+ readonly default?: RouteMapping;
28
+ readonly mappings?: readonly RouteMapping[] | Record<string, RouteMapping>;
29
+ readonly disabled?: boolean;
30
+ }
31
+
32
+ function mappingNeedsOpenCodeSdk(mapping: RouteMapping | undefined): boolean {
33
+ if (mapping === undefined) return false;
34
+ return (
35
+ mapping.backend === "opencode" &&
36
+ mapping.disabled !== true &&
37
+ mapping.allowSpend !== false
38
+ );
39
+ }
40
+
41
+ // Spend that would actually open an OpenCode transport. A disabled route,
42
+ // a mapping that refuses spend, or no routing at all does not.
43
+ export function routingNeedsOpenCodeSdk(
44
+ routing: RoutingConfig | undefined,
45
+ ): boolean {
46
+ if (routing === undefined || routing.disabled === true) return false;
47
+ if (mappingNeedsOpenCodeSdk(routing.default)) return true;
48
+ const mappings = routing.mappings;
49
+ if (mappings === undefined) return false;
50
+ const entries = Array.isArray(mappings) ? mappings : Object.values(mappings);
51
+ return entries.some((entry) => mappingNeedsOpenCodeSdk(entry));
52
+ }
53
+
54
+ export interface ParsedLogicalIdentity {
55
+ readonly raw: string;
56
+ readonly canonical: string;
57
+ readonly provider: string;
58
+ readonly model: string;
59
+ readonly variant?: string;
60
+ readonly alias?: ModelAlias;
61
+ }
62
+
63
+ export interface ResolvedStepRoute {
64
+ readonly stepKey: string;
65
+ readonly role: string;
66
+ readonly logicalIdentity: string;
67
+ readonly route: ResolvedModelRoute;
68
+ readonly routeFingerprint: string;
69
+ }
70
+
71
+ export interface ResolvedRoutePlan {
72
+ readonly planId?: string;
73
+ readonly steps: readonly ResolvedStepRoute[];
74
+ readonly routeFingerprint?: string;
75
+ }
76
+
77
+ export class ModelRoutingError extends Error {}
78
+ export class UnmappedRouteError extends ModelRoutingError {}
79
+ export class AmbiguousMappingError extends ModelRoutingError {}
80
+ export class UnauthorizedRouteError extends ModelRoutingError {}
81
+
82
+ export type { ModelAlias } from "./catalog";
83
+ export {
84
+ aliasCanonical,
85
+ isModelAlias,
86
+ lookupAlias,
87
+ MODEL_CATALOG,
88
+ } from "./catalog";
89
+
90
+ const SLASH_GRAMMAR_REGEX =
91
+ /^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9._-]+)(?:#([a-zA-Z0-9._-]+))?$/;
92
+
93
+ export function parseLogicalIdentity(raw: string): ParsedLogicalIdentity {
94
+ if (typeof raw !== "string") {
95
+ throw new ModelRoutingError("Model identity must be a string");
96
+ }
97
+ const trimmed = raw.trim();
98
+ if (trimmed.length === 0) {
99
+ throw new ModelRoutingError("Model identity cannot be empty");
100
+ }
101
+
102
+ if (isModelAlias(trimmed)) {
103
+ const aliasInfo = lookupAlias(trimmed);
104
+ return {
105
+ raw: trimmed,
106
+ canonical: aliasInfo.canonical,
107
+ provider: aliasInfo.provider,
108
+ // #175: the alias IS the model segment now. `parsed.model` feeds both
109
+ // `modelFamily` and `modelSnapshot` on the default alias route below,
110
+ // so this is the single line that decides what our provenance claims
111
+ // an alias run used — and after #175 it claims the name that was
112
+ // actually sent to the CLI, not a version we never verified.
113
+ model: aliasInfo.alias,
114
+ alias: trimmed,
115
+ };
116
+ }
117
+
118
+ const match = trimmed.match(SLASH_GRAMMAR_REGEX);
119
+ if (match) {
120
+ const [, provider, model, variant] = match;
121
+ const canonical = `${provider}/${model}${variant ? `#${variant}` : ""}`;
122
+ return {
123
+ raw: trimmed,
124
+ canonical,
125
+ provider,
126
+ model,
127
+ ...(variant !== undefined ? { variant } : {}),
128
+ };
129
+ }
130
+
131
+ const safeRaw = redactDiagnostic(raw);
132
+ throw new ModelRoutingError(
133
+ `Unknown model identity "${safeRaw}": bare model names must be an alias (sonnet|opus|haiku) or use slash grammar provider/model(#variant)`,
134
+ );
135
+ }
136
+
137
+ // #175 follow-up, 2026-09-02. THE ONE PLACE a route's `modelSnapshot` may fall
138
+ // back to the parsed identity. It exists as a function because the fallback had
139
+ // THREE copies — array mappings, record mappings, default mapping — and a guard
140
+ // added to one of them is the "two copies drift" failure this repo keeps paying
141
+ // for.
142
+ //
143
+ // WHAT IT REFUSES, and why refusing is the only honest option: #175 made a bare
144
+ // alias parse to the alias WORD (`parsed.model === "sonnet"`), where it used to
145
+ // parse to a version pinned in our own catalogue. That pin was the lie #175
146
+ // deleted — only the Claude CLI knows what `sonnet` currently means. But the
147
+ // fallback then started handing the bare word to consumers that resolve
148
+ // nothing: `transport-registry.ts` forwards `modelSnapshot` verbatim as the
149
+ // OpenCode SDK's `modelID`, so a `{"sonnet": {"backend": "opencode"}}` config
150
+ // went from sending a real model id to sending the word "sonnet" to a live API.
151
+ //
152
+ // #176 follow-up, 2026-09-02. THE AXIS IS THE GATEWAY, NOT THE BACKEND. This
153
+ // guard's first version refused on `mapping.backend !== "claude-code"`, and
154
+ // that door had a hole the size of the defect it closed: `claude-code` only
155
+ // resolves the alias itself when the route's gateway is `direct`.
156
+ // `spawnModelForClaudeCli` is explicit about it — on any other gateway it
157
+ // returns `route.modelSnapshot` verbatim as `--model`, without ever consulting
158
+ // the alias table. So `{"sonnet": {"backend": "claude-code", "provider":
159
+ // "anthropic"}}` sent `--model sonnet` to a CLI pointed at a gateway that never
160
+ // heard of pr-hero's aliases. The predicate below therefore asks the only
161
+ // question that matters — DOES THE CONSUMER RESOLVE THIS WORD? — which is true
162
+ // in exactly one combination: `claude-code` AND `direct`.
163
+ //
164
+ // AND MIND THE TWO DIVERGENT GATEWAY DEFAULTS, because the divergence IS what
165
+ // let the hole open. Route resolution defaults an absent `gateway` to
166
+ // `"configured"` (the three `?? "configured"` call sites below);
167
+ // `spawnModelForClaudeCli` defaults an absent one to `"direct"` (and so does
168
+ // `report.ts`'s renderer). Those are not the same rule, and only the first one
169
+ // is correct here: this guard runs while the route is being BUILT, so it must
170
+ // use the value the route is about to assert, not the value a later reader
171
+ // would infer from a route that omitted it. Hence `gateway` is passed IN, read
172
+ // off the same `?? "configured"` expression that populates the route's own
173
+ // field — a fourth independent copy of that default inside this helper is
174
+ // exactly the drift this helper exists to prevent.
175
+ //
176
+ // HOW MUCH the old fallback actually got right, measured on `dev` rather than
177
+ // assumed, because it bounds what this guard is restoring: the snapshot came
178
+ // from the CATALOGUE, never from the mapping's `provider`. So `sonnet` ->
179
+ // opencode/`anthropic` did resolve to `claude-sonnet-5`, and that is the config
180
+ // this fix stops breaking — but `sonnet` -> opencode/`openai` sent
181
+ // `claude-sonnet-5` to OpenAI, nonsense before #175 and nonsense after. The
182
+ // guard refuses BOTH, which is why it is a guard and not a restored pin: we
183
+ // cannot know the version, and we must not fabricate one, so the route is
184
+ // refused and the operator is told the one thing that fixes it.
185
+ //
186
+ // THE PREDICATE IS THE ALIAS IDENTITY, not the model segment. `reverseAlias` is
187
+ // set for the bare word AND for its canonical `provider/alias` form — the key
188
+ // shape this repo's own configs use via `aliasCanonical()`, so a guard on the
189
+ // bare word alone would be bypassed by the recommended key. It is unset for
190
+ // slash grammar, where the segment is the operator's own words and forwarding
191
+ // them verbatim is correct. `anthropic/sonnet#high` is not the registered
192
+ // canonical and so passes through: that hole predates #175 (the same
193
+ // `?? parsed.model` produced `"sonnet"` for it on `dev` too) and is not this
194
+ // regression.
195
+ //
196
+ // WHY `modelFamily` KEEPS ITS `?? parsed.model` FALLBACK and is deliberately
197
+ // NOT guarded here — stated so the next reader does not "complete" the fix:
198
+ // (1) it never reaches a provider — the wire identity is `modelSnapshot`, read
199
+ // by `transport-registry.ts` for OpenCode's `modelID`, by
200
+ // `spawnModelForClaudeCli` for `--model`, and by pricing admission in
201
+ // `production-runtime.ts`; (2) `"sonnet"` is a truthful FAMILY label, not a
202
+ // fabricated version, so unlike the snapshot it asserts nothing false; and
203
+ // (3) this guard already refuses the whole route in the only case where an
204
+ // alias-derived family could reach a consumer that does not resolve aliases
205
+ // with no snapshot. Guarding it too would force operators to supply both fields
206
+ // and buy no safety.
207
+ function routeModelSnapshot(
208
+ mapping: RouteMapping,
209
+ parsed: ParsedLogicalIdentity,
210
+ reverseAlias: ModelAlias | undefined,
211
+ gateway: ModelGateway,
212
+ mappingLabel: string,
213
+ ): string {
214
+ if (mapping.modelSnapshot !== undefined) {
215
+ return mapping.modelSnapshot;
216
+ }
217
+ // The one combination whose consumer resolves the bare word itself, so the
218
+ // alias IS the honest snapshot: the Claude CLI, reached directly.
219
+ const consumerResolvesAlias =
220
+ mapping.backend === "claude-code" && gateway === "direct";
221
+ if (reverseAlias !== undefined && !consumerResolvesAlias) {
222
+ // `UnmappedRouteError` and not a new class: a mapping was found, but it
223
+ // leaves the alias unmapped to any provider model id, which is what this
224
+ // error already names. Nothing in src/ catches these classes, so the
225
+ // choice is about meaning, and a fifth class would have no consumer.
226
+ throw new UnmappedRouteError(
227
+ redactDiagnostic(
228
+ `Model alias "${reverseAlias}" is routed to backend "${mapping.backend}" over the "${gateway}" gateway by the ${mappingLabel}, which supplies no "modelSnapshot". Only the Claude CLI reached over the "direct" gateway resolves a bare alias; every other gateway forwards the model identity verbatim to an endpoint that never registered Crysk's aliases, so this route has no provider model id to send. Add an explicit "modelSnapshot" naming the provider's model id to that ${mappingLabel}, or set its "gateway" to "direct" if the Claude CLI really is resolving this alias.`,
229
+ ),
230
+ );
231
+ }
232
+ return parsed.model;
233
+ }
234
+
235
+ export function resolveModelRoute(
236
+ logicalInput: string,
237
+ config?: RoutingConfig,
238
+ ): ResolvedModelRoute {
239
+ const parsed = parseLogicalIdentity(logicalInput);
240
+ const reverseAlias = reverseAliasForCanonical(parsed.canonical);
241
+
242
+ if (config !== undefined) {
243
+ if (config.disabled === true) {
244
+ throw new UnauthorizedRouteError(
245
+ redactDiagnostic(
246
+ `Spend is disabled for model route "${parsed.canonical}"`,
247
+ ),
248
+ );
249
+ }
250
+
251
+ if (config.mappings !== undefined) {
252
+ if (Array.isArray(config.mappings)) {
253
+ const matches = config.mappings.filter((entry) => {
254
+ if (!entry || typeof entry !== "object") return false;
255
+ if (entry.logical === parsed.canonical) return true;
256
+ if (entry.logical === parsed.raw) return true;
257
+ if (parsed.alias && entry.logical === parsed.alias) return true;
258
+ if (reverseAlias && entry.logical === reverseAlias) return true;
259
+ return false;
260
+ });
261
+
262
+ if (matches.length > 1) {
263
+ throw new AmbiguousMappingError(
264
+ redactDiagnostic(
265
+ `Ambiguous model routing: found ${matches.length} duplicate mappings for "${parsed.canonical}"`,
266
+ ),
267
+ );
268
+ }
269
+
270
+ if (matches.length === 1) {
271
+ const m = matches[0];
272
+ if (m.disabled === true || m.allowSpend === false) {
273
+ throw new UnauthorizedRouteError(
274
+ redactDiagnostic(
275
+ `Spend is disabled for model route "${parsed.canonical}"`,
276
+ ),
277
+ );
278
+ }
279
+ // One `?? "configured"` per branch, shared by the route field and the
280
+ // guard, so the value the guard judges is the value the route claims.
281
+ const gateway = m.gateway ?? "configured";
282
+ return {
283
+ backend: m.backend,
284
+ provider: m.provider,
285
+ gateway,
286
+ modelFamily: m.modelFamily ?? parsed.model,
287
+ modelSnapshot: routeModelSnapshot(
288
+ m,
289
+ parsed,
290
+ reverseAlias,
291
+ gateway,
292
+ "routing mapping",
293
+ ),
294
+ ...(m.modelVariant !== undefined || parsed.variant !== undefined
295
+ ? { modelVariant: m.modelVariant ?? parsed.variant }
296
+ : {}),
297
+ };
298
+ }
299
+ } else if (
300
+ typeof config.mappings === "object" &&
301
+ config.mappings !== null
302
+ ) {
303
+ const record = config.mappings as Record<string, RouteMapping>;
304
+ const candidateKeys = Array.from(
305
+ new Set(
306
+ [parsed.canonical, parsed.alias, reverseAlias, parsed.raw].filter(
307
+ (key): key is string => key !== undefined,
308
+ ),
309
+ ),
310
+ );
311
+ const matchedKeys = candidateKeys.filter((key) => key in record);
312
+
313
+ if (matchedKeys.length > 1) {
314
+ throw new AmbiguousMappingError(
315
+ redactDiagnostic(
316
+ `Ambiguous model routing: found ${matchedKeys.length} duplicate mappings for "${parsed.canonical}" in record mappings`,
317
+ ),
318
+ );
319
+ }
320
+
321
+ const m = matchedKeys.length > 0 ? record[matchedKeys[0]] : undefined;
322
+
323
+ if (m !== undefined) {
324
+ if (m.disabled === true || m.allowSpend === false) {
325
+ throw new UnauthorizedRouteError(
326
+ redactDiagnostic(
327
+ `Spend is disabled for model route "${parsed.canonical}"`,
328
+ ),
329
+ );
330
+ }
331
+ // Same shared `?? "configured"` as the array branch: the guard and
332
+ // the recorded route must never read two different gateways.
333
+ const gateway = m.gateway ?? "configured";
334
+ return {
335
+ backend: m.backend,
336
+ provider: m.provider,
337
+ gateway,
338
+ modelFamily: m.modelFamily ?? parsed.model,
339
+ modelSnapshot: routeModelSnapshot(
340
+ m,
341
+ parsed,
342
+ reverseAlias,
343
+ gateway,
344
+ "routing mapping",
345
+ ),
346
+ ...(m.modelVariant !== undefined || parsed.variant !== undefined
347
+ ? { modelVariant: m.modelVariant ?? parsed.variant }
348
+ : {}),
349
+ };
350
+ }
351
+ }
352
+ }
353
+
354
+ if (config.default !== undefined) {
355
+ const def = config.default;
356
+ if (def.disabled === true || def.allowSpend === false) {
357
+ throw new UnauthorizedRouteError(
358
+ redactDiagnostic("Spend is disabled for default model route"),
359
+ );
360
+ }
361
+ // Third and last copy of the same shared default, for the same reason.
362
+ const gateway = def.gateway ?? "configured";
363
+ return {
364
+ backend: def.backend,
365
+ provider: def.provider,
366
+ gateway,
367
+ modelFamily: def.modelFamily ?? parsed.model,
368
+ modelSnapshot: routeModelSnapshot(
369
+ def,
370
+ parsed,
371
+ reverseAlias,
372
+ gateway,
373
+ "default routing mapping",
374
+ ),
375
+ ...(def.modelVariant !== undefined || parsed.variant !== undefined
376
+ ? { modelVariant: def.modelVariant ?? parsed.variant }
377
+ : {}),
378
+ };
379
+ }
380
+ }
381
+
382
+ if (parsed.alias !== undefined) {
383
+ return {
384
+ backend: "claude-code",
385
+ provider: "anthropic",
386
+ gateway: "direct",
387
+ modelFamily: parsed.model,
388
+ modelSnapshot: parsed.model,
389
+ ...(parsed.variant !== undefined ? { modelVariant: parsed.variant } : {}),
390
+ };
391
+ }
392
+
393
+ throw new UnmappedRouteError(
394
+ redactDiagnostic(
395
+ `No route mapping found for logical model "${parsed.canonical}"`,
396
+ ),
397
+ );
398
+ }
399
+
400
+ export function computeRouteFingerprint(
401
+ canonicalLogical: string,
402
+ route: ResolvedModelRoute,
403
+ ): string {
404
+ const payload = JSON.stringify({
405
+ logical: canonicalLogical,
406
+ backend: route.backend,
407
+ provider: route.provider,
408
+ gateway: route.gateway ?? "",
409
+ modelFamily: route.modelFamily,
410
+ modelSnapshot: route.modelSnapshot,
411
+ modelVariant: route.modelVariant ?? "",
412
+ });
413
+ return createHash("sha256").update(payload).digest("hex");
414
+ }
415
+
416
+ function deepFreeze<T>(obj: T): T {
417
+ if (obj === null || typeof obj !== "object") {
418
+ return obj;
419
+ }
420
+ Object.freeze(obj);
421
+ for (const key of Object.keys(obj)) {
422
+ const val = (obj as Record<string, unknown>)[key];
423
+ if (val !== null && typeof val === "object" && !Object.isFrozen(val)) {
424
+ deepFreeze(val);
425
+ }
426
+ }
427
+ return obj;
428
+ }
429
+
430
+ export function freezeRoutePlan(plan: ResolvedRoutePlan): ResolvedRoutePlan {
431
+ return deepFreeze(plan);
432
+ }
433
+
434
+ export function resolveLogicalModel(
435
+ cliModel?: string,
436
+ specModel?: string,
437
+ frontmatterModel?: string,
438
+ stepName?: string,
439
+ ): string {
440
+ const model = cliModel ?? specModel ?? frontmatterModel;
441
+ if (!model || (typeof model === "string" && model.trim().length === 0)) {
442
+ throw new ModelRoutingError(
443
+ `agent ${stepName ?? "step"} has no model and no override given`,
444
+ );
445
+ }
446
+ return model.trim();
447
+ }
448
+
449
+ export interface ResolveStepRouteInput {
450
+ readonly stepKey: string;
451
+ readonly role: string;
452
+ readonly cliModel?: string;
453
+ readonly specModel?: string;
454
+ readonly frontmatterModel?: string;
455
+ readonly routingConfig?: RoutingConfig;
456
+ }
457
+
458
+ export function resolveStepRoute(
459
+ input: ResolveStepRouteInput,
460
+ ): ResolvedStepRoute {
461
+ const logical = resolveLogicalModel(
462
+ input.cliModel,
463
+ input.specModel,
464
+ input.frontmatterModel,
465
+ input.stepKey,
466
+ );
467
+ const parsed = parseLogicalIdentity(logical);
468
+ const route = resolveModelRoute(logical, input.routingConfig);
469
+ const routeFingerprint = computeRouteFingerprint(parsed.canonical, route);
470
+ return {
471
+ stepKey: input.stepKey,
472
+ role: input.role,
473
+ logicalIdentity: parsed.canonical,
474
+ route,
475
+ routeFingerprint,
476
+ };
477
+ }
478
+
479
+ export function createResolvedRoutePlan(
480
+ steps: readonly ResolvedStepRoute[],
481
+ ): ResolvedRoutePlan {
482
+ const sortedFingerprints = steps
483
+ .map((s) => `${s.stepKey}:${s.routeFingerprint}`)
484
+ .sort()
485
+ .join(";");
486
+ const planFingerprint = createHash("sha256")
487
+ .update(sortedFingerprints)
488
+ .digest("hex");
489
+ const plan: ResolvedRoutePlan = {
490
+ steps,
491
+ routeFingerprint: planFingerprint,
492
+ };
493
+ return freezeRoutePlan(plan);
494
+ }
495
+
496
+ export function agentStepKey(agent: { key: string; role: string }): string {
497
+ if (agent.role === "hunter") return `hunter-${agent.key}`;
498
+ if (agent.role === "refuter") {
499
+ return agent.key === "refuter" ? "refuter" : agent.key;
500
+ }
501
+ return agent.key;
502
+ }
503
+
504
+ export interface BuildRoutePlanInput {
505
+ readonly agents: readonly { key: string; role: string; model?: string }[];
506
+ readonly cliModel?: string;
507
+ readonly routingConfig?: RoutingConfig;
508
+ readonly frontmatterModel?: (agentKey: string) => string | undefined;
509
+ readonly summarizer?: { model?: string; frontmatterModel?: string };
510
+ readonly scout?: {
511
+ model?: string;
512
+ frontmatterModel?: string;
513
+ defaultModel?: string;
514
+ };
515
+ readonly consolidate?: {
516
+ model?: string;
517
+ frontmatterModel?: string;
518
+ defaultModel?: string;
519
+ };
520
+ }
521
+
522
+ export function buildResolvedRoutePlan(
523
+ input: BuildRoutePlanInput,
524
+ ): ResolvedRoutePlan {
525
+ const stepRoutes: ResolvedStepRoute[] = [];
526
+ for (const agent of input.agents) {
527
+ stepRoutes.push(
528
+ resolveStepRoute({
529
+ stepKey: agentStepKey(agent),
530
+ role: agent.role,
531
+ cliModel: input.cliModel,
532
+ specModel: agent.model,
533
+ frontmatterModel: input.frontmatterModel?.(agent.key),
534
+ routingConfig: input.routingConfig,
535
+ }),
536
+ );
537
+ }
538
+ if (input.summarizer) {
539
+ stepRoutes.push(
540
+ resolveStepRoute({
541
+ stepKey: "summarizer",
542
+ role: "summarizer",
543
+ cliModel: input.cliModel,
544
+ specModel: input.summarizer.model,
545
+ frontmatterModel: input.summarizer.frontmatterModel,
546
+ routingConfig: input.routingConfig,
547
+ }),
548
+ );
549
+ }
550
+ if (input.scout) {
551
+ stepRoutes.push(
552
+ resolveStepRoute({
553
+ stepKey: "scout",
554
+ role: "scout",
555
+ cliModel: input.scout.model ?? input.cliModel,
556
+ frontmatterModel:
557
+ input.scout.frontmatterModel ?? input.scout.defaultModel,
558
+ routingConfig: input.routingConfig,
559
+ }),
560
+ );
561
+ }
562
+ if (input.consolidate) {
563
+ stepRoutes.push(
564
+ resolveStepRoute({
565
+ stepKey: "consolidate",
566
+ role: "other",
567
+ cliModel: input.consolidate.model ?? input.cliModel,
568
+ frontmatterModel:
569
+ input.consolidate.frontmatterModel ?? input.consolidate.defaultModel,
570
+ routingConfig: input.routingConfig,
571
+ }),
572
+ );
573
+ }
574
+ return createResolvedRoutePlan(stepRoutes);
575
+ }
576
+
577
+ export function spawnModelForClaudeCli(
578
+ route: ResolvedModelRoute,
579
+ executionModel: string,
580
+ ): string {
581
+ const gateway = route.gateway ?? "direct";
582
+ if (gateway !== "direct") {
583
+ return route.modelSnapshot;
584
+ }
585
+ if (isModelAlias(executionModel)) {
586
+ return executionModel;
587
+ }
588
+ try {
589
+ const parsed = parseLogicalIdentity(executionModel);
590
+ const alias = reverseAliasForCanonical(
591
+ `${parsed.provider}/${parsed.model}`,
592
+ );
593
+ if (alias !== undefined) {
594
+ return alias;
595
+ }
596
+ } catch {
597
+ // executionModel is not a catalog alias or slash-grammar identity.
598
+ }
599
+ return route.modelSnapshot;
600
+ }