crysk 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +26 -17
  2. package/config/models/anthropic.json +1 -1
  3. package/dist/SKILL-k4k0zn1w.md +143 -0
  4. package/dist/SKILL-vhb4c3vv.md +553 -0
  5. package/dist/SKILL-xpf6kmdw.md +74 -0
  6. package/dist/ci-admission-0ken6ehx.md +128 -0
  7. package/dist/cli.js +3056 -1623
  8. package/dist/index.js +1744 -938
  9. package/dist/opencode-ci-ac5zksdn.md +106 -0
  10. package/dist/workflow-4pkyck01.yml +160 -0
  11. package/package.json +1 -1
  12. package/prompts/default/PROVENANCE.md +1 -0
  13. package/skills/crysk/SKILL.md +16 -16
  14. package/skills/crysk-ci-setup/SKILL.md +41 -38
  15. package/skills/crysk-ci-setup/assets/workflow.yml +31 -22
  16. package/skills/crysk-ci-setup/references/ci-admission.md +1 -1
  17. package/skills/crysk-ci-setup/references/opencode-ci.md +53 -88
  18. package/skills/crysk-loop/SKILL.md +1 -1
  19. package/src/asset-manifest.ts +0 -4
  20. package/src/assets.ts +1 -1
  21. package/src/ci/admission-ledger.ts +4 -0
  22. package/src/ci/classify-error.ts +21 -24
  23. package/src/ci/cli-record.ts +53 -1
  24. package/src/ci/crysk-secrets.ts +409 -0
  25. package/src/ci/gates.ts +22 -36
  26. package/src/ci/outcome.ts +421 -330
  27. package/src/ci/platform-config.ts +2 -2
  28. package/src/ci/platform-report.ts +274 -41
  29. package/src/ci/platform-trace.ts +551 -0
  30. package/src/ci/platform.ts +28 -12
  31. package/src/ci/publish.ts +19 -6
  32. package/src/ci/review-levels.ts +8 -7
  33. package/src/ci/run.ts +88 -0
  34. package/src/ci/setup.ts +453 -118
  35. package/src/ci/trace-bundle.ts +1282 -0
  36. package/src/ci/trace-transcripts.ts +415 -0
  37. package/src/ci/trigger.ts +176 -33
  38. package/src/cli.ts +11 -3
  39. package/src/commands/ci-setup-questions.ts +3 -3
  40. package/src/commands/ci-setup.ts +152 -6
  41. package/src/commands/config.ts +3 -0
  42. package/src/commands/doctor.ts +15 -6
  43. package/src/config/config.ts +16 -3
  44. package/src/diversity/clustering.ts +0 -1
  45. package/src/diversity/identity.ts +4 -5
  46. package/src/diversity/pipeline-integration.ts +1 -9
  47. package/src/doctor.ts +3 -3
  48. package/src/execution/attempt-evidence.ts +10 -5
  49. package/src/execution/claude-session-trace.ts +480 -0
  50. package/src/execution/contracts.ts +21 -4
  51. package/src/execution/harness.ts +105 -8
  52. package/src/execution/model-fallback.ts +239 -0
  53. package/src/execution/usage-normalized.ts +6 -4
  54. package/src/home-preflight.ts +1 -1
  55. package/src/index.ts +1 -1
  56. package/src/model/catalog.ts +13 -37
  57. package/src/model/free-discovery.ts +117 -8
  58. package/src/model/model-name.ts +404 -0
  59. package/src/model/provider-capabilities.ts +22 -7
  60. package/src/model/routing.ts +346 -467
  61. package/src/pr/admission.ts +18 -0
  62. package/src/pr/plan.ts +20 -4
  63. package/src/pr/preflight.ts +1 -1
  64. package/src/pr/publish-outcome.ts +1 -1
  65. package/src/pr/review-pr.ts +15 -1
  66. package/src/pr/target.ts +12 -3
  67. package/src/production-runtime.ts +760 -331
  68. package/src/review/pipeline.ts +277 -101
  69. package/src/review/preflight.ts +201 -294
  70. package/src/review/report.ts +26 -26
  71. package/src/review/review.ts +20 -3
  72. package/src/review/route-preflight.ts +79 -11
  73. package/src/review/run.ts +28 -6
  74. package/src/review/scout.ts +1 -1
  75. package/src/review/spec.ts +3 -3
  76. package/src/review/step-runner.ts +70 -1
  77. package/src/runner-authority.ts +127 -9
  78. package/src/security/binding-policy.ts +1 -2
  79. package/src/security/claude-credential.ts +355 -0
  80. package/src/security/credential-broker.ts +56 -40
  81. package/src/security/evidence-redaction.ts +179 -4
  82. package/src/security/opencode-secret-manifest.ts +114 -0
  83. package/src/security/redact.ts +45 -0
  84. package/src/system-tools.ts +48 -21
  85. package/src/transport-registry.ts +12 -2
  86. package/src/transports/claude-code-cli.ts +21 -2
  87. package/src/transports/opencode-sdk.ts +11 -9
  88. package/src/transports/opencode-server.ts +7 -10
  89. package/src/ui/config-edit.ts +9 -20
  90. package/src/ui/config.ts +32 -27
  91. package/src/ui/plan.ts +76 -47
  92. package/src/updater.ts +10 -7
  93. package/prompts/default/deep-review-lifecycle.md +0 -362
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ var __esm = (fn, res, err) => () => {
10
10
  throw err[0];
11
11
  return res;
12
12
  };
13
+ var __promiseAll = (args) => Promise.all(args);
13
14
 
14
15
  // src/errors.ts
15
16
  function withRecordClass(error, cls) {
@@ -117,12 +118,26 @@ function redactDiagnostic(text) {
117
118
  }
118
119
  return redacted.replace(KEYWORD_VALUE, (match, _keyword, separator, word) => /^\s+$/.test(separator) && PROSE_AFTER_KEYWORD.has(word.toLowerCase().replace(/[.,;:!?)\]"']+$/, "")) ? match : REDACTED);
119
120
  }
120
- var REDACTED = "[REDACTED]", REDACTION_PATTERNS, KEYWORD_VALUE, PROSE_AFTER_KEYWORD;
121
+ function isLongBase64(value) {
122
+ return WHOLE_BASE64.test(value) && /[A-Z]/.test(value) && /[a-z]/.test(value) && /[0-9]/.test(value);
123
+ }
124
+ function looksLikeCredential(value) {
125
+ return redactDiagnostic(value) !== value || WHOLE_HEX.test(value) || isLongBase64(value);
126
+ }
127
+ function redactConfigValue(value) {
128
+ if (WHOLE_HEX.test(value) || isLongBase64(value))
129
+ return REDACTED;
130
+ return redactDiagnostic(value);
131
+ }
132
+ var REDACTED = "[REDACTED]", REDACTION_PATTERNS, KEYWORD_VALUE, PROSE_AFTER_KEYWORD, WHOLE_HEX, WHOLE_BASE64;
121
133
  var init_redact = __esm(() => {
122
134
  REDACTION_PATTERNS = [
123
135
  /sk-[A-Za-z0-9_-]{8,}/g,
124
136
  /gh[pousr]_[A-Za-z0-9_]{20,}/g,
125
- /Bearer\s+\S+/gi
137
+ /Bearer\s+\S+/gi,
138
+ /AIza[0-9A-Za-z_-]{35}/g,
139
+ /gsk_[A-Za-z0-9]{20,}/g,
140
+ /xai-[A-Za-z0-9]{20,}/g
126
141
  ];
127
142
  KEYWORD_VALUE = /(api[_-]?key|token|password)((?:["':=]|\s)+)(\S+)/gi;
128
143
  PROSE_AFTER_KEYWORD = new Set([
@@ -162,6 +177,8 @@ var init_redact = __esm(() => {
162
177
  "refused",
163
178
  "denied"
164
179
  ]);
180
+ WHOLE_HEX = /^[0-9a-fA-F]{32,}$/;
181
+ WHOLE_BASE64 = /^[A-Za-z0-9+/_]{40,}={0,2}$/;
165
182
  });
166
183
 
167
184
  // config/models/anthropic.json
@@ -170,7 +187,7 @@ var init_anthropic = __esm(() => {
170
187
  anthropic_default = {
171
188
  provider: "anthropic",
172
189
  defaultBackend: "claude-code",
173
- aliases: ["sonnet", "opus", "haiku"]
190
+ aliases: ["sonnet", "opus", "haiku", "fable"]
174
191
  };
175
192
  });
176
193
 
@@ -212,27 +229,13 @@ function canonicalIdentity(provider, alias) {
212
229
  function isModelAlias(value) {
213
230
  return aliasIndex.has(value);
214
231
  }
215
- function lookupAlias(alias) {
216
- const entry = aliasIndex.get(alias);
217
- if (entry === undefined) {
218
- throw new Error(`model catalog: unknown alias "${alias}"`);
219
- }
220
- return entry;
221
- }
222
- function aliasCanonical(alias) {
223
- return lookupAlias(alias).canonical;
224
- }
225
- function reverseAliasForCanonical(canonical) {
226
- const alias = canonicalToAlias.get(canonical);
227
- return alias === undefined ? undefined : alias;
228
- }
229
232
  function isEffort(value) {
230
233
  return EFFORT_LEVELS.includes(value);
231
234
  }
232
235
  function defaultEffortForRole(role) {
233
236
  return ROLE_EFFORT[role];
234
237
  }
235
- var PROVIDER_CATALOGS, MODEL_CATALOG, aliasIndex, canonicalToAlias, REQUIRED_ALIASES, EFFORT_LEVELS, ROLE_EFFORT;
238
+ var PROVIDER_CATALOGS, MODEL_CATALOG, aliasIndex, REQUIRED_ALIASES, EFFORT_LEVELS, ROLE_EFFORT;
236
239
  var init_catalog = __esm(() => {
237
240
  init_anthropic();
238
241
  PROVIDER_CATALOGS = {
@@ -242,26 +245,26 @@ var init_catalog = __esm(() => {
242
245
  providers: PROVIDER_CATALOGS
243
246
  });
244
247
  aliasIndex = new Map;
245
- canonicalToAlias = new Map;
246
248
  for (const catalog of Object.values(PROVIDER_CATALOGS)) {
247
249
  for (const alias of catalog.aliases) {
248
250
  if (aliasIndex.has(alias)) {
249
251
  throw new Error(`model catalog: duplicate alias "${alias}"`);
250
252
  }
251
253
  const canonical = canonicalIdentity(catalog.provider, alias);
252
- if (canonicalToAlias.has(canonical)) {
253
- throw new Error(`model catalog: duplicate canonical "${canonical}"`);
254
- }
255
254
  aliasIndex.set(alias, {
256
255
  provider: catalog.provider,
257
256
  alias,
258
257
  canonical,
259
258
  ...catalog.defaultBackend === undefined ? {} : { defaultBackend: catalog.defaultBackend }
260
259
  });
261
- canonicalToAlias.set(canonical, alias);
262
260
  }
263
261
  }
264
- REQUIRED_ALIASES = ["sonnet", "opus", "haiku"];
262
+ REQUIRED_ALIASES = [
263
+ "sonnet",
264
+ "opus",
265
+ "haiku",
266
+ "fable"
267
+ ];
265
268
  for (const alias of REQUIRED_ALIASES) {
266
269
  if (!aliasIndex.has(alias)) {
267
270
  throw new Error(`model catalog: missing required alias "${alias}"`);
@@ -278,165 +281,257 @@ var init_catalog = __esm(() => {
278
281
  });
279
282
  });
280
283
 
281
- // src/model/routing.ts
282
- import { createHash } from "crypto";
283
- function mappingNeedsOpenCodeSdk(mapping) {
284
- if (mapping === undefined)
285
- return false;
286
- return mapping.backend === "opencode" && mapping.disabled !== true && mapping.allowSpend !== false;
284
+ // src/model/model-name.ts
285
+ function quoted(raw) {
286
+ return `"${redactConfigValue(raw)}"`;
287
+ }
288
+ function nameLooksLikeCredential(raw) {
289
+ const parts = raw.split(/[:/]/);
290
+ for (const [i, ch] of [...raw].entries()) {
291
+ if (ch === ":" || ch === "/")
292
+ parts.push(raw.slice(i + 1));
293
+ }
294
+ return looksLikeCredential(raw) || parts.some(looksLikeCredential);
295
+ }
296
+ function parseClaudeName(raw, name) {
297
+ if (name.endsWith(LATEST_SUFFIX)) {
298
+ const alias = name.slice(0, -LATEST_SUFFIX.length);
299
+ if (isModelAlias(alias)) {
300
+ return {
301
+ raw,
302
+ backend: "claude-code",
303
+ provider: "anthropic",
304
+ model: alias,
305
+ alias
306
+ };
307
+ }
308
+ }
309
+ if (isModelAlias(name)) {
310
+ throw new ModelNameError(`${quoted(raw)} is not a model name: write "claude:${name}-latest" for the newest ${name}, or a full name such as "claude-${name}-5-5" to pin a version`);
311
+ }
312
+ if (CLAUDE_ID_RE.test(name) && !name.endsWith("-")) {
313
+ return { raw, backend: "claude-code", provider: "anthropic", model: name };
314
+ }
315
+ throw new ModelNameError(`${quoted(raw)} is not a Claude model name: use ${CLAUDE_FORMS}`);
287
316
  }
288
- function routingNeedsOpenCodeSdk(routing) {
289
- if (routing === undefined || routing.disabled === true)
290
- return false;
291
- if (mappingNeedsOpenCodeSdk(routing.default))
292
- return true;
293
- const mappings = routing.mappings;
294
- if (mappings === undefined)
295
- return false;
296
- const entries = Array.isArray(mappings) ? mappings : Object.values(mappings);
297
- return entries.some((entry) => mappingNeedsOpenCodeSdk(entry));
317
+ function parseOpenCodeName(raw, name) {
318
+ const match = name.match(OPENCODE_RE);
319
+ if (match === null) {
320
+ throw new ModelNameError(`${quoted(raw)} is not an OpenCode model name: use ${OPENCODE_FORM}`);
321
+ }
322
+ const [, provider, model] = match;
323
+ return { raw, backend: "opencode", provider, model };
298
324
  }
299
- function parseLogicalIdentity(raw) {
325
+ function refuseVariantSuffix(raw) {
326
+ const at = raw.indexOf("#");
327
+ if (at < 0)
328
+ return;
329
+ const base = raw.slice(0, at);
330
+ const effort = raw.slice(at + 1);
331
+ if (!OPENCODE_EFFORT_RE.test(effort))
332
+ return;
333
+ try {
334
+ parseModelName(base);
335
+ } catch {
336
+ return;
337
+ }
338
+ throw new ModelNameError(`${quoted(raw)}: the #variant suffix is gone: write {"model": ${JSON.stringify(base)}, "effort": ${JSON.stringify(effort)}} in models`);
339
+ }
340
+ function parseModelName(raw) {
300
341
  if (typeof raw !== "string") {
301
- throw new ModelRoutingError("Model identity must be a string");
342
+ throw new ModelNameError("a model name must be a string");
302
343
  }
303
- const trimmed = raw.trim();
304
- if (trimmed.length === 0) {
305
- throw new ModelRoutingError("Model identity cannot be empty");
344
+ if (nameLooksLikeCredential(raw)) {
345
+ throw new ModelNameError("a model name looks like a credential, and credentials are not permitted in models");
346
+ }
347
+ refuseVariantSuffix(raw);
348
+ if (raw.startsWith(CLAUDE_PREFIX)) {
349
+ return parseClaudeName(raw, raw.slice(CLAUDE_PREFIX.length));
350
+ }
351
+ if (raw.startsWith(OPENCODE_PREFIX)) {
352
+ return parseOpenCodeName(raw, raw.slice(OPENCODE_PREFIX.length));
353
+ }
354
+ if (isModelAlias(raw)) {
355
+ throw new ModelNameError(`${quoted(raw)} is not a model name: write "claude:${raw}-latest"`);
306
356
  }
357
+ throw new ModelNameError(`${quoted(raw)} is not a model name: a model is "claude:<name>" or "${OPENCODE_FORM}"`);
358
+ }
359
+ function modelNameFromAlias(value) {
360
+ const trimmed = value.trim();
307
361
  if (isModelAlias(trimmed)) {
308
- const aliasInfo = lookupAlias(trimmed);
309
- return {
310
- raw: trimmed,
311
- canonical: aliasInfo.canonical,
312
- provider: aliasInfo.provider,
313
- model: aliasInfo.alias,
314
- alias: trimmed
315
- };
362
+ return parseModelName(`${CLAUDE_PREFIX}${trimmed}${LATEST_SUFFIX}`);
316
363
  }
317
- const match = trimmed.match(SLASH_GRAMMAR_REGEX);
318
- if (match) {
319
- const [, provider, model, variant] = match;
320
- const canonical = `${provider}/${model}${variant ? `#${variant}` : ""}`;
321
- return {
322
- raw: trimmed,
323
- canonical,
324
- provider,
325
- model,
326
- ...variant !== undefined ? { variant } : {}
327
- };
364
+ return parseModelName(trimmed);
365
+ }
366
+ function hunterRole(key) {
367
+ return `${HUNTER_ROLE_PREFIX}${key}`;
368
+ }
369
+ function isModelRole(value) {
370
+ if (FIXED_MODEL_ROLES.includes(value))
371
+ return true;
372
+ if (!value.startsWith(HUNTER_ROLE_PREFIX))
373
+ return false;
374
+ const key = value.slice(HUNTER_ROLE_PREFIX.length);
375
+ return key.length <= 64 && HUNTER_KEY_RE.test(key);
376
+ }
377
+ function modelEntry(entry) {
378
+ if (typeof entry === "string")
379
+ return { name: entry };
380
+ return entry.effort === undefined ? { name: entry.model } : { name: entry.model, effort: entry.effort };
381
+ }
382
+ function levelList() {
383
+ return `${EFFORT_LEVELS.slice(0, -1).join(", ")} or ${EFFORT_LEVELS.at(-1)}`;
384
+ }
385
+ function checkEffort(effort, name, at) {
386
+ if (typeof effort !== "string") {
387
+ throw new ModelNameError(`${at}: effort must be a string`);
328
388
  }
329
- const safeRaw = redactDiagnostic(raw);
330
- throw new ModelRoutingError(`Unknown model identity "${safeRaw}": bare model names must be an alias (sonnet|opus|haiku) or use slash grammar provider/model(#variant)`);
331
- }
332
- function routeModelSnapshot(mapping, parsed, reverseAlias, gateway, mappingLabel) {
333
- if (mapping.modelSnapshot !== undefined) {
334
- return mapping.modelSnapshot;
335
- }
336
- const consumerResolvesAlias = mapping.backend === "claude-code" && gateway === "direct";
337
- if (reverseAlias !== undefined && !consumerResolvesAlias) {
338
- throw new UnmappedRouteError(redactDiagnostic(`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.`));
339
- }
340
- return parsed.model;
341
- }
342
- function resolveModelRoute(logicalInput, config) {
343
- const parsed = parseLogicalIdentity(logicalInput);
344
- const reverseAlias = reverseAliasForCanonical(parsed.canonical);
345
- if (config !== undefined) {
346
- if (config.disabled === true) {
347
- throw new UnauthorizedRouteError(redactDiagnostic(`Spend is disabled for model route "${parsed.canonical}"`));
348
- }
349
- if (config.mappings !== undefined) {
350
- if (Array.isArray(config.mappings)) {
351
- const matches = config.mappings.filter((entry) => {
352
- if (!entry || typeof entry !== "object")
353
- return false;
354
- if (entry.logical === parsed.canonical)
355
- return true;
356
- if (entry.logical === parsed.raw)
357
- return true;
358
- if (parsed.alias && entry.logical === parsed.alias)
359
- return true;
360
- if (reverseAlias && entry.logical === reverseAlias)
361
- return true;
362
- return false;
363
- });
364
- if (matches.length > 1) {
365
- throw new AmbiguousMappingError(redactDiagnostic(`Ambiguous model routing: found ${matches.length} duplicate mappings for "${parsed.canonical}"`));
366
- }
367
- if (matches.length === 1) {
368
- const m = matches[0];
369
- if (m.disabled === true || m.allowSpend === false) {
370
- throw new UnauthorizedRouteError(redactDiagnostic(`Spend is disabled for model route "${parsed.canonical}"`));
371
- }
372
- const gateway = m.gateway ?? "configured";
373
- return {
374
- backend: m.backend,
375
- provider: m.provider,
376
- gateway,
377
- modelFamily: m.modelFamily ?? parsed.model,
378
- modelSnapshot: routeModelSnapshot(m, parsed, reverseAlias, gateway, "routing mapping"),
379
- ...m.modelVariant !== undefined || parsed.variant !== undefined ? { modelVariant: m.modelVariant ?? parsed.variant } : {}
380
- };
381
- }
382
- } else if (typeof config.mappings === "object" && config.mappings !== null) {
383
- const record = config.mappings;
384
- const candidateKeys = Array.from(new Set([parsed.canonical, parsed.alias, reverseAlias, parsed.raw].filter((key) => key !== undefined)));
385
- const matchedKeys = candidateKeys.filter((key) => (key in record));
386
- if (matchedKeys.length > 1) {
387
- throw new AmbiguousMappingError(redactDiagnostic(`Ambiguous model routing: found ${matchedKeys.length} duplicate mappings for "${parsed.canonical}" in record mappings`));
388
- }
389
- const m = matchedKeys.length > 0 ? record[matchedKeys[0]] : undefined;
390
- if (m !== undefined) {
391
- if (m.disabled === true || m.allowSpend === false) {
392
- throw new UnauthorizedRouteError(redactDiagnostic(`Spend is disabled for model route "${parsed.canonical}"`));
393
- }
394
- const gateway = m.gateway ?? "configured";
395
- return {
396
- backend: m.backend,
397
- provider: m.provider,
398
- gateway,
399
- modelFamily: m.modelFamily ?? parsed.model,
400
- modelSnapshot: routeModelSnapshot(m, parsed, reverseAlias, gateway, "routing mapping"),
401
- ...m.modelVariant !== undefined || parsed.variant !== undefined ? { modelVariant: m.modelVariant ?? parsed.variant } : {}
402
- };
403
- }
404
- }
389
+ if (looksLikeCredential(effort)) {
390
+ throw new ModelNameError(`${at}: the effort looks like a credential, and credentials are not permitted in models`);
391
+ }
392
+ if (name.backend === "claude-code") {
393
+ if (effort === ULTRACODE) {
394
+ throw new ModelNameError(`${at}: effort "${ULTRACODE}" is not an effort level: on the Claude Code CLI it also turns on workflow orchestration. Write "xhigh" for its effort level`);
405
395
  }
406
- if (config.default !== undefined) {
407
- const def = config.default;
408
- if (def.disabled === true || def.allowSpend === false) {
409
- throw new UnauthorizedRouteError(redactDiagnostic("Spend is disabled for default model route"));
410
- }
411
- const gateway = def.gateway ?? "configured";
412
- return {
413
- backend: def.backend,
414
- provider: def.provider,
415
- gateway,
416
- modelFamily: def.modelFamily ?? parsed.model,
417
- modelSnapshot: routeModelSnapshot(def, parsed, reverseAlias, gateway, "default routing mapping"),
418
- ...def.modelVariant !== undefined || parsed.variant !== undefined ? { modelVariant: def.modelVariant ?? parsed.variant } : {}
419
- };
396
+ if (!isEffort(effort)) {
397
+ throw new ModelNameError(`${at}: effort ${quoted(effort)} is not a Claude effort level: use ${levelList()}`);
420
398
  }
399
+ return effort;
421
400
  }
422
- if (parsed.alias !== undefined) {
423
- return {
424
- backend: "claude-code",
425
- provider: "anthropic",
426
- gateway: "direct",
427
- modelFamily: parsed.model,
428
- modelSnapshot: parsed.model,
429
- ...parsed.variant !== undefined ? { modelVariant: parsed.variant } : {}
430
- };
401
+ if (!OPENCODE_EFFORT_RE.test(effort)) {
402
+ throw new ModelNameError(`${at}: effort ${quoted(effort)} is not an OpenCode variant name: use letters, digits, ".", "_" and "-", at most 64 characters`);
403
+ }
404
+ return effort;
405
+ }
406
+ function parseModelEntry(value, at, effortAllowed) {
407
+ if (typeof value === "string") {
408
+ try {
409
+ parseModelName(value);
410
+ } catch (error) {
411
+ throw new ModelNameError(`${at}: ${error.message}`);
412
+ }
413
+ return value;
414
+ }
415
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
416
+ throw new ModelNameError(`${at} must be a model name or ${ENTRY_FORM}`);
417
+ }
418
+ const record = value;
419
+ for (const key of Object.keys(record)) {
420
+ if (!ENTRY_KEYS.includes(key)) {
421
+ throw new ModelNameError(`${at} has an unknown key ${quoted(key)}: an entry takes model and effort`);
422
+ }
423
+ }
424
+ if (record.model === undefined) {
425
+ throw new ModelNameError(`${at} needs a "model"`);
426
+ }
427
+ let name;
428
+ try {
429
+ name = parseModelName(record.model);
430
+ } catch (error) {
431
+ throw new ModelNameError(`${at}: ${error.message}`);
431
432
  }
432
- throw new UnmappedRouteError(redactDiagnostic(`No route mapping found for logical model "${parsed.canonical}"`));
433
+ if (record.effort === undefined)
434
+ return { model: name.raw };
435
+ if (effortAllowed !== undefined) {
436
+ throw new ModelNameError(`${at} sets an effort: ${effortAllowed}`);
437
+ }
438
+ return { model: name.raw, effort: checkEffort(record.effort, name, at) };
439
+ }
440
+ function parseModelList(value, where, noEffortReason) {
441
+ if (!Array.isArray(value)) {
442
+ throw new ModelNameError(`${where} must be a list of models`);
443
+ }
444
+ if (value.length === 0) {
445
+ throw new ModelNameError(`${where} must list at least one model`);
446
+ }
447
+ if (value.length > MAX_MODELS_PER_ROLE) {
448
+ throw new ModelNameError(`${where} lists ${value.length} models: at most ${MAX_MODELS_PER_ROLE} are allowed`);
449
+ }
450
+ const seen = new Set;
451
+ const result = [];
452
+ for (const [i, value_] of value.entries()) {
453
+ const entry = parseModelEntry(value_, `${where}[${i}]`, noEffortReason);
454
+ const { name } = modelEntry(entry);
455
+ if (seen.has(name)) {
456
+ throw new ModelNameError(`${where} lists ${quoted(name)} twice`);
457
+ }
458
+ seen.add(name);
459
+ result.push(entry);
460
+ }
461
+ return result;
462
+ }
463
+ function parseModelsConfig(value) {
464
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
465
+ throw new ModelNameError("models must be an object from role to a list of models");
466
+ }
467
+ const result = {};
468
+ for (const [role, list] of Object.entries(value)) {
469
+ if (!isModelRole(role)) {
470
+ throw new ModelNameError(`models has an unknown role ${quoted(role)}: roles are ${ROLE_LIST}`);
471
+ }
472
+ result[role] = parseModelList(list, `models.${role}`, role === "judge" ? JUDGE_NO_EFFORT : undefined);
473
+ }
474
+ return result;
433
475
  }
434
- function computeRouteFingerprint(canonicalLogical, route) {
476
+ function modelsNeedOpenCode(models) {
477
+ if (models === undefined)
478
+ return false;
479
+ return Object.values(models).some((list) => list.some((entry) => modelEntry(entry).name.startsWith(OPENCODE_PREFIX)));
480
+ }
481
+ var ModelNameError, CLAUDE_PREFIX = "claude:", OPENCODE_PREFIX = "opencode:", LATEST_SUFFIX = "-latest", CLAUDE_ID_RE, OPENCODE_RE, OPENCODE_EFFORT_RE, CLAUDE_FORMS = "claude:sonnet-latest, claude:opus-latest, claude:haiku-latest, claude:fable-latest or a full claude-* model name", OPENCODE_FORM = "opencode:<provider>/<model>", FIXED_MODEL_ROLES, HUNTER_ROLE_PREFIX = "hunter.", HUNTER_KEY_RE, MAX_MODELS_PER_ROLE = 3, ENTRY_KEYS, ENTRY_FORM = '{"model": "<name>", "effort": "<level>"}', ULTRACODE = "ultracode", JUDGE_NO_EFFORT = "the materiality judge runs at the effort it was measured at, so models.judge takes model names only", ROLE_LIST = "default, hunter.<key>, consolidate, scout, judge, refuter, summary";
482
+ var init_model_name = __esm(() => {
483
+ init_redact();
484
+ init_catalog();
485
+ ModelNameError = class ModelNameError extends Error {
486
+ };
487
+ CLAUDE_ID_RE = /^claude-[a-z0-9.-]+$/;
488
+ OPENCODE_RE = /^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9._-]+(?:\/[a-zA-Z0-9._-]+)*)$/;
489
+ OPENCODE_EFFORT_RE = /^[a-zA-Z0-9._-]{1,64}$/;
490
+ FIXED_MODEL_ROLES = [
491
+ "default",
492
+ "consolidate",
493
+ "scout",
494
+ "judge",
495
+ "refuter",
496
+ "summary"
497
+ ];
498
+ HUNTER_KEY_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
499
+ ENTRY_KEYS = ["model", "effort"];
500
+ });
501
+
502
+ // src/model/routing.ts
503
+ import { createHash } from "crypto";
504
+ function toModelName(value, source, stepKey) {
505
+ try {
506
+ return source === "models" ? parseModelName(value) : modelNameFromAlias(value);
507
+ } catch (error) {
508
+ if (!(error instanceof ModelNameError))
509
+ throw error;
510
+ const where = source === "--model" ? "--model" : source === "models" ? `models for ${stepKey}` : `the ${source} model of ${stepKey}`;
511
+ const message = `${where}: ${error.message}`;
512
+ if (source === "models" || NEW_FORM_PREFIXES.some((prefix) => value.trim().startsWith(prefix))) {
513
+ throw new InvalidModelError(message);
514
+ }
515
+ throw new ModelRoutingError(message);
516
+ }
517
+ }
518
+ function routeForModel(name, effort) {
519
+ return {
520
+ backend: name.backend,
521
+ provider: name.provider,
522
+ modelFamily: name.alias ?? name.model,
523
+ modelSnapshot: name.model,
524
+ ...effort !== undefined && name.backend === "opencode" ? { modelVariant: effort } : {}
525
+ };
526
+ }
527
+ function claudeCliModel(route) {
528
+ return route.modelSnapshot;
529
+ }
530
+ function computeRouteFingerprint(logicalIdentity, route) {
435
531
  const payload = JSON.stringify({
436
- logical: canonicalLogical,
532
+ logical: logicalIdentity,
437
533
  backend: route.backend,
438
534
  provider: route.provider,
439
- gateway: route.gateway ?? "",
440
535
  modelFamily: route.modelFamily,
441
536
  modelSnapshot: route.modelSnapshot,
442
537
  modelVariant: route.modelVariant ?? ""
@@ -459,28 +554,74 @@ function deepFreeze(obj) {
459
554
  function freezeRoutePlan(plan) {
460
555
  return deepFreeze(plan);
461
556
  }
462
- function resolveLogicalModel(cliModel, specModel, frontmatterModel, stepName) {
463
- const model = cliModel ?? specModel ?? frontmatterModel;
464
- if (!model || typeof model === "string" && model.trim().length === 0) {
465
- throw new ModelRoutingError(`agent ${stepName ?? "step"} has no model and no override given`);
557
+ function stepModelOf(entry, stepKey) {
558
+ const { name, effort } = modelEntry(entry);
559
+ const parsed = toModelName(name, "models", stepKey);
560
+ return effort === undefined ? { name: parsed } : { name: parsed, effort };
561
+ }
562
+ function resolveStepChoices(input) {
563
+ if (input.cliModel !== undefined) {
564
+ return [{ name: toModelName(input.cliModel, "--model", input.stepKey) }];
565
+ }
566
+ if (input.specModel !== undefined) {
567
+ return [{ name: toModelName(input.specModel, "spec", input.stepKey) }];
568
+ }
569
+ const configured = (input.modelRole === undefined ? undefined : input.models?.[input.modelRole]) ?? input.models?.default;
570
+ if (configured !== undefined && configured.length > 0) {
571
+ const [first, ...rest] = configured;
572
+ return [
573
+ stepModelOf(first, input.stepKey),
574
+ ...rest.map((entry) => stepModelOf(entry, input.stepKey))
575
+ ];
466
576
  }
467
- return model.trim();
577
+ if (input.frontmatterModel !== undefined && input.frontmatterModel.trim().length > 0) {
578
+ return [
579
+ { name: toModelName(input.frontmatterModel, "prompt", input.stepKey) }
580
+ ];
581
+ }
582
+ throw new ModelRoutingError(`agent ${input.stepKey} has no model and no override given`);
583
+ }
584
+ function resolveStepModels(input) {
585
+ const [first, ...rest] = resolveStepChoices(input);
586
+ return [first.name, ...rest.map((choice) => choice.name)];
587
+ }
588
+ function resolveStepModel(input) {
589
+ return resolveStepModels(input)[0];
468
590
  }
469
591
  function resolveStepRoute(input) {
470
- const logical = resolveLogicalModel(input.cliModel, input.specModel, input.frontmatterModel, input.stepKey);
471
- const parsed = parseLogicalIdentity(logical);
472
- const route = resolveModelRoute(logical, input.routingConfig);
473
- const routeFingerprint = computeRouteFingerprint(parsed.canonical, route);
592
+ const [first, ...rest] = resolveStepChoices(input);
593
+ const route = stepRouteFor(input.stepKey, input.role, first);
594
+ if (rest.length === 0)
595
+ return route;
474
596
  return {
475
- stepKey: input.stepKey,
476
- role: input.role,
477
- logicalIdentity: parsed.canonical,
597
+ ...route,
598
+ fallbacks: rest.map((choice) => stepRouteFor(input.stepKey, input.role, choice))
599
+ };
600
+ }
601
+ function resolveModelEntryRoute(stepKey, role, entry) {
602
+ return stepRouteFor(stepKey, role, stepModelOf(entry, stepKey));
603
+ }
604
+ function planRoutes(plan) {
605
+ const fallbacks = plan.steps.flatMap((step) => step.fallbacks ?? []);
606
+ return fallbacks.length === 0 ? plan.steps : [...plan.steps, ...fallbacks];
607
+ }
608
+ function stepRouteFor(stepKey, role, { name, effort }) {
609
+ const route = routeForModel(name, effort);
610
+ return {
611
+ stepKey,
612
+ role,
613
+ logicalIdentity: name.raw,
478
614
  route,
479
- routeFingerprint
615
+ routeFingerprint: computeRouteFingerprint(name.raw, route),
616
+ ...effort === undefined ? {} : { effort }
480
617
  };
481
618
  }
619
+ function resolveModelRoute(model) {
620
+ return routeForModel(toModelName(model, "spec", "route"));
621
+ }
482
622
  function createResolvedRoutePlan(steps) {
483
- const sortedFingerprints = steps.map((s) => `${s.stepKey}:${s.routeFingerprint}`).sort().join(";");
623
+ const withEffort = (s) => `${s.routeFingerprint}${s.effort === undefined ? "" : `@${s.effort}`}`;
624
+ const sortedFingerprints = steps.map((s) => `${s.stepKey}:${withEffort(s)}${(s.fallbacks ?? []).map((f) => `>${withEffort(f)}`).join("")}`).sort().join(";");
484
625
  const planFingerprint = createHash("sha256").update(sortedFingerprints).digest("hex");
485
626
  const plan = {
486
627
  steps,
@@ -496,101 +637,113 @@ function agentStepKey(agent) {
496
637
  }
497
638
  return agent.key;
498
639
  }
499
- function resolveMaterialityJudgeRoute(routingConfig) {
500
- let step;
501
- try {
502
- step = resolveStepRoute({
503
- stepKey: MATERIALITY_STEP_KEY,
504
- role: "other",
505
- specModel: MATERIALITY_JUDGE_MODEL,
506
- routingConfig
507
- });
508
- } catch {
640
+ function agentModelRole(agent) {
641
+ if (agent.role === "hunter")
642
+ return hunterRole(agent.specialty ?? agent.key);
643
+ if (agent.role === "refuter")
644
+ return "refuter";
645
+ return;
646
+ }
647
+ function assertHunterRolesExist(models, agents) {
648
+ if (models === undefined)
509
649
  return;
650
+ const hunters = [
651
+ ...new Set(agents.filter((agent) => agent.role === "hunter").map((agent) => agent.specialty ?? agent.key))
652
+ ];
653
+ for (const role of Object.keys(models)) {
654
+ if (!role.startsWith("hunter.") || !isModelRole(role))
655
+ continue;
656
+ if (hunters.includes(role.slice("hunter.".length)))
657
+ continue;
658
+ throw new InvalidModelError(`models.${role} names no hunter in this review: its hunters are ${hunters.join(", ")}`);
510
659
  }
511
- return isMeasuredJudgeRoute(step.route) ? step : undefined;
660
+ }
661
+ function judgeModelChoice(models) {
662
+ const listed = (models?.judge ?? [`claude:${MATERIALITY_JUDGE_MODEL}-latest`]).map((entry) => modelEntry(entry).name);
663
+ const usable = listed.filter((name) => MEASURED_JUDGE_MODELS.includes(name));
664
+ return {
665
+ ...usable.length === 0 ? {} : { model: usable[0] },
666
+ dropped: listed.filter((name) => !MEASURED_JUDGE_MODELS.includes(name))
667
+ };
668
+ }
669
+ function resolveMaterialityJudgeRoute(models) {
670
+ const { model } = judgeModelChoice(models);
671
+ if (model === undefined)
672
+ return;
673
+ return stepRouteFor(MATERIALITY_STEP_KEY, "other", {
674
+ name: parseModelName(model)
675
+ });
512
676
  }
513
677
  function isMeasuredJudgeRoute(route) {
514
- return route.backend === "claude-code" && route.provider === "anthropic" && (route.gateway === undefined || route.gateway === "direct");
678
+ return route.backend === "claude-code" && route.provider === "anthropic" && (route.modelSnapshot === "sonnet" || route.modelSnapshot === "opus");
515
679
  }
516
680
  function buildResolvedRoutePlan(input) {
681
+ assertHunterRolesExist(input.models, input.agents);
517
682
  const stepRoutes = [];
518
683
  for (const agent of input.agents) {
684
+ const modelRole = agentModelRole(agent);
519
685
  stepRoutes.push(resolveStepRoute({
520
686
  stepKey: agentStepKey(agent),
521
687
  role: agent.role,
688
+ ...modelRole === undefined ? {} : { modelRole },
522
689
  cliModel: input.cliModel,
523
690
  specModel: agent.model,
524
691
  frontmatterModel: input.frontmatterModel?.(agent.key),
525
- routingConfig: input.routingConfig
692
+ models: input.models
526
693
  }));
527
694
  }
528
695
  if (input.summarizer) {
529
696
  stepRoutes.push(resolveStepRoute({
530
697
  stepKey: "summarizer",
531
698
  role: "summarizer",
699
+ modelRole: "summary",
532
700
  cliModel: input.cliModel,
533
701
  specModel: input.summarizer.model,
534
702
  frontmatterModel: input.summarizer.frontmatterModel,
535
- routingConfig: input.routingConfig
703
+ models: input.models
536
704
  }));
537
705
  }
538
706
  if (input.scout) {
539
707
  stepRoutes.push(resolveStepRoute({
540
708
  stepKey: "scout",
541
709
  role: "scout",
542
- cliModel: input.scout.model ?? input.cliModel,
710
+ modelRole: "scout",
711
+ cliModel: input.cliModel ?? input.scout.model,
543
712
  frontmatterModel: input.scout.frontmatterModel ?? input.scout.defaultModel,
544
- routingConfig: input.routingConfig
713
+ models: input.models
545
714
  }));
546
715
  }
547
716
  if (input.consolidate) {
548
717
  stepRoutes.push(resolveStepRoute({
549
718
  stepKey: "consolidate",
550
719
  role: "other",
720
+ modelRole: "consolidate",
551
721
  cliModel: input.consolidate.model ?? input.cliModel,
552
722
  frontmatterModel: input.consolidate.frontmatterModel ?? input.consolidate.defaultModel,
553
- routingConfig: input.routingConfig
723
+ models: input.models
554
724
  }));
555
725
  }
556
726
  if (input.materiality) {
557
- const judge = resolveMaterialityJudgeRoute(input.routingConfig);
558
- if (judge !== undefined)
727
+ const judge = resolveMaterialityJudgeRoute(input.models);
728
+ const hasClaudeStep = stepRoutes.some((s) => s.route.backend === "claude-code");
729
+ if (judge !== undefined && (input.models?.judge !== undefined || hasClaudeStep)) {
559
730
  stepRoutes.push(judge);
731
+ }
560
732
  }
561
733
  return createResolvedRoutePlan(stepRoutes);
562
734
  }
563
- function spawnModelForClaudeCli(route, executionModel) {
564
- const gateway = route.gateway ?? "direct";
565
- if (gateway !== "direct") {
566
- return route.modelSnapshot;
567
- }
568
- if (isModelAlias(executionModel)) {
569
- return executionModel;
570
- }
571
- try {
572
- const parsed = parseLogicalIdentity(executionModel);
573
- const alias = reverseAliasForCanonical(`${parsed.provider}/${parsed.model}`);
574
- if (alias !== undefined) {
575
- return alias;
576
- }
577
- } catch {}
578
- return route.modelSnapshot;
579
- }
580
- var ModelRoutingError, UnmappedRouteError, AmbiguousMappingError, UnauthorizedRouteError, SLASH_GRAMMAR_REGEX, MATERIALITY_STEP_KEY = "materiality", MATERIALITY_JUDGE_MODEL = "sonnet";
735
+ var ModelRoutingError, InvalidModelError, NEW_FORM_PREFIXES, MATERIALITY_STEP_KEY = "materiality", MATERIALITY_JUDGE_MODEL = "sonnet", MEASURED_JUDGE_MODELS;
581
736
  var init_routing = __esm(() => {
582
- init_redact();
583
- init_catalog();
584
- init_catalog();
737
+ init_model_name();
585
738
  ModelRoutingError = class ModelRoutingError extends Error {
586
739
  };
587
- UnmappedRouteError = class UnmappedRouteError extends ModelRoutingError {
588
- };
589
- AmbiguousMappingError = class AmbiguousMappingError extends ModelRoutingError {
590
- };
591
- UnauthorizedRouteError = class UnauthorizedRouteError extends ModelRoutingError {
740
+ InvalidModelError = class InvalidModelError extends ModelRoutingError {
592
741
  };
593
- SLASH_GRAMMAR_REGEX = /^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9._-]+)(?:#([a-zA-Z0-9._-]+))?$/;
742
+ NEW_FORM_PREFIXES = ["claude:", "opencode:"];
743
+ MEASURED_JUDGE_MODELS = [
744
+ "claude:sonnet-latest",
745
+ "claude:opus-latest"
746
+ ];
594
747
  });
595
748
 
596
749
  // src/compare/materiality.ts
@@ -663,8 +816,33 @@ var init_boundary = __esm(() => {
663
816
  });
664
817
 
665
818
  // src/security/evidence-redaction.ts
819
+ function nameParts(name) {
820
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter((part) => part.length > 0);
821
+ }
822
+ function isSecretName(name) {
823
+ const parts = nameParts(name);
824
+ const last = parts.at(-1);
825
+ if (last === undefined)
826
+ return false;
827
+ if (parts.some((part) => SECRET_WORDS.has(part)))
828
+ return true;
829
+ if (last === "token")
830
+ return true;
831
+ const qualifier = parts.at(-2);
832
+ return last === "key" && qualifier !== undefined && KEY_QUALIFIERS.has(qualifier);
833
+ }
834
+ function isNonSecretValue(value, name = "") {
835
+ const bare = value.replace(/^\\*(["'])(.*)\\*\1$/, "$2");
836
+ if (bare === "" || NON_SECRET_VALUES.some((shape) => shape.test(bare))) {
837
+ return true;
838
+ }
839
+ return /^\d{1,5}$/.test(bare) && !nameParts(name).some((part) => PASSWORD_WORDS.has(part));
840
+ }
841
+ function redactSecretShapes(value, isSecret = isSecretName, unquotedCamelCase = false) {
842
+ return value.replace(PEM_PRIVATE_KEY, REDACTED2).replace(URL_CREDENTIALS, `$1${REDACTED2}@`).replace(AWS_ACCESS_KEY_ID, REDACTED2).replace(STRIPE_KEY, REDACTED2).replace(JWT, REDACTED2).replace(QUOTED_ASSIGNMENT, (match, name, separator, value) => isSecret(name) && !isNonSecretValue(value, name) ? `${name}${separator}${REDACTED2}` : match).replace(UNQUOTED_ASSIGNMENT, (match, name, separator, value) => (unquotedCamelCase || !/[a-z][A-Z]/.test(name)) && isSecret(name) && !isNonSecretValue(value, name) ? `${name}${separator}${REDACTED2}` : match);
843
+ }
666
844
  function redactEvidenceText(value) {
667
- return value.replace(/\b(?:authorization|proxy-authorization|cookie|set-cookie)\s*:[^\r\n]*/gi, "[REDACTED HEADER]").replace(/https?:\/\/[^\s<>"']+/gi, (text) => {
845
+ return redactSecretShapes(value).replace(/\b(?:authorization|proxy-authorization|cookie|set-cookie)\s*:[^\r\n]*/gi, "[REDACTED HEADER]").replace(/https?:\/\/[^\s<>"']+/gi, (text) => {
668
846
  try {
669
847
  const url = new URL(text);
670
848
  url.username = "";
@@ -676,7 +854,7 @@ function redactEvidenceText(value) {
676
854
  } catch {
677
855
  return "[REDACTED URL]";
678
856
  }
679
- }).replace(/\b(?:sk-[\w-]+|gh[pousr]_[\w]+|github_pat_[\w]+|Bearer\s+[^\s,;]+)/gi, "[REDACTED]").replace(/((?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret)\s*[=:]\s*)[^\s,;&]+/gi, "$1[REDACTED]");
857
+ }).replace(/\b(?:sk-[\w-]+|gh[pousr]_[\w]+|github_pat_[\w]+|Bearer\s+[^\s,;]+)/gi, "[REDACTED]").replace(LEGACY_KEYWORD_VALUE, (match, keyword, value) => isNonSecretValue(value, keyword) ? match : `${keyword}[REDACTED]`);
680
858
  }
681
859
  function redactEvidence(value, depth = 0, budget = { nodes: 0 }) {
682
860
  if (++budget.nodes > 20000 || depth > 12)
@@ -707,10 +885,60 @@ function redactEvidence(value, depth = 0, budget = { nodes: 0 }) {
707
885
  }
708
886
  return Array.isArray(value) ? Object.values(result) : result;
709
887
  }
710
- var MAX_BYTES, SECRET;
888
+ var MAX_BYTES, REDACTED2 = "[REDACTED]", SECRET, SECRET_WORDS, KEY_QUALIFIERS, NON_SECRET_VALUES, PASSWORD_WORDS, EXPRESSION_VALUE, YAML_VALUE_BELOW, PEM_PRIVATE_KEY, URL_CREDENTIALS, AWS_ACCESS_KEY_ID, STRIPE_KEY, JWT, QUOTED_ASSIGNMENT, UNQUOTED_ASSIGNMENT, LEGACY_KEYWORD_VALUE;
711
889
  var init_evidence_redaction = __esm(() => {
712
890
  MAX_BYTES = 4 * 1024 * 1024;
713
891
  SECRET = /authorization|cookie|password|secret|api.?key|access.?token|refresh.?token|^token$|^key$/i;
892
+ SECRET_WORDS = new Set([
893
+ "secret",
894
+ "secrets",
895
+ "password",
896
+ "passwords",
897
+ "passwd",
898
+ "passphrase",
899
+ "apikey",
900
+ "apitoken",
901
+ "accesskey",
902
+ "accesstoken",
903
+ "authtoken",
904
+ "privatekey",
905
+ "secretkey",
906
+ "clientsecret",
907
+ "refreshtoken"
908
+ ]);
909
+ KEY_QUALIFIERS = new Set([
910
+ "api",
911
+ "access",
912
+ "private",
913
+ "secret",
914
+ "client",
915
+ "signing",
916
+ "encryption",
917
+ "master",
918
+ "session"
919
+ ]);
920
+ NON_SECRET_VALUES = [
921
+ /^\$\{\{(?:(?!\}\})[^\r\n])*\}\}$/,
922
+ /^(?:read|write|none|read-all|write-all|inherit)$/,
923
+ /^[|>][+-]?[1-9]?$/,
924
+ /^<[^<>\r\n]*>$/,
925
+ /^(?:x{3,}|X{3,}|\*{3,}|changeme|\[REDACTED\])$/,
926
+ /^\$[A-Z_][A-Z0-9_]*$/,
927
+ /^\$\{[A-Z_][A-Z0-9_]*\}$/,
928
+ /^(?:process\.env|Bun\.env|import\.meta\.env)\.[A-Za-z_]\w*$/,
929
+ /^(?:true|false)$/i
930
+ ];
931
+ PASSWORD_WORDS = new Set(["password", "passwd", "passphrase", "pin"]);
932
+ EXPRESSION_VALUE = String.raw`\$\{\{(?:[^$}\r\n]|\$(?!\{\{)|\}(?!\})){0,512}\}\}(?=[\s,;&"'\\]|$)`;
933
+ YAML_VALUE_BELOW = String.raw`:(?:[ \t]*\r?\n(?:[ \t]*(?:#[^\r\n]*)?\r?\n){0,3}(?![ \t]*[\w.-]+[ \t]*:(?:\s|$))[ \t]*(?!#)|[ \t]*)`;
934
+ PEM_PRIVATE_KEY = /-----BEGIN[A-Z0-9 ]*PRIVATE KEY[A-Z ]*-----(?:[\s\S]*?-----END[A-Z0-9 ]*PRIVATE KEY[A-Z ]*-----|(?:[A-Za-z0-9+/=\s\u2192]|\\[nrt])*)/g;
935
+ URL_CREDENTIALS = /(?<![a-z0-9+.-])([a-z][a-z0-9+.-]*:\/\/)[^\s/@:'"<>\\]*:[^\s/@'"<>\\]+@/gi;
936
+ AWS_ACCESS_KEY_ID = /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g;
937
+ STRIPE_KEY = /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{10,}/g;
938
+ JWT = /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{4,}\.eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*/g;
939
+ QUOTED_ASSIGNMENT = /(?<![\w.-])([\w.-]+)(\\*["']?\s*[=:]\s*\\*["'])([^"'\\\r\n]+)/g;
940
+ UNQUOTED_ASSIGNMENT = new RegExp(String.raw`(?<![\w.-])([A-Za-z][\w-]*)([ \t]*(?:=[ \t]*|${YAML_VALUE_BELOW}))(${EXPRESSION_VALUE}|[^\s,;&"'\\]+)`, "g");
941
+ LEGACY_KEYWORD_VALUE = new RegExp(String.raw`((?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret)[ \t]*(?:=[ \t]*|${YAML_VALUE_BELOW}))(${EXPRESSION_VALUE}|[^\s,;&]+)`, "gi");
714
942
  });
715
943
 
716
944
  // src/review/materiality-gate.ts
@@ -1065,7 +1293,7 @@ function validateReviewSpec(candidate) {
1065
1293
  if (diversityEnabled && Array.isArray(a.models)) {
1066
1294
  for (const model of a.models) {
1067
1295
  try {
1068
- parseLogicalIdentity(model);
1296
+ modelNameFromAlias(model);
1069
1297
  } catch (error) {
1070
1298
  must2(false, `agents[${i}].models contains invalid model identity "${model}": ${error.message}`);
1071
1299
  }
@@ -1074,7 +1302,7 @@ function validateReviewSpec(candidate) {
1074
1302
  must2(a.model === undefined || typeof a.model === "string" && a.model.length > 0, `agents[${i}].model must be a non-empty string when present`);
1075
1303
  if (a.model !== undefined) {
1076
1304
  try {
1077
- parseLogicalIdentity(a.model);
1305
+ modelNameFromAlias(a.model);
1078
1306
  } catch (error) {
1079
1307
  must2(false, `agents[${i}].model "${a.model}" is not a valid model identity: ${error.message}`);
1080
1308
  }
@@ -1118,7 +1346,7 @@ function defaultReviewSpec() {
1118
1346
  }
1119
1347
  var SAFE_SLUG_RE, ReviewSpecValidationError;
1120
1348
  var init_spec = __esm(() => {
1121
- init_routing();
1349
+ init_model_name();
1122
1350
  SAFE_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
1123
1351
  ReviewSpecValidationError = class ReviewSpecValidationError extends Error {
1124
1352
  };
@@ -1349,9 +1577,12 @@ function parseCliClass(value) {
1349
1577
  return;
1350
1578
  if (value.kind === "unknown")
1351
1579
  return { kind: "unknown" };
1352
- if (value.kind === "route") {
1353
- if (value.reason === "unmapped" || value.reason === "ambiguous" || value.reason === "spend-disabled") {
1354
- return { kind: "route", reason: value.reason };
1580
+ if (value.kind === "trigger") {
1581
+ return value.check === "no-credential" ? { kind: "trigger", check: "no-credential" } : undefined;
1582
+ }
1583
+ if (value.kind === "credential") {
1584
+ if (value.failureClass === "missing_provider_record" || value.failureClass === "missing_subscription_record") {
1585
+ return { kind: "credential", failureClass: value.failureClass };
1355
1586
  }
1356
1587
  return;
1357
1588
  }
@@ -1361,7 +1592,7 @@ function parseCliClass(value) {
1361
1592
  }
1362
1593
  }
1363
1594
  if (value.kind === "config-parse") {
1364
- if (value.source === "routing" || value.source === "repo-config" || value.source === "extra-hunters") {
1595
+ if (value.source === "repo-config" || value.source === "extra-hunters") {
1365
1596
  return { kind: "config-parse", source: value.source };
1366
1597
  }
1367
1598
  return;
@@ -1510,46 +1741,83 @@ function parseCliRecord(text) {
1510
1741
  function isOpencodeRoute(params) {
1511
1742
  return params.backend?.trim() === "opencode";
1512
1743
  }
1744
+ function isCryskSecretsDetail(params) {
1745
+ const detail = params.detail?.trim() ?? "";
1746
+ return detail.startsWith("CRYSK_") || /^line \d+ of the crysk-secrets input /.test(detail);
1747
+ }
1748
+ function isEmptySlotDetail(detail) {
1749
+ const parts = detail.trim().split(/; (?=CRYSK_OPENCODE__API_KEY )/);
1750
+ return parts.every((part) => part.trim() === EMPTY_SLOT_DETAIL);
1751
+ }
1752
+ function unsupportedOAuthApiKeyNames(detail) {
1753
+ const names = [];
1754
+ for (const part of detail.split(/; (?=CRYSK_OPENCODE_[A-Z0-9_]+_OAUTH )/)) {
1755
+ const name = UNSUPPORTED_OAUTH_DETAIL_RE.exec(part.trim())?.[1];
1756
+ if (name === undefined)
1757
+ return;
1758
+ names.push(name);
1759
+ }
1760
+ return names.length === 0 ? undefined : names;
1761
+ }
1762
+ function cryskSecretsFixes(params) {
1763
+ if (isEmptySlotDetail(params.detail ?? ""))
1764
+ return [...EMPTY_SLOT_FIXES];
1765
+ const apiKeys = unsupportedOAuthApiKeyNames(params.detail ?? "");
1766
+ if (apiKeys === undefined)
1767
+ return CRYSK_SECRETS_FIXES;
1768
+ return [
1769
+ "Only openai reads an _OAUTH secret for now. Remove that _OAUTH secret from the crysk-secrets input and set this provider's API key instead:",
1770
+ ...apiKeys.map((apiKey) => `$ gh secret set ${apiKey}`),
1771
+ "Each line of the crysk-secrets input is NAME=value, one CRYSK_* secret per line."
1772
+ ];
1773
+ }
1774
+ function cryskSecretsAnnotationFix(params) {
1775
+ if (isEmptySlotDetail(params.detail ?? "")) {
1776
+ return "the Crysk platform forwarded an OpenCode key in a slot with no provider: save that OpenCode provider again in the platform's model settings, then re-run";
1777
+ }
1778
+ return unsupportedOAuthApiKeyNames(params.detail ?? "") === undefined ? "re-set the CRYSK_* secret it names (an _OAUTH secret is base64 -w0 of the provider's OpenCode record)" : "remove that _OAUTH secret from the crysk-secrets input and set the provider's _API_KEY secret instead (only openai reads an _OAUTH secret for now)";
1779
+ }
1780
+ function cryskSecretsLine(name) {
1781
+ return `${name}=$` + `{{ secrets.${name} }}`;
1782
+ }
1513
1783
  function single(why, fixes, annotationFix) {
1514
1784
  return { default: { why, fixes, annotationFix } };
1515
1785
  }
1516
1786
  function parseOutcomeCode(body) {
1517
1787
  if (matchMarkerPrefix(body, OUTCOME_MARKER_PREFIX) === undefined)
1518
1788
  return null;
1519
- const heading = /^### (PRH-[A-Z0-9-]+)(?=[:\s]|$)/m.exec(body);
1520
- const code = heading?.[1];
1521
- if (code === undefined)
1789
+ const heading = /^### (?:CRYSK|PRH)-([A-Z0-9-]+)(?=[:\s]|$)/m.exec(body);
1790
+ if (heading === null)
1522
1791
  return null;
1792
+ const code = `CRYSK-${heading[1]}`;
1523
1793
  return ERROR_CODES.includes(code) ? code : null;
1524
1794
  }
1525
- var ERROR_CODES, CLI_RECORD_FILE = "cli.json", PENDING_AT_FILE = "pending-at", STATUS_DESCRIPTION_MAX = 140, TRANSPORT_CAUSE_LOOKUP, PROVIDER_NAME_PATTERN, MODEL_NAME_PATTERN, FAILURE_CREDENTIAL_LOOKUP, FAILURE_DETAIL_MAX = 160, FAILURE_DETAIL_PATTERN, RECORD_PARAM_KEYS, CLI_OUTCOMES, CLI_SKIPS, CLI_HEAD_PATTERN, ENGINE_DEFECT_ISSUE = 'gh issue create -R cryskai/crysk --title "PRH-ENGINE-DEFECT {detail}" --body "{runUrl}"', RERUN_FAILED = "$ gh run rerun {runId} --failed", REVIEW_AGAIN = '$ gh pr comment {pr} --body "/crysk review"', LEGACY_REVIEW_NOTE = "On a workflow set up before the rename, comment `/pr-hero review` instead.", OPENCODE_STORE = "$ gh secret set OPENCODE_AUTH_JSON < ~/.local/share/opencode/auth.json", CRED_STORE_WHY = "the credential store does not hold what this route needs", CLAUDE_SUBSCRIPTION_FIXES, OPENCODE_SUBSCRIPTION_FIXES, MODEL_NOT_SERVED, ROUTE_WHY = "every agent needs exactly one backend, provider and model", PROVIDER_REFUSED_WHY = "the provider's safety system declined this input", UNCLASSIFIED_FIXES, UNCLASSIFIED_FIX = "re-run the failed jobs with `gh run rerun {runId} --failed`", GITHUB_TOKEN_INPUT, CLAUDE_TOKEN_INPUT, OPENCODE_AUTH_INPUT, ANTHROPIC_API_KEY_INPUT, CLAUDE_CREDENTIAL_FIXES, LEGACY_ROUTING_NOTE = "A workflow set up before the rename reads PRHERO_ROUTING instead: set that one, or run `crysk ci init --force` so the workflow also reads CRYSK_ROUTING.", OPENCODE_CREDENTIAL_FIXES, PROVIDER_LIMITED, CREDENTIAL_UNUSABLE_ENV, ROUTE_UNMAPPED, RUNTIME_LOCAL, GITHUB_SERVER, ERROR_CATALOG, OUTCOME_MARKER_PREFIX;
1795
+ var ERROR_CODES, CLI_RECORD_FILE = "cli.json", PENDING_AT_FILE = "pending-at", RUN_DIR_FILE = "run-dir", STATUS_DESCRIPTION_MAX = 140, TRANSPORT_CAUSE_LOOKUP, PROVIDER_NAME_PATTERN, MODEL_NAME_PATTERN, FAILURE_CREDENTIAL_LOOKUP, FAILURE_DETAIL_MAX = 160, FAILURE_DETAIL_PATTERN, RECORD_PARAM_KEYS, CLI_OUTCOMES, CLI_SKIPS, CLI_HEAD_PATTERN, ENGINE_DEFECT_ISSUE = 'gh issue create -R cryskai/crysk --title "CRYSK-ENGINE-DEFECT {detail}" --body "{runUrl}"', RERUN_FAILED = "$ gh run rerun {runId} --failed", REVIEW_AGAIN = '$ gh pr comment {pr} --body "/crysk review"', LEGACY_REVIEW_NOTE = "On a workflow set up before the rename, comment `/pr-hero review` instead.", OPENCODE_API_KEY_SECRET = "$ gh secret set CRYSK_OPENCODE_<PROVIDER>_API_KEY", OPENCODE_PROVIDER_TOKEN_NOTE = "<PROVIDER> is the provider id uppercased with `-` and `.` as `_` (`deepseek` is DEEPSEEK).", OPENAI_OAUTH_SECRET = "$ jq -c .openai ~/.local/share/opencode/auth.json | base64 -w0 | gh secret set CRYSK_OPENCODE_OPENAI_OAUTH", CRED_STORE_WHY = "the credential store does not hold what this route needs", CLAUDE_SUBSCRIPTION_FIXES, OPENCODE_SUBSCRIPTION_FIXES, CRYSK_SECRETS_FIXES, EMPTY_SLOT_DETAIL = "CRYSK_OPENCODE__API_KEY has a value but no provider: an unused OpenCode slot must be empty", EMPTY_SLOT_FIXES, UNSUPPORTED_OAUTH_DETAIL_RE, MODEL_NOT_SERVED, PROVIDER_REFUSED_WHY = "the provider's safety system declined this input", UNCLASSIFIED_FIXES, UNCLASSIFIED_FIX = "re-run the failed jobs with `gh run rerun {runId} --failed`", GITHUB_TOKEN_INPUT, CLAUDE_CREDENTIAL_FIXES, OPENCODE_CREDENTIAL_FIXES, MODELS_INPUT_LINE, CREDENTIALS_INPUT_LINE, REMOVED_INPUT_FIXES, PROVIDER_LIMITED, CREDENTIAL_UNUSABLE_ENV, RUNTIME_LOCAL, GITHUB_SERVER, ERROR_CATALOG, OUTCOME_MARKER_PREFIX;
1526
1796
  var init_outcome = __esm(() => {
1527
1797
  init_brand();
1528
1798
  ERROR_CODES = [
1529
- "PRH-CRED-MISSING",
1530
- "PRH-CRED-UNUSABLE",
1531
- "PRH-CRED-REJECTED",
1532
- "PRH-ROUTING-MISSING",
1533
- "PRH-ROUTING-INVALID",
1534
- "PRH-ROUTE-UNRESOLVABLE",
1535
- "PRH-MODEL-UNAVAILABLE",
1536
- "PRH-PROMPTSET-INVALID",
1537
- "PRH-GOTCHAS-MISSING",
1538
- "PRH-CONFIG-INVALID",
1539
- "PRH-TOKEN-PERMISSION",
1540
- "PRH-GITHUB-TOKEN-INVALID",
1541
- "PRH-GITHUB-UNAVAILABLE",
1542
- "PRH-PR-UNRESOLVED",
1543
- "PRH-STATUS-WRITE-FAILED",
1544
- "PRH-RUNTIME-UNAVAILABLE",
1545
- "PRH-INSTALL-FAILED",
1546
- "PRH-PROVIDER-LIMITED",
1547
- "PRH-PROVIDER-UNAVAILABLE",
1548
- "PRH-PROVIDER-REFUSED",
1549
- "PRH-ENGINE-DEFECT",
1550
- "PRH-HUNTERS-FAILED",
1551
- "PRH-UNCLASSIFIED",
1552
- "PRH-CANCELLED"
1799
+ "CRYSK-CRED-MISSING",
1800
+ "CRYSK-INPUT-REMOVED",
1801
+ "CRYSK-CRED-UNUSABLE",
1802
+ "CRYSK-CRED-REJECTED",
1803
+ "CRYSK-MODEL-UNAVAILABLE",
1804
+ "CRYSK-PROMPTSET-INVALID",
1805
+ "CRYSK-GOTCHAS-MISSING",
1806
+ "CRYSK-CONFIG-INVALID",
1807
+ "CRYSK-TOKEN-PERMISSION",
1808
+ "CRYSK-GITHUB-TOKEN-INVALID",
1809
+ "CRYSK-GITHUB-UNAVAILABLE",
1810
+ "CRYSK-PR-UNRESOLVED",
1811
+ "CRYSK-STATUS-WRITE-FAILED",
1812
+ "CRYSK-RUNTIME-UNAVAILABLE",
1813
+ "CRYSK-INSTALL-FAILED",
1814
+ "CRYSK-PROVIDER-LIMITED",
1815
+ "CRYSK-PROVIDER-UNAVAILABLE",
1816
+ "CRYSK-PROVIDER-REFUSED",
1817
+ "CRYSK-ENGINE-DEFECT",
1818
+ "CRYSK-HUNTERS-FAILED",
1819
+ "CRYSK-UNCLASSIFIED",
1820
+ "CRYSK-CANCELLED"
1553
1821
  ];
1554
1822
  TRANSPORT_CAUSE_LOOKUP = {
1555
1823
  auth_invalid: true,
@@ -1584,7 +1852,8 @@ var init_outcome = __esm(() => {
1584
1852
  "scope",
1585
1853
  "runId",
1586
1854
  "runUrl",
1587
- "detail"
1855
+ "detail",
1856
+ "model"
1588
1857
  ];
1589
1858
  CLI_OUTCOMES = [
1590
1859
  "reviewing",
@@ -1603,23 +1872,36 @@ var init_outcome = __esm(() => {
1603
1872
  ];
1604
1873
  CLI_HEAD_PATTERN = /^[0-9a-f]{40}$/;
1605
1874
  CLAUDE_SUBSCRIPTION_FIXES = [
1606
- "Log in again with `claude setup-token`, then set `CLAUDE_CODE_OAUTH_TOKEN`:",
1607
- "$ claude setup-token && gh secret set CLAUDE_CODE_OAUTH_TOKEN"
1875
+ "Log in again with `claude setup-token`, then set `CRYSK_CLAUDE_OAUTH_TOKEN`:",
1876
+ "$ claude setup-token && gh secret set CRYSK_CLAUDE_OAUTH_TOKEN"
1608
1877
  ];
1609
1878
  OPENCODE_SUBSCRIPTION_FIXES = [
1610
- "Provider `openai` expects a ChatGPT login: run `opencode auth login` and choose ChatGPT, then re-set the secret:",
1879
+ "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):",
1611
1880
  "$ opencode auth login",
1612
- OPENCODE_STORE,
1613
- "Or rename the provider in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename)."
1881
+ OPENAI_OAUTH_SECRET,
1882
+ "Or bill per token with an OpenAI API key instead:",
1883
+ "$ gh secret set CRYSK_OPENCODE_OPENAI_API_KEY"
1614
1884
  ];
1885
+ CRYSK_SECRETS_FIXES = [
1886
+ "Re-set the CRYSK_* secret the message names. An _OAUTH secret is the provider's record from your OpenCode auth file, base64 on one line (on macOS, drop -w0):",
1887
+ OPENAI_OAUTH_SECRET,
1888
+ "Each line of the crysk-secrets input is NAME=value, one CRYSK_* secret per line."
1889
+ ];
1890
+ EMPTY_SLOT_FIXES = [
1891
+ "The Crysk platform passed an OpenCode key through a provider slot with no provider name, so Crysk cannot tell whose key it is. The platform's provider slots for this run are empty while a key was forwarded:",
1892
+ "Open the repository's model settings on the Crysk platform, save the OpenCode provider whose key this is again so its slot names the provider, then re-run the workflow:",
1893
+ "$ gh run rerun {runId}",
1894
+ "In a workflow you wrote yourself, name the provider in the line: CRYSK_OPENCODE_<PROVIDER>_API_KEY, and leave an unused slot as CRYSK_OPENCODE__API_KEY= with nothing after it."
1895
+ ];
1896
+ UNSUPPORTED_OAUTH_DETAIL_RE = /^CRYSK_OPENCODE_[A-Z0-9_]+_OAUTH is an OpenCode subscription record, which Crysk reads only for openai for now; set (CRYSK_OPENCODE_[A-Z0-9_]+_API_KEY) instead$/;
1615
1897
  MODEL_NOT_SERVED = {
1616
- why: "the routing names a model this provider does not offer",
1898
+ why: "the configured models name a model this provider does not offer",
1617
1899
  fixes: [
1618
- "Fix the `modelSnapshot` for this step in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename).",
1900
+ "Set a model this provider serves for this step's role in `models` (on the Crysk platform, the model settings).",
1619
1901
  "List the models this provider serves:",
1620
1902
  "$ opencode models {provider}"
1621
1903
  ],
1622
- annotationFix: "fix the `modelSnapshot` for {step} in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename) to a model that {provider} serves"
1904
+ annotationFix: "set a model that {provider} serves for {step}'s role in `models` (the Crysk platform's model settings)"
1623
1905
  };
1624
1906
  UNCLASSIFIED_FIXES = [
1625
1907
  "Re-run the failed jobs:",
@@ -1628,30 +1910,41 @@ var init_outcome = __esm(() => {
1628
1910
  "$ gh run view {runId} --log-failed"
1629
1911
  ];
1630
1912
  GITHUB_TOKEN_INPUT = "github-token: $" + "{{ secrets.GITHUB_TOKEN }}";
1631
- CLAUDE_TOKEN_INPUT = "claude-token: $" + "{{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}";
1632
- OPENCODE_AUTH_INPUT = "opencode-auth: $" + "{{ secrets.OPENCODE_AUTH_JSON }}";
1633
- ANTHROPIC_API_KEY_INPUT = "anthropic-api-key: $" + "{{ secrets.ANTHROPIC_API_KEY }}";
1634
1913
  CLAUDE_CREDENTIAL_FIXES = [
1635
1914
  "Set one credential for the route you use:",
1636
- "$ claude setup-token && gh secret set CLAUDE_CODE_OAUTH_TOKEN",
1637
- "$ gh secret set ANTHROPIC_API_KEY",
1638
- "$ opencode auth login && gh secret set OPENCODE_AUTH_JSON < ~/.local/share/opencode/auth.json",
1639
- `If the secret is already set, check that the workflow passes it to the action under \`with:\`, for example \`${CLAUDE_TOKEN_INPUT}\` or \`${ANTHROPIC_API_KEY_INPUT}\`: a secret the workflow does not pass never reaches Crysk.`,
1915
+ "$ claude setup-token && gh secret set CRYSK_CLAUDE_OAUTH_TOKEN",
1916
+ "$ gh secret set CRYSK_CLAUDE_API_KEY",
1917
+ `If the secret is already set, check that the workflow passes it to the action in the \`crysk-secrets\` input, one NAME=value line per secret, for example \`${cryskSecretsLine("CRYSK_CLAUDE_OAUTH_TOKEN")}\`: a secret the workflow does not pass never reaches Crysk.`,
1640
1918
  "Dependabot PRs read Dependabot secrets, so set this one too:",
1641
- "$ gh secret set --app dependabot CLAUDE_CODE_OAUTH_TOKEN",
1919
+ "$ gh secret set --app dependabot CRYSK_CLAUDE_OAUTH_TOKEN",
1642
1920
  "Then re-run the workflow:",
1643
1921
  "$ gh run rerun {runId}"
1644
1922
  ];
1645
1923
  OPENCODE_CREDENTIAL_FIXES = [
1646
- "Set the OpenCode credential for the route you use:",
1647
- "$ opencode auth login && gh secret set OPENCODE_AUTH_JSON < ~/.local/share/opencode/auth.json",
1648
- `If the secret is already set, check that the workflow passes it to the action under \`with:\`, for example \`${OPENCODE_AUTH_INPUT}\`: a secret the workflow does not pass never reaches Crysk.`,
1649
- "An OpenCode route also needs the routing variable:",
1650
- "$ gh variable set CRYSK_ROUTING --body '<routing-object-json>'",
1651
- LEGACY_ROUTING_NOTE,
1924
+ "Set the OpenCode credential of each provider your models use:",
1925
+ OPENCODE_API_KEY_SECRET,
1926
+ OPENCODE_PROVIDER_TOKEN_NOTE,
1927
+ "For an OpenAI subscription, set its record from your OpenCode auth file, base64 on one line (on macOS, drop -w0):",
1928
+ OPENAI_OAUTH_SECRET,
1929
+ `If the secret is already set, check that the workflow passes it to the action in the \`crysk-secrets\` input, one NAME=value line per secret, for example \`${cryskSecretsLine("CRYSK_OPENCODE_DEEPSEEK_API_KEY")}\`: a secret the workflow does not pass never reaches Crysk.`,
1652
1930
  "Dependabot PRs read Dependabot secrets, so set this one too:",
1653
- "$ gh secret set --app dependabot OPENCODE_AUTH_JSON < ~/.local/share/opencode/auth.json",
1654
- "A Claude route uses `CLAUDE_CODE_OAUTH_TOKEN` instead, from `claude setup-token`.",
1931
+ "$ gh secret set --app dependabot CRYSK_OPENCODE_<PROVIDER>_API_KEY",
1932
+ "A Claude route uses `CRYSK_CLAUDE_OAUTH_TOKEN` instead, from `claude setup-token`.",
1933
+ "Then re-run the workflow:",
1934
+ "$ gh run rerun {runId}"
1935
+ ];
1936
+ MODELS_INPUT_LINE = "models: $" + "{{ vars.CRYSK_MODELS }}";
1937
+ CREDENTIALS_INPUT_LINE = "credentials: $" + "{{ vars.CRYSK_CREDENTIALS }}";
1938
+ REMOVED_INPUT_FIXES = [
1939
+ "Set the CRYSK_* secret that replaces each old credential input:",
1940
+ "$ claude setup-token && gh secret set CRYSK_CLAUDE_OAUTH_TOKEN",
1941
+ "$ gh secret set CRYSK_CLAUDE_API_KEY",
1942
+ "$ gh secret set CRYSK_OPENCODE_<PROVIDER>_API_KEY",
1943
+ "claude-token becomes CRYSK_CLAUDE_OAUTH_TOKEN and anthropic-api-key becomes CRYSK_CLAUDE_API_KEY. opencode-auth becomes one CRYSK_OPENCODE_<PROVIDER>_API_KEY per provider your models use, <PROVIDER> being the provider id uppercased with `-` and `.` as `_`. An OpenAI subscription is the provider's record from your OpenCode auth file, base64 on one line (on macOS, drop -w0):",
1944
+ "$ jq -c .openai ~/.local/share/opencode/auth.json | base64 -w0 | gh secret set CRYSK_OPENCODE_OPENAI_OAUTH",
1945
+ `In the workflow, delete the old lines under \`with:\` and pass the secrets in one \`crysk-secrets: |\` block, one NAME=value line per secret, for example \`${cryskSecretsLine("CRYSK_CLAUDE_OAUTH_TOKEN")}\`.`,
1946
+ `The routing input becomes the \`models\` input: set your models per role in the CRYSK_MODELS variable, and pass it as \`${MODELS_INPUT_LINE}\` (a repository connected to the Crysk platform takes them from its model settings instead).`,
1947
+ `$ gh variable set CRYSK_MODELS --body '{"default": ["claude:sonnet-latest"]}'`,
1655
1948
  "Then re-run the workflow:",
1656
1949
  "$ gh run rerun {runId}"
1657
1950
  ];
@@ -1669,13 +1962,6 @@ var init_outcome = __esm(() => {
1669
1962
  fixes: ["Set the secret again:", "$ gh secret set {secret}"],
1670
1963
  annotationFix: "set the {secret} secret with `gh secret set {secret}`"
1671
1964
  };
1672
- ROUTE_UNMAPPED = {
1673
- why: ROUTE_WHY,
1674
- fixes: [
1675
- "Add or complete this model's route in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename), with an explicit `modelSnapshot`."
1676
- ],
1677
- annotationFix: "add or complete this model's route in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename), with an explicit `modelSnapshot`"
1678
- };
1679
1965
  RUNTIME_LOCAL = {
1680
1966
  why: "a required tool is missing from your environment",
1681
1967
  fixes: ["Reconcile the crysk install:", "$ crysk upgrade --reconcile"],
@@ -1687,13 +1973,19 @@ var init_outcome = __esm(() => {
1687
1973
  annotationFix: "re-run the workflow once GitHub is serving requests again"
1688
1974
  };
1689
1975
  ERROR_CATALOG = {
1690
- "PRH-CRED-MISSING": {
1976
+ "CRYSK-CRED-MISSING": {
1691
1977
  level: "error",
1692
1978
  owner: "config",
1693
1979
  what: "No credential for the {backend} route reached the action",
1694
- variants: single("Crysk cannot authenticate, so it cannot review this PR", (params) => isOpencodeRoute(params) ? OPENCODE_CREDENTIAL_FIXES : CLAUDE_CREDENTIAL_FIXES, (params) => params.backend?.trim() === "opencode" ? "set the OPENCODE_AUTH_JSON secret: `gh secret set OPENCODE_AUTH_JSON < ~/.local/share/opencode/auth.json`" : "set a Claude credential: `claude setup-token && gh secret set CLAUDE_CODE_OAUTH_TOKEN`")
1980
+ variants: single("Crysk cannot authenticate, so it cannot review this PR", (params) => isOpencodeRoute(params) ? OPENCODE_CREDENTIAL_FIXES : CLAUDE_CREDENTIAL_FIXES, (params) => params.backend?.trim() === "opencode" ? "set the provider's CRYSK_OPENCODE_<PROVIDER>_API_KEY secret (`gh secret set CRYSK_OPENCODE_<PROVIDER>_API_KEY`) and pass it in the crysk-secrets input" : "set a Claude credential (`claude setup-token && gh secret set CRYSK_CLAUDE_OAUTH_TOKEN`) and pass it in the crysk-secrets input")
1695
1981
  },
1696
- "PRH-CRED-UNUSABLE": {
1982
+ "CRYSK-INPUT-REMOVED": {
1983
+ level: "error",
1984
+ owner: "config",
1985
+ what: "The workflow passes inputs Crysk no longer reads: {detail}",
1986
+ variants: single("Crysk now takes its credentials only from the CRYSK_* secrets in the crysk-secrets input, and its models only from `models`, so a review would run without the credential or models the workflow names", REMOVED_INPUT_FIXES, "delete the {detail} input lines from the workflow and pass the CRYSK_* secrets in the crysk-secrets input instead (a routing input becomes the models input, from `vars.CRYSK_MODELS`)")
1987
+ },
1988
+ "CRYSK-CRED-UNUSABLE": {
1697
1989
  level: "error",
1698
1990
  owner: "config",
1699
1991
  what: "The {backend}/{provider} route for {step} has no usable credential ({detail})",
@@ -1703,69 +1995,68 @@ var init_outcome = __esm(() => {
1703
1995
  whatWithoutModel: "The {backend}/{provider} route for {step} has no usable credential ({detail})",
1704
1996
  why: CRED_STORE_WHY,
1705
1997
  fixes: [
1706
- "Add {provider} to the OpenCode store, then re-set the secret:",
1707
- "$ opencode auth login",
1708
- OPENCODE_STORE
1998
+ "Set {provider}'s secret and pass it in the crysk-secrets input:",
1999
+ OPENCODE_API_KEY_SECRET,
2000
+ OPENCODE_PROVIDER_TOKEN_NOTE
1709
2001
  ],
1710
- annotationFix: "add {provider} to the OpenCode store with `opencode auth login`, then set OPENCODE_AUTH_JSON again"
2002
+ annotationFix: "set {provider}'s CRYSK_OPENCODE_<PROVIDER>_API_KEY secret and pass it in the crysk-secrets input"
1711
2003
  },
1712
2004
  missing_subscription_record: {
1713
2005
  why: CRED_STORE_WHY,
1714
2006
  fixes: (params) => isOpencodeRoute(params) ? OPENCODE_SUBSCRIPTION_FIXES : CLAUDE_SUBSCRIPTION_FIXES,
1715
- annotationFix: (params) => isOpencodeRoute(params) ? "run `opencode auth login` and choose ChatGPT for provider `openai`, then re-set OPENCODE_AUTH_JSON, or rename the provider in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename)" : "log in again with `claude setup-token` and set `CLAUDE_CODE_OAUTH_TOKEN` (`gh secret set CLAUDE_CODE_OAUTH_TOKEN`)"
2007
+ annotationFix: (params) => isOpencodeRoute(params) ? "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" : "log in again with `claude setup-token` and set `CRYSK_CLAUDE_OAUTH_TOKEN` (`gh secret set CRYSK_CLAUDE_OAUTH_TOKEN`)"
1716
2008
  },
1717
2009
  malformed_payload: {
1718
2010
  what: "The credential store is not usable: {detail}",
1719
2011
  why: CRED_STORE_WHY,
1720
- fixes: [
2012
+ fixes: (params) => isCryskSecretsDetail(params) ? cryskSecretsFixes(params) : [
1721
2013
  "Check that the store is a JSON object:",
1722
2014
  `$ jq -e 'type=="object"' ~/.local/share/opencode/auth.json`,
1723
- "Then re-set the secret:",
1724
- OPENCODE_STORE
2015
+ "In CI the action builds this file from the CRYSK_OPENCODE_* secrets: re-set the one for this provider.",
2016
+ OPENCODE_API_KEY_SECRET
1725
2017
  ],
1726
- annotationFix: "make the OpenCode auth store a JSON object, then set OPENCODE_AUTH_JSON again"
2018
+ annotationFix: (params) => isCryskSecretsDetail(params) ? cryskSecretsAnnotationFix(params) : "make the OpenCode auth store a JSON object (in CI, re-set the provider's CRYSK_OPENCODE_* secret)"
1727
2019
  },
1728
2020
  source_read_failed: CREDENTIAL_UNUSABLE_ENV,
1729
2021
  "env-absent": CREDENTIAL_UNUSABLE_ENV,
1730
2022
  default: CREDENTIAL_UNUSABLE_ENV
1731
2023
  }
1732
2024
  },
1733
- "PRH-CRED-REJECTED": {
2025
+ "CRYSK-CRED-REJECTED": {
1734
2026
  level: "error",
1735
2027
  owner: "config",
1736
2028
  what: "provider {provider} rejected the credential in {secret}",
1737
2029
  variants: {
1738
2030
  api_key: {
1739
- why: "the key is invalid, expired or revoked, and the CLI uses it ahead of CLAUDE_CODE_OAUTH_TOKEN",
2031
+ why: "the key is invalid, expired or revoked, and it is the Claude credential this run chose from credentials.claude",
1740
2032
  fixes: [
1741
2033
  "Create a new key in the Claude Console and set it:",
1742
2034
  "$ gh secret set {secret}",
1743
- "Or delete the secret so the review uses CLAUDE_CODE_OAUTH_TOKEN (setting CLAUDE_CODE_OAUTH_TOKEN alone changes nothing while {secret} is set):",
1744
- "$ gh secret delete {secret}",
2035
+ "Or run on the subscription: set CRYSK_CLAUDE_OAUTH_TOKEN and put subscription first in `credentials.claude` (the default order).",
1745
2036
  "Then ask for a new review:",
1746
2037
  REVIEW_AGAIN,
1747
2038
  LEGACY_REVIEW_NOTE
1748
2039
  ],
1749
- annotationFix: "create a new key and run `gh secret set {secret}`, or delete the {secret} secret so the OAuth token is used (setting CLAUDE_CODE_OAUTH_TOKEN alone changes nothing while the key is set)"
2040
+ annotationFix: "create a new key and run `gh secret set {secret}`, or set CRYSK_CLAUDE_OAUTH_TOKEN and put subscription first in `credentials.claude` (the default order)"
1750
2041
  },
1751
2042
  oauth: {
1752
2043
  why: "it is expired, revoked, or a short-lived /login session token",
1753
2044
  fixes: [
1754
- "$ claude setup-token && gh secret set CLAUDE_CODE_OAUTH_TOKEN",
2045
+ "$ claude setup-token && gh secret set {secret}",
1755
2046
  "Then ask for a new review:",
1756
2047
  REVIEW_AGAIN,
1757
2048
  LEGACY_REVIEW_NOTE
1758
2049
  ],
1759
- annotationFix: "log in again with `claude setup-token` and set `CLAUDE_CODE_OAUTH_TOKEN` (`gh secret set CLAUDE_CODE_OAUTH_TOKEN`)"
2050
+ annotationFix: "log in again with `claude setup-token` and set `{secret}` (`gh secret set {secret}`)"
1760
2051
  },
1761
2052
  default: {
1762
2053
  why: "it is expired, revoked, or a short-lived /login session token",
1763
2054
  fixes: [
1764
- "$ claude setup-token && gh secret set CLAUDE_CODE_OAUTH_TOKEN",
2055
+ "$ claude setup-token && gh secret set CRYSK_CLAUDE_OAUTH_TOKEN",
1765
2056
  "Or, for an API key, create a new key in the Claude Console and set it:",
1766
- "$ gh secret set ANTHROPIC_API_KEY",
1767
- "Or, for OpenCode, re-export the auth store and re-set the secret:",
1768
- OPENCODE_STORE,
2057
+ "$ gh secret set CRYSK_CLAUDE_API_KEY",
2058
+ "Or, for OpenCode, set the provider's key again:",
2059
+ OPENCODE_API_KEY_SECRET,
1769
2060
  "Then ask for a new review:",
1770
2061
  REVIEW_AGAIN,
1771
2062
  LEGACY_REVIEW_NOTE
@@ -1774,57 +2065,7 @@ var init_outcome = __esm(() => {
1774
2065
  }
1775
2066
  }
1776
2067
  },
1777
- "PRH-ROUTING-MISSING": {
1778
- level: "error",
1779
- owner: "config",
1780
- what: "OpenCode auth is set but the routing variable is empty, so the default Claude route is used",
1781
- variants: single("the run would fail later at the Claude credential check", [
1782
- '$ gh variable set CRYSK_ROUTING --body "$(jq -c .routing ~/.crysk/config.json)"',
1783
- "On a machine set up before the rename the config is ~/.prhero/config.json: use that path in the command.",
1784
- LEGACY_ROUTING_NOTE
1785
- ], `set CRYSK_ROUTING from your routing config: \`gh variable set CRYSK_ROUTING --body "$(jq -c .routing ~/.crysk/config.json)"\` (~/.prhero/config.json on a machine set up before the rename; PRHERO_ROUTING on a workflow set up before the rename)`)
1786
- },
1787
- "PRH-ROUTING-INVALID": {
1788
- level: "error",
1789
- owner: "config",
1790
- what: "The routing variable is invalid: {detail}",
1791
- variants: single("Crysk cannot tell which backend and model each agent should use", [
1792
- "Edit the JSON, then set it again:",
1793
- '$ gh variable set CRYSK_ROUTING --body "$(jq -c . routing.json)"',
1794
- LEGACY_ROUTING_NOTE
1795
- ], "fix the routing JSON ({detail}), then set it again with `gh variable set CRYSK_ROUTING` (PRHERO_ROUTING on a workflow set up before the rename)")
1796
- },
1797
- "PRH-ROUTE-UNRESOLVABLE": {
1798
- level: "error",
1799
- owner: "config",
1800
- what: "Model routing for {step} has no usable route: {detail}",
1801
- variants: {
1802
- unmapped: ROUTE_UNMAPPED,
1803
- ambiguous: {
1804
- why: ROUTE_WHY,
1805
- fixes: [
1806
- "Remove the duplicate mapping for this route from CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename)."
1807
- ],
1808
- annotationFix: "remove the duplicate mapping for this route from CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename)"
1809
- },
1810
- "spend-disabled": {
1811
- why: ROUTE_WHY,
1812
- fixes: [
1813
- "Enable spend for this route in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename)."
1814
- ],
1815
- annotationFix: "enable spend for this route in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename)"
1816
- },
1817
- "multiple-opencode-providers": {
1818
- why: ROUTE_WHY,
1819
- fixes: [
1820
- "Keep one OpenCode provider per review in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename)."
1821
- ],
1822
- annotationFix: "keep one OpenCode provider per review in CRYSK_ROUTING (PRHERO_ROUTING on a workflow set up before the rename)"
1823
- },
1824
- default: ROUTE_UNMAPPED
1825
- }
1826
- },
1827
- "PRH-MODEL-UNAVAILABLE": {
2068
+ "CRYSK-MODEL-UNAVAILABLE": {
1828
2069
  level: "error",
1829
2070
  owner: "provider",
1830
2071
  what: "Provider {provider} does not serve the model configured for {step}",
@@ -1838,7 +2079,7 @@ var init_outcome = __esm(() => {
1838
2079
  provider_configuration_invalid: { ...MODEL_NOT_SERVED, owner: "config" }
1839
2080
  }
1840
2081
  },
1841
- "PRH-PROMPTSET-INVALID": {
2082
+ "CRYSK-PROMPTSET-INVALID": {
1842
2083
  level: "error",
1843
2084
  owner: "config",
1844
2085
  what: "The prompt set is invalid: {detail}",
@@ -1847,7 +2088,7 @@ var init_outcome = __esm(() => {
1847
2088
  "$ crysk review --pr {pr} --dry-run"
1848
2089
  ], "fix the agent file or `agents_dir` ({detail}), then check it with `crysk review --pr {pr} --dry-run`")
1849
2090
  },
1850
- "PRH-GOTCHAS-MISSING": {
2091
+ "CRYSK-GOTCHAS-MISSING": {
1851
2092
  level: "error",
1852
2093
  owner: "config",
1853
2094
  what: "the review instructions file (REVIEW.md or .crysk/gotchas.md) is empty or still the scaffold",
@@ -1855,13 +2096,39 @@ var init_outcome = __esm(() => {
1855
2096
  "Write real rules and facts about this repository into the file (REVIEW.md at the repository root, or .crysk/gotchas.md), delete the scaffold marker line if it is there, and commit it to the base branch (comment-triggered runs read the base branch). Or delete the file to review with the default guidance only."
1856
2097
  ], "write real rules into REVIEW.md or .crysk/gotchas.md (remove the scaffold marker line if present) and commit it to the base branch, or delete the file")
1857
2098
  },
1858
- "PRH-CONFIG-INVALID": {
2099
+ "CRYSK-CONFIG-INVALID": {
1859
2100
  level: "error",
1860
2101
  owner: "config",
1861
2102
  what: ".crysk/config.json is invalid: {detail}",
1862
- variants: single("Crysk refuses to guess repository settings", ["Fix the file, then check it:", "$ crysk review --pr {pr} --dry-run"], "fix `.crysk/config.json` ({detail}), then check it with `crysk review --pr {pr} --dry-run`")
2103
+ variants: {
2104
+ ...single("Crysk refuses to guess repository settings", ["Fix the file, then check it:", "$ crysk review --pr {pr} --dry-run"], "fix `.crysk/config.json` ({detail}), then check it with `crysk review --pr {pr} --dry-run`"),
2105
+ "models-input": {
2106
+ what: "The models input is invalid: {detail}",
2107
+ why: "Crysk refuses to guess which model each role should use",
2108
+ fixes: [
2109
+ "Fix the models per role, a JSON object from role to model list, and set the variable again:",
2110
+ '$ gh variable set CRYSK_MODELS --body "$(jq -c . models.json)"',
2111
+ `The workflow passes it as \`${MODELS_INPUT_LINE}\`.`,
2112
+ "Then re-run the workflow:",
2113
+ "$ gh run rerun {runId}"
2114
+ ],
2115
+ annotationFix: "fix the models JSON ({detail}) and set it again with `gh variable set CRYSK_MODELS`, the variable the workflow passes as `vars.CRYSK_MODELS`"
2116
+ },
2117
+ "credentials-input": {
2118
+ what: "The credentials input is invalid: {detail}",
2119
+ why: "Crysk refuses to guess which Claude credential to use",
2120
+ fixes: [
2121
+ 'Fix the Claude credential order, a JSON object such as {"claude": ["subscription", "api_key"]}, and set the variable again:',
2122
+ '$ gh variable set CRYSK_CREDENTIALS --body "$(jq -c . credentials.json)"',
2123
+ `The workflow passes it as \`${CREDENTIALS_INPUT_LINE}\`.`,
2124
+ "Then re-run the workflow:",
2125
+ "$ gh run rerun {runId}"
2126
+ ],
2127
+ annotationFix: "fix the credentials JSON ({detail}) and set it again with `gh variable set CRYSK_CREDENTIALS`, the variable the workflow passes as `vars.CRYSK_CREDENTIALS`"
2128
+ }
2129
+ }
1863
2130
  },
1864
- "PRH-TOKEN-PERMISSION": {
2131
+ "CRYSK-TOKEN-PERMISSION": {
1865
2132
  level: "error",
1866
2133
  owner: "config",
1867
2134
  what: "The workflow token lacks `{scope}: write`",
@@ -1881,13 +2148,13 @@ var init_outcome = __esm(() => {
1881
2148
  }
1882
2149
  }
1883
2150
  },
1884
- "PRH-GITHUB-TOKEN-INVALID": {
2151
+ "CRYSK-GITHUB-TOKEN-INVALID": {
1885
2152
  level: "error",
1886
2153
  owner: "config",
1887
2154
  what: "The github-token input is invalid",
1888
2155
  variants: single("every GitHub API call is rejected", [`Set \`${GITHUB_TOKEN_INPUT}\` on the action step.`], `set \`${GITHUB_TOKEN_INPUT}\` on the action step`)
1889
2156
  },
1890
- "PRH-GITHUB-UNAVAILABLE": {
2157
+ "CRYSK-GITHUB-UNAVAILABLE": {
1891
2158
  level: "error",
1892
2159
  owner: "provider",
1893
2160
  providerName: "GitHub",
@@ -1906,7 +2173,7 @@ var init_outcome = __esm(() => {
1906
2173
  default: GITHUB_SERVER
1907
2174
  }
1908
2175
  },
1909
- "PRH-PR-UNRESOLVED": {
2176
+ "CRYSK-PR-UNRESOLVED": {
1910
2177
  level: "error",
1911
2178
  owner: "config",
1912
2179
  what: "Crysk could not determine the pull request number or head",
@@ -1922,7 +2189,7 @@ var init_outcome = __esm(() => {
1922
2189
  }
1923
2190
  }
1924
2191
  },
1925
- "PRH-STATUS-WRITE-FAILED": {
2192
+ "CRYSK-STATUS-WRITE-FAILED": {
1926
2193
  level: "error",
1927
2194
  owner: "unclassified",
1928
2195
  providerName: "GitHub",
@@ -1954,7 +2221,7 @@ var init_outcome = __esm(() => {
1954
2221
  }
1955
2222
  }
1956
2223
  },
1957
- "PRH-RUNTIME-UNAVAILABLE": {
2224
+ "CRYSK-RUNTIME-UNAVAILABLE": {
1958
2225
  level: "error",
1959
2226
  owner: { action: "pr-hero", local: "config" },
1960
2227
  what: "a runtime Crysk depends on is unusable: {detail}",
@@ -1963,7 +2230,7 @@ var init_outcome = __esm(() => {
1963
2230
  why: "the action installs this runtime itself, so this is a Crysk defect",
1964
2231
  fixes: [
1965
2232
  "Report it with this run:",
1966
- '$ gh issue create -R cryskai/crysk --title "PRH-RUNTIME-UNAVAILABLE" --body "{runUrl}"'
2233
+ '$ gh issue create -R cryskai/crysk --title "CRYSK-RUNTIME-UNAVAILABLE" --body "{runUrl}"'
1967
2234
  ],
1968
2235
  annotationFix: "report it at cryskai/crysk with this run's URL"
1969
2236
  },
@@ -1971,7 +2238,7 @@ var init_outcome = __esm(() => {
1971
2238
  default: RUNTIME_LOCAL
1972
2239
  }
1973
2240
  },
1974
- "PRH-INSTALL-FAILED": {
2241
+ "CRYSK-INSTALL-FAILED": {
1975
2242
  level: "error",
1976
2243
  owner: "unclassified",
1977
2244
  what: "The {step} step failed",
@@ -1982,7 +2249,7 @@ var init_outcome = __esm(() => {
1982
2249
  "If it repeats, report it."
1983
2250
  ], "re-run only the failed jobs with `gh run rerun {runId} --failed`")
1984
2251
  },
1985
- "PRH-PROVIDER-LIMITED": {
2252
+ "CRYSK-PROVIDER-LIMITED": {
1986
2253
  level: "error",
1987
2254
  owner: "provider",
1988
2255
  what: "rate limit or quota reached",
@@ -1993,38 +2260,37 @@ var init_outcome = __esm(() => {
1993
2260
  what: "{detail} (rate limit or quota reached)"
1994
2261
  },
1995
2262
  api_key: {
1996
- what: "{detail}: the Anthropic account behind ANTHROPIC_API_KEY has no credit left or reached its spend limit",
2263
+ what: "{detail}: the Anthropic account behind the API key has no credit left or reached its spend limit",
1997
2264
  why: "the provider refuses every request until the account has credit again, so a retry would fail the same way",
1998
2265
  fixes: [
1999
- "Add credit to the Anthropic account behind ANTHROPIC_API_KEY (Claude Console \u2192 Plans & Billing), or delete the secret so the review uses CLAUDE_CODE_OAUTH_TOKEN:",
2000
- "$ gh secret delete ANTHROPIC_API_KEY",
2266
+ "Add credit to the Anthropic account behind the API key (Claude Console \u2192 Plans & Billing), or run on the subscription: set CRYSK_CLAUDE_OAUTH_TOKEN and put subscription first in `credentials.claude` (the default order).",
2001
2267
  "Then ask for a new review:",
2002
2268
  REVIEW_AGAIN,
2003
2269
  LEGACY_REVIEW_NOTE
2004
2270
  ],
2005
- annotationFix: "add credit to the Anthropic account behind ANTHROPIC_API_KEY (Claude Console \u2192 Plans & Billing), or delete the ANTHROPIC_API_KEY secret so the review uses CLAUDE_CODE_OAUTH_TOKEN"
2271
+ annotationFix: "add credit to the Anthropic account behind the API key (Claude Console \u2192 Plans & Billing), or set CRYSK_CLAUDE_OAUTH_TOKEN and put subscription first in `credentials.claude` (the default order)"
2006
2272
  },
2007
2273
  subscription: {
2008
- what: "{detail}: the Claude subscription behind CLAUDE_CODE_OAUTH_TOKEN reached its usage limit",
2274
+ what: "{detail}: the Claude subscription reached its usage limit",
2009
2275
  why: "the subscription refuses requests until its usage window resets, so an immediate retry would fail the same way",
2010
2276
  fixes: [
2011
2277
  "Re-run after the limit resets (the reset time is in the sentence above):",
2012
2278
  REVIEW_AGAIN,
2013
2279
  LEGACY_REVIEW_NOTE,
2014
- "Or set ANTHROPIC_API_KEY to bill per token:",
2015
- "$ gh secret set ANTHROPIC_API_KEY"
2280
+ "Or bill per token: set CRYSK_CLAUDE_API_KEY and put api_key first in `credentials.claude` (the default order uses the subscription while it is set):",
2281
+ "$ gh secret set CRYSK_CLAUDE_API_KEY"
2016
2282
  ],
2017
- annotationFix: "re-run after the limit resets, or set ANTHROPIC_API_KEY to bill per token"
2283
+ annotationFix: "re-run after the limit resets, or set CRYSK_CLAUDE_API_KEY and put api_key first in `credentials.claude` to bill per token"
2018
2284
  }
2019
2285
  }
2020
2286
  },
2021
- "PRH-PROVIDER-UNAVAILABLE": {
2287
+ "CRYSK-PROVIDER-UNAVAILABLE": {
2022
2288
  level: "error",
2023
2289
  owner: "provider",
2024
2290
  what: "unreachable",
2025
2291
  variants: single("the request did not complete, and the provider's outcome cannot be confirmed from here", ["Re-run the workflow:", "$ gh run rerun {runId}"], "re-run the workflow with `gh run rerun {runId}`")
2026
2292
  },
2027
- "PRH-PROVIDER-REFUSED": {
2293
+ "CRYSK-PROVIDER-REFUSED": {
2028
2294
  level: "error",
2029
2295
  owner: "provider",
2030
2296
  what: "the request was refused",
@@ -2035,13 +2301,13 @@ var init_outcome = __esm(() => {
2035
2301
  "If it repeats, report it."
2036
2302
  ], "ask for a new review once, and report it if the provider refuses again")
2037
2303
  },
2038
- "PRH-ENGINE-DEFECT": {
2304
+ "CRYSK-ENGINE-DEFECT": {
2039
2305
  level: "error",
2040
2306
  owner: "pr-hero",
2041
2307
  what: "Crysk hit an internal error ({detail}) in {step}",
2042
2308
  variants: single("this is a defect in Crysk, not in your configuration", ["Report it, with this run:", `$ ${ENGINE_DEFECT_ISSUE}`], "report it at cryskai/crysk with this run's URL")
2043
2309
  },
2044
- "PRH-HUNTERS-FAILED": {
2310
+ "CRYSK-HUNTERS-FAILED": {
2045
2311
  level: "error",
2046
2312
  owner: "unclassified",
2047
2313
  lead: "Not reviewed:",
@@ -2067,7 +2333,7 @@ var init_outcome = __esm(() => {
2067
2333
  }
2068
2334
  }
2069
2335
  },
2070
- "PRH-UNCLASSIFIED": {
2336
+ "CRYSK-UNCLASSIFIED": {
2071
2337
  level: "error",
2072
2338
  owner: "unclassified",
2073
2339
  what: "Crysk stopped at {step} and could not tell why",
@@ -2085,11 +2351,11 @@ var init_outcome = __esm(() => {
2085
2351
  }
2086
2352
  }
2087
2353
  },
2088
- "PRH-CANCELLED": {
2354
+ "CRYSK-CANCELLED": {
2089
2355
  level: "notice",
2090
2356
  owner: "unclassified",
2091
2357
  lead: "Not reviewed:",
2092
- headline: "PRH-CANCELLED: not reviewed",
2358
+ headline: "CRYSK-CANCELLED: not reviewed",
2093
2359
  what: "The review was cancelled or superseded by a newer push",
2094
2360
  variants: single("a newer run replaces this one, so this result would describe an outdated head", [
2095
2361
  "Ask for a review of the current head:",
@@ -2148,6 +2414,41 @@ var init_override = __esm(() => {
2148
2414
  OVERRIDE_STATUS_CONTEXT = STATUS_CONTEXT;
2149
2415
  });
2150
2416
 
2417
+ // src/ci/crysk-secrets.ts
2418
+ function opencodeSecretToken(providerId) {
2419
+ if (!PROVIDER_ID_RE.test(providerId))
2420
+ return;
2421
+ return providerId.toUpperCase().replace(/[.-]/g, "_");
2422
+ }
2423
+ function chooseOpenCodeSecret(providerId, names) {
2424
+ const token = opencodeSecretToken(providerId);
2425
+ if (token === undefined)
2426
+ return;
2427
+ const apiKey = `CRYSK_OPENCODE_${token}_API_KEY`;
2428
+ const oauth = `CRYSK_OPENCODE_${token}_OAUTH`;
2429
+ const hasApiKey = names.includes(apiKey);
2430
+ if (names.includes(oauth)) {
2431
+ if (providerId !== OPENCODE_OAUTH_SECRET_PROVIDER) {
2432
+ return {
2433
+ problem: `${oauth} ${UNSUPPORTED_OAUTH_TEXT}; set ${apiKey} instead`
2434
+ };
2435
+ }
2436
+ return hasApiKey ? { kind: "oauth", secret: oauth, unused: apiKey } : { kind: "oauth", secret: oauth };
2437
+ }
2438
+ return hasApiKey ? { kind: "api_key", secret: apiKey } : undefined;
2439
+ }
2440
+ var LEGACY_SECRET_REPLACEMENT, PROVIDER_ID_RE, EMPTY_OPENCODE_SLOT_NAME = "CRYSK_OPENCODE__API_KEY", EMPTY_OPENCODE_SLOT_LINE, MAX_OPENCODE_PROVIDER_SLOTS = 5, OPENCODE_OAUTH_SECRET_PROVIDER = "openai", UNSUPPORTED_OAUTH_TEXT;
2441
+ var init_crysk_secrets = __esm(() => {
2442
+ LEGACY_SECRET_REPLACEMENT = {
2443
+ CLAUDE_CODE_OAUTH_TOKEN: "CRYSK_CLAUDE_OAUTH_TOKEN",
2444
+ ANTHROPIC_API_KEY: "CRYSK_CLAUDE_API_KEY",
2445
+ OPENCODE_AUTH_JSON: "one CRYSK_OPENCODE_<PROVIDER>_API_KEY per provider (CRYSK_OPENCODE_OPENAI_OAUTH for an OpenAI subscription)"
2446
+ };
2447
+ PROVIDER_ID_RE = /^[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*$/;
2448
+ EMPTY_OPENCODE_SLOT_LINE = `${EMPTY_OPENCODE_SLOT_NAME}=`;
2449
+ UNSUPPORTED_OAUTH_TEXT = `is an OpenCode subscription record, which Crysk reads only for ${OPENCODE_OAUTH_SECRET_PROVIDER} for now`;
2450
+ });
2451
+
2151
2452
  // src/ci/trigger.ts
2152
2453
  import { randomBytes } from "crypto";
2153
2454
  import {
@@ -2186,13 +2487,18 @@ function writeRecordAtomically(dir, name, text, fs) {
2186
2487
  throw error;
2187
2488
  }
2188
2489
  }
2189
- var REVIEW_COMMAND = "/crysk review", REVIEW_FULL_COMMAND = "/crysk review --full", RECHECK_COMMAND = "/crysk recheck", OVERRIDE_COMMAND = "/crysk override", STOP_COMMAND = "/crysk stop", TRIGGER_PERMISSIONS, CLAUDE_SESSION_FILES, NODE_FS, RECORD_TEMP_SUFFIX = ".tmp", OVERRIDE_FORK_REFUSAL, OVERRIDE_UNKNOWN_FORK_REFUSAL, RECHECK_UNKNOWN_FORK_REFUSAL;
2190
- var init_trigger = __esm(() => {
2490
+ var REVIEW_COMMAND = "/crysk review", REVIEW_FULL_COMMAND = "/crysk review --full", RECHECK_COMMAND = "/crysk recheck", OVERRIDE_COMMAND = "/crysk override", STOP_COMMAND = "/crysk stop", TRIGGER_PERMISSIONS, REMOVED_INPUT_REPLACEMENT, CLAUDE_SESSION_FILES, NODE_FS, RECORD_TEMP_SUFFIX = ".tmp", OVERRIDE_FORK_REFUSAL, OVERRIDE_UNKNOWN_FORK_REFUSAL, RECHECK_UNKNOWN_FORK_REFUSAL;
2491
+ var init_trigger = __esm(async () => {
2191
2492
  init_brand();
2493
+ init_crysk_secrets();
2192
2494
  TRIGGER_PERMISSIONS = new Set(["admin", "write"]);
2495
+ REMOVED_INPUT_REPLACEMENT = {
2496
+ "claude-token": `pass ${LEGACY_SECRET_REPLACEMENT.CLAUDE_CODE_OAUTH_TOKEN} in the crysk-secrets input`,
2497
+ "anthropic-api-key": `pass ${LEGACY_SECRET_REPLACEMENT.ANTHROPIC_API_KEY} in the crysk-secrets input`,
2498
+ "opencode-auth": `pass ${LEGACY_SECRET_REPLACEMENT.OPENCODE_AUTH_JSON} in the crysk-secrets input`,
2499
+ routing: "pass the models per role in the `models` input, from `vars.CRYSK_MODELS`"
2500
+ };
2193
2501
  CLAUDE_SESSION_FILES = [
2194
- ".claude.json",
2195
- path2.join(".claude", "session.json"),
2196
2502
  path2.join(".claude", ".credentials.json")
2197
2503
  ];
2198
2504
  NODE_FS = {
@@ -2216,12 +2522,12 @@ var init_trigger = __esm(() => {
2216
2522
  });
2217
2523
 
2218
2524
  // src/ci/publish.ts
2219
- var MARKER_PREFIX, CANCELLED_STATUS_DESCRIPTION = "PRH-CANCELLED: not reviewed \u2014 /pr-hero review reviews this head", SETTLED_STATES;
2220
- var init_publish = __esm(() => {
2525
+ var MARKER_PREFIX, CANCELLED_STATUS_DESCRIPTION = "CRYSK-CANCELLED: not reviewed \u2014 /crysk review reviews this head", SETTLED_STATES;
2526
+ var init_publish = __esm(async () => {
2221
2527
  init_brand();
2222
2528
  init_outcome();
2223
2529
  init_override();
2224
- init_trigger();
2530
+ await init_trigger();
2225
2531
  MARKER_PREFIX = OUTCOME_MARKER_PREFIX.trimEnd();
2226
2532
  SETTLED_STATES = new Set([
2227
2533
  "success",
@@ -2313,7 +2619,7 @@ function redactPrivateKeys(text) {
2313
2619
  PEM_BODY.test(text);
2314
2620
  to = PEM_BODY.lastIndex;
2315
2621
  }
2316
- out += text.slice(from, begin.index) + REDACTED2;
2622
+ out += text.slice(from, begin.index) + REDACTED3;
2317
2623
  from = to;
2318
2624
  PEM_BEGIN.lastIndex = to;
2319
2625
  }
@@ -2322,11 +2628,11 @@ function redactPrivateKeys(text) {
2322
2628
  function redactSecrets(text) {
2323
2629
  let out = redactPrivateKeys(text);
2324
2630
  for (const shape of SECRET_SHAPES)
2325
- out = out.replace(shape, REDACTED2);
2326
- return out.replace(URL_CREDENTIALS, `$1${REDACTED2}@`).replace(SECRET_ASSIGNMENT, (match, quote, name, separator, raw) => isSecretValue(name, separator, raw) ? `${quote}${name}${quote}${separator}${REDACTED2}` : match);
2631
+ out = out.replace(shape, REDACTED3);
2632
+ return out.replace(URL_CREDENTIALS2, `$1${REDACTED3}@`).replace(SECRET_ASSIGNMENT, (match, quote, name, separator, raw) => isSecretValue(name, separator, raw) ? `${quote}${name}${quote}${separator}${REDACTED3}` : match);
2327
2633
  }
2328
2634
  function wasRedacted(text) {
2329
- return text.includes(REDACTED2);
2635
+ return text.includes(REDACTED3);
2330
2636
  }
2331
2637
  function defuseMarkup(text) {
2332
2638
  return text.replace(/(?<![A-Za-z0-9/])@(?!\u200b)/g, `@${ZERO_WIDTH_SPACE}`).replace(/&(?=#|commat)/gi, `&${ZERO_WIDTH_SPACE}`).replaceAll("![", `!${ZERO_WIDTH_SPACE}[`).replace(/<(?=[a-zA-Z/!?])/g, `<${ZERO_WIDTH_SPACE}`).replaceAll("-->", `--${ZERO_WIDTH_SPACE}>`);
@@ -2334,7 +2640,7 @@ function defuseMarkup(text) {
2334
2640
  function publishedText(text) {
2335
2641
  return defuseMarkup(redactSecrets(text));
2336
2642
  }
2337
- var REDACTED2 = "[REDACTED]", ZERO_WIDTH_SPACE = "\u200B", SECRET_SHAPES, URL_CREDENTIALS, SECRET_ASSIGNMENT, PEM_BEGIN, PEM_END, PEM_BODY;
2643
+ var REDACTED3 = "[REDACTED]", ZERO_WIDTH_SPACE = "\u200B", SECRET_SHAPES, URL_CREDENTIALS2, SECRET_ASSIGNMENT, PEM_BEGIN, PEM_END, PEM_BODY;
2338
2644
  var init_published_text = __esm(() => {
2339
2645
  SECRET_SHAPES = [
2340
2646
  /(?<![A-Za-z0-9])gh[pousr]_[A-Za-z0-9_]{20,}/g,
@@ -2350,7 +2656,7 @@ var init_published_text = __esm(() => {
2350
2656
  /(?<![A-Za-z0-9])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}/g,
2351
2657
  /(?<![A-Za-z0-9])Bearer\s+(?=[A-Za-z0-9._~+/=-]{0,512}\d)[A-Za-z0-9._~+/=-]{20,}/gi
2352
2658
  ];
2353
- URL_CREDENTIALS = /(?<![A-Za-z0-9+.-])([a-z][a-z0-9+.-]{0,30}:\/\/)(?:[^\s/?#${<]{0,256}:[^\s/?#${<]{1,256}|[^\s/?#${<:@]{20,256})@/gi;
2659
+ URL_CREDENTIALS2 = /(?<![A-Za-z0-9+.-])([a-z][a-z0-9+.-]{0,30}:\/\/)(?:[^\s/?#${<]{0,256}:[^\s/?#${<]{1,256}|[^\s/?#${<:@]{20,256})@/gi;
2354
2660
  SECRET_ASSIGNMENT = /(?<![A-Za-z0-9_-])(["']?)((?:[A-Za-z0-9_-]{0,40}[_-])?(?:password|passwd|secret|token|api[_-]?key|private[_-]?key|credentials?)(?:[_-][A-Za-z0-9_-]{0,40})?)\1(\s*[=:](?![=:])\s*)("[^"\n]{1,256}"|'[^'\n]{1,256}'|[^\s"',;]{1,256})/gi;
2355
2661
  PEM_BEGIN = /-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----/g;
2356
2662
  PEM_END = /-----END [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----/g;
@@ -2486,10 +2792,6 @@ var init_triage = __esm(() => {
2486
2792
  var consolidate_default = "./consolidate-ac0mnfyj.md";
2487
2793
  var init_consolidate = () => {};
2488
2794
 
2489
- // prompts/default/deep-review-lifecycle.md
2490
- var deep_review_lifecycle_default = "./deep-review-lifecycle-m698ybjp.md";
2491
- var init_deep_review_lifecycle = () => {};
2492
-
2493
2795
  // prompts/default/deep-review-logic.md
2494
2796
  var deep_review_logic_default = "./deep-review-logic-a6b1gczf.md";
2495
2797
  var init_deep_review_logic = () => {};
@@ -2523,7 +2825,7 @@ var summarizer_default = "./summarizer-zca44nxa.md";
2523
2825
  var init_summarizer = () => {};
2524
2826
 
2525
2827
  // skills/crysk/SKILL.md
2526
- var SKILL_default = "./SKILL-12as0f3q.md";
2828
+ var SKILL_default = "./SKILL-xpf6kmdw.md";
2527
2829
  var init_SKILL = () => {};
2528
2830
 
2529
2831
  // skills/crysk-ci-setup/assets/admission-config.example.json
@@ -2531,19 +2833,19 @@ var admission_config_example_default = "./admission-config.example-a9vqmmad.json
2531
2833
  var init_admission_config_example = () => {};
2532
2834
 
2533
2835
  // skills/crysk-ci-setup/assets/workflow.yml
2534
- var workflow_default = "./workflow-w1g9szna.yml";
2836
+ var workflow_default = "./workflow-4pkyck01.yml";
2535
2837
  var init_workflow = () => {};
2536
2838
 
2537
2839
  // skills/crysk-ci-setup/references/ci-admission.md
2538
- var ci_admission_default = "./ci-admission-t0f5qwth.md";
2840
+ var ci_admission_default = "./ci-admission-0ken6ehx.md";
2539
2841
  var init_ci_admission = () => {};
2540
2842
 
2541
2843
  // skills/crysk-ci-setup/references/opencode-ci.md
2542
- var opencode_ci_default = "./opencode-ci-7b0be64p.md";
2844
+ var opencode_ci_default = "./opencode-ci-ac5zksdn.md";
2543
2845
  var init_opencode_ci = () => {};
2544
2846
 
2545
2847
  // skills/crysk-ci-setup/SKILL.md
2546
- var SKILL_default2 = "./SKILL-dsnffnfp.md";
2848
+ var SKILL_default2 = "./SKILL-k4k0zn1w.md";
2547
2849
  var init_SKILL2 = () => {};
2548
2850
 
2549
2851
  // skills/crysk-loop/adjudicator.md
@@ -2551,7 +2853,7 @@ var adjudicator_default = "./adjudicator-dtg2axnh.md";
2551
2853
  var init_adjudicator = () => {};
2552
2854
 
2553
2855
  // skills/crysk-loop/SKILL.md
2554
- var SKILL_default3 = "./SKILL-vws0aqb8.md";
2856
+ var SKILL_default3 = "./SKILL-vhb4c3vv.md";
2555
2857
  var init_SKILL3 = () => {};
2556
2858
 
2557
2859
  // skills/crysk-pr/SKILL.md
@@ -2562,7 +2864,6 @@ var init_SKILL4 = () => {};
2562
2864
  var BUNDLED_AGENT_FILES, CONSOLIDATE_PROMPT_PATH, MATERIALITY_PROMPT_PATH, SCOUT_PROMPT_PATH, SUMMARIZER_PROMPT_PATH, TRIAGE_SKILL_FILES, CI_SETUP_SKILL_FILES, PR_SKILL_FILES, GENERAL_SKILL_FILES;
2563
2865
  var init_asset_manifest = __esm(() => {
2564
2866
  init_consolidate();
2565
- init_deep_review_lifecycle();
2566
2867
  init_deep_review_logic();
2567
2868
  init_deep_review_parity();
2568
2869
  init_deep_review_reliability();
@@ -2581,7 +2882,6 @@ var init_asset_manifest = __esm(() => {
2581
2882
  init_SKILL3();
2582
2883
  init_SKILL4();
2583
2884
  BUNDLED_AGENT_FILES = {
2584
- "deep-review-lifecycle.md": deep_review_lifecycle_default,
2585
2885
  "deep-review-logic.md": deep_review_logic_default,
2586
2886
  "deep-review-parity.md": deep_review_parity_default,
2587
2887
  "deep-review-reliability.md": deep_review_reliability_default,
@@ -2637,7 +2937,7 @@ function resolveVersion() {
2637
2937
  }
2638
2938
  }
2639
2939
  } catch {}
2640
- return "0.4.0";
2940
+ return "0.5.0";
2641
2941
  }
2642
2942
  function resolveEngineAssets() {
2643
2943
  const mode = detectAssetMode();
@@ -4337,12 +4637,12 @@ function formatIntervalSeconds(seconds) {
4337
4637
  return seconds % 60 === 0 ? `${seconds / 60} min` : `${seconds}s`;
4338
4638
  }
4339
4639
  var DEFAULT_DAILY_CAP = 5, HHMM, MARKER_HEAD_RE, MAX_WATCH_ATTEMPTS = 2, SETTLE_SKIP_REASONS, WATCH_LAUNCHD_LABEL = "io.crysk.watch";
4340
- var init_preflight = __esm(() => {
4341
- init_preflight3();
4640
+ var init_preflight = __esm(async () => {
4342
4641
  init_size_gate();
4343
4642
  init_brand();
4344
4643
  init_errors();
4345
4644
  init_home_preflight();
4645
+ await init_preflight3();
4346
4646
  HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
4347
4647
  MARKER_HEAD_RE = new RegExp(`^<!-- ${MARKER_BRAND_PATTERN}-report head=([0-9a-f]{40})( coverage=partial)? -->`);
4348
4648
  SETTLE_SKIP_REASONS = new Set([
@@ -4509,11 +4809,11 @@ async function stampWorktree(registryPath, pr, isoTimestamp) {
4509
4809
  }
4510
4810
  }
4511
4811
  var PID_LOCK_ATTEMPTS = 3;
4512
- var init_home = __esm(() => {
4812
+ var init_home = __esm(async () => {
4513
4813
  init_git();
4514
- init_preflight();
4515
4814
  init_errors();
4516
4815
  init_home_preflight();
4816
+ await init_preflight();
4517
4817
  });
4518
4818
 
4519
4819
  // src/review/preflight.ts
@@ -5257,10 +5557,10 @@ async function createRunDir(options, repoRoot, headSha) {
5257
5557
  const explicit = path11.resolve(options.out);
5258
5558
  assertOutsideRepo(explicit, repoRoot);
5259
5559
  await mkdir2(explicit, { recursive: true });
5260
- await Promise.resolve().then(() => init_home());
5560
+ await init_home();
5261
5561
  return { runDir: explicit, repoId: await tryOriginRepoId(repoRoot) };
5262
5562
  }
5263
- await Promise.resolve().then(() => init_home());
5563
+ await init_home();
5264
5564
  const repoHome = await resolveRepoHome({
5265
5565
  home: os.homedir(),
5266
5566
  operatorRoot: repoRoot,
@@ -5292,7 +5592,7 @@ function agentsDirProblems(specFiles, presentFiles) {
5292
5592
  }
5293
5593
  for (const file of presentFiles) {
5294
5594
  if (!named.has(file)) {
5295
- problems.push(`the dir has "${file}" but no agent in the spec references it (it would never run)`);
5595
+ problems.push(`the dir has "${file}" but no agent in the spec references it (it would never run)${RETIRED_AGENT_HINTS[file] ?? ""}`);
5296
5596
  }
5297
5597
  }
5298
5598
  return problems.sort();
@@ -5373,7 +5673,6 @@ function localReviewSpec(env = process.env) {
5373
5673
  role: "hunter"
5374
5674
  },
5375
5675
  { key: "resilience", file: "deep-review-resilience.md", role: "hunter" },
5376
- { key: "lifecycle", file: "deep-review-lifecycle.md", role: "hunter" },
5377
5676
  { key: "logic", file: "deep-review-logic.md", role: "hunter" },
5378
5677
  {
5379
5678
  key: "parity",
@@ -5386,11 +5685,11 @@ function localReviewSpec(env = process.env) {
5386
5685
  ]
5387
5686
  };
5388
5687
  }
5389
- function parseLocalConfig(raw, label = REPO_CONFIG_LABEL) {
5390
- return withUsageClass({ kind: "config-parse", source: "repo-config" }, () => parseConfigLayer(raw, label, LOCAL_CONFIG_KEYS, parseRoutingConfig, true));
5688
+ function parseLocalConfig(raw, label = REPO_CONFIG_LABEL, warnings) {
5689
+ return withUsageClass({ kind: "config-parse", source: "repo-config" }, () => parseConfigLayer(raw, label, LOCAL_CONFIG_KEYS, true, warnings));
5391
5690
  }
5392
- function parseGlobalConfig(raw, label = GLOBAL_CONFIG_LABEL) {
5393
- return parseConfigLayer(raw, label, GLOBAL_CONFIG_KEYS, parseRoutingValue, false);
5691
+ function parseGlobalConfig(raw, label = GLOBAL_CONFIG_LABEL, warnings) {
5692
+ return parseConfigLayer(raw, label, GLOBAL_CONFIG_KEYS, false, warnings);
5394
5693
  }
5395
5694
  function given(value) {
5396
5695
  return value !== undefined && value !== null;
@@ -5403,7 +5702,7 @@ function parseOptionalBoolean(value, key, file) {
5403
5702
  }
5404
5703
  return value;
5405
5704
  }
5406
- function parseConfigLayer(raw, file, admitted, parseRouting, isRepoFile) {
5705
+ function parseConfigLayer(raw, file, admitted, isRepoFile, warnings) {
5407
5706
  let parsed;
5408
5707
  try {
5409
5708
  parsed = JSON.parse(raw);
@@ -5415,8 +5714,11 @@ function parseConfigLayer(raw, file, admitted, parseRouting, isRepoFile) {
5415
5714
  }
5416
5715
  const config = parsed;
5417
5716
  for (const key of Object.keys(config)) {
5717
+ if (key === "routing") {
5718
+ throw new CliUsageError(`${file}: ${REMOVED_ROUTING_MESSAGE}`);
5719
+ }
5418
5720
  if (!KNOWN_CONFIG_KEYS.has(key)) {
5419
- throw new CliUsageError(`${file} unknown key: ${redactDiagnostic(key)}`);
5721
+ throw new CliUsageError(`${file} unknown key: ${redactConfigValue(key)}`);
5420
5722
  }
5421
5723
  if (!admitted.has(key)) {
5422
5724
  if (isRepoFile) {
@@ -5448,8 +5750,26 @@ function parseConfigLayer(raw, file, admitted, parseRouting, isRepoFile) {
5448
5750
  throw new CliUsageError(`suspicion_priors[${i}].reason required`);
5449
5751
  }
5450
5752
  }
5451
- const summary = parseSummaryConfig(config.summary, file);
5452
- const routing = parseRouting(config.routing, file);
5753
+ const summaryParse = parseSummaryConfig(config.summary, file);
5754
+ const summary = summaryParse?.summary;
5755
+ let models = parseModels(config.models, file);
5756
+ if (summaryParse?.initModel === true) {
5757
+ if (isRepoFile) {
5758
+ warnings?.push(`${file}: summary.model is gone and is ignored here: the summary model is set per person, under models.summary in your person config (~/.crysk/config.json). Delete summary.model from this file.`);
5759
+ } else if (models?.summary !== undefined) {
5760
+ warnings?.push(`${file}: summary.model is gone and models.summary already sets the summary model. Delete summary.model.`);
5761
+ } else {
5762
+ models = { ...models, summary: [...SUMMARY_MODEL_CONVERTED] };
5763
+ warnings?.push(`${file}: summary.model is gone; "haiku" is read as ${SUMMARY_MODEL_EXAMPLE}. Write that instead of summary.model.`);
5764
+ }
5765
+ }
5766
+ if (models?.judge !== undefined) {
5767
+ const { model, dropped } = judgeModelChoice(models);
5768
+ if (dropped.length > 0) {
5769
+ warnings?.push(`${file}: models.judge skips ${dropped.join(", ")}: the materiality judge runs only on claude:sonnet-latest or claude:opus-latest${model === undefined ? ", so it stands down" : ""}.`);
5770
+ }
5771
+ }
5772
+ const credentials = parseCredentialsConfig(config.credentials, file);
5453
5773
  const maxVerificationSteps = parseNonNegativeInteger(config.max_verification_steps, "max_verification_steps", file);
5454
5774
  const maxConcurrentSteps = parsePositiveInteger(config.max_concurrent_steps, "max_concurrent_steps", file);
5455
5775
  const maxChangedLines = parseNonNegativeInteger(config.max_changed_lines, "max_changed_lines", file);
@@ -5475,7 +5795,8 @@ function parseConfigLayer(raw, file, admitted, parseRouting, isRepoFile) {
5475
5795
  ...optionalString(config, "agents_dir", file),
5476
5796
  ...optionalString(config, "default_base", file),
5477
5797
  ...summary === undefined ? {} : { summary },
5478
- ...routing === undefined ? {} : { routing },
5798
+ ...models === undefined ? {} : { models },
5799
+ ...credentials === undefined ? {} : { credentials },
5479
5800
  ...maxVerificationSteps === undefined ? {} : { max_verification_steps: maxVerificationSteps },
5480
5801
  ...maxConcurrentSteps === undefined ? {} : { max_concurrent_steps: maxConcurrentSteps },
5481
5802
  ...maxChangedLines === undefined ? {} : { max_changed_lines: maxChangedLines },
@@ -5494,118 +5815,47 @@ function parseConfigLayer(raw, file, admitted, parseRouting, isRepoFile) {
5494
5815
  ...ciAdmissionObserveOnly === undefined ? {} : { ci_admission_observe_only: ciAdmissionObserveOnly }
5495
5816
  };
5496
5817
  }
5497
- function checkNoCredentials(obj, path, file) {
5498
- for (const key of Object.keys(obj)) {
5499
- const lower = key.toLowerCase();
5500
- if (CREDENTIAL_KEY_NAMES.has(lower) || lower.includes("secret") || lower.includes("password") || lower.includes("token") || lower.includes("apikey") || lower.includes("api_key")) {
5501
- throw new CliUsageError(`${file} ${path}: credentials are not permitted in routing config`);
5502
- }
5503
- const val = obj[key];
5504
- if (typeof val === "string") {
5505
- const redacted = redactDiagnostic(val);
5506
- if (redacted !== val) {
5507
- throw new CliUsageError(`${file} ${path}: credentials are not permitted in routing config`);
5508
- }
5509
- }
5510
- }
5511
- }
5512
- function parseRouteMapping(m, path, file) {
5513
- if (typeof m !== "object" || m === null || Array.isArray(m)) {
5514
- throw new CliUsageError(`${file} ${path} must be an object`);
5515
- }
5516
- const mapping = m;
5517
- checkNoCredentials(mapping, path, file);
5518
- for (const key of Object.keys(mapping)) {
5519
- if (!KNOWN_ROUTE_MAPPING_KEYS.has(key)) {
5520
- throw new CliUsageError(`${file} ${path} unknown key: ${redactDiagnostic(key)}`);
5521
- }
5522
- }
5523
- if (mapping.logical !== undefined) {
5524
- if (typeof mapping.logical !== "string" || mapping.logical.trim().length === 0) {
5525
- throw new CliUsageError(`${file} ${path}.logical must be a non-empty string`);
5526
- }
5527
- }
5528
- if (typeof mapping.backend !== "string" || mapping.backend !== "claude-code" && mapping.backend !== "opencode") {
5529
- throw new CliUsageError(`${file} ${path}.backend must be claude-code|opencode`);
5530
- }
5531
- if (typeof mapping.provider !== "string" || mapping.provider.trim().length === 0) {
5532
- throw new CliUsageError(`${file} ${path}.provider must be a non-empty string`);
5533
- }
5534
- if (mapping.gateway !== undefined) {
5535
- if (typeof mapping.gateway !== "string" || mapping.gateway !== "configured" && mapping.gateway !== "direct" && mapping.gateway !== "openrouter") {
5536
- throw new CliUsageError(`${file} ${path}.gateway must be configured|direct|openrouter`);
5818
+ function parseModels(value, file) {
5819
+ if (value === undefined)
5820
+ return;
5821
+ try {
5822
+ return parseModelsConfig(value);
5823
+ } catch (error) {
5824
+ if (error instanceof ModelNameError) {
5825
+ throw new CliUsageError(`${file} ${error.message}`);
5537
5826
  }
5827
+ throw error;
5538
5828
  }
5539
- if (mapping.modelFamily !== undefined && typeof mapping.modelFamily !== "string") {
5540
- throw new CliUsageError(`${file} ${path}.modelFamily must be a string`);
5541
- }
5542
- if (mapping.modelSnapshot !== undefined && typeof mapping.modelSnapshot !== "string") {
5543
- throw new CliUsageError(`${file} ${path}.modelSnapshot must be a string`);
5544
- }
5545
- if (mapping.modelVariant !== undefined && typeof mapping.modelVariant !== "string") {
5546
- throw new CliUsageError(`${file} ${path}.modelVariant must be a string`);
5547
- }
5548
- if (mapping.disabled !== undefined && typeof mapping.disabled !== "boolean") {
5549
- throw new CliUsageError(`${file} ${path}.disabled must be a boolean`);
5550
- }
5551
- if (mapping.allowSpend !== undefined && typeof mapping.allowSpend !== "boolean") {
5552
- throw new CliUsageError(`${file} ${path}.allowSpend must be a boolean`);
5553
- }
5554
- return {
5555
- ...mapping.logical ? { logical: mapping.logical } : {},
5556
- backend: mapping.backend,
5557
- provider: mapping.provider,
5558
- ...mapping.gateway ? { gateway: mapping.gateway } : {},
5559
- ...mapping.modelFamily ? { modelFamily: mapping.modelFamily } : {},
5560
- ...mapping.modelSnapshot ? { modelSnapshot: mapping.modelSnapshot } : {},
5561
- ...mapping.modelVariant ? { modelVariant: mapping.modelVariant } : {},
5562
- ...mapping.disabled !== undefined ? { disabled: mapping.disabled } : {},
5563
- ...mapping.allowSpend !== undefined ? { allowSpend: mapping.allowSpend } : {}
5564
- };
5565
- }
5566
- function parseRoutingConfig(value, file) {
5567
- return withUsageClass({ kind: "config-parse", source: "routing" }, () => parseRoutingValue(value, file));
5568
5829
  }
5569
- function parseRoutingValue(value, file) {
5830
+ function parseCredentialsConfig(value, file) {
5570
5831
  if (value === undefined)
5571
5832
  return;
5572
5833
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
5573
- throw new CliUsageError(`${file} routing must be an object`);
5574
- }
5575
- const routing = value;
5576
- checkNoCredentials(routing, "routing", file);
5577
- for (const key of Object.keys(routing)) {
5578
- if (key !== "mappings" && key !== "default" && key !== "disabled") {
5579
- throw new CliUsageError(`${file} routing unknown key: ${redactDiagnostic(key)}`);
5580
- }
5581
- }
5582
- let mappings;
5583
- if (routing.mappings !== undefined) {
5584
- if (Array.isArray(routing.mappings)) {
5585
- mappings = routing.mappings.map((m, i) => parseRouteMapping(m, `routing.mappings[${i}]`, file));
5586
- } else if (typeof routing.mappings === "object" && routing.mappings !== null) {
5587
- const rec = routing.mappings;
5588
- const result = {};
5589
- for (const [k, v] of Object.entries(rec)) {
5590
- result[k] = parseRouteMapping(v, `routing.mappings.${k}`, file);
5591
- }
5592
- mappings = result;
5593
- } else {
5594
- throw new CliUsageError(`${file} routing.mappings must be an array or object`);
5834
+ throw new CliUsageError(`${file} credentials must be an object, e.g. ${CREDENTIALS_EXAMPLE}`);
5835
+ }
5836
+ const record = value;
5837
+ for (const key of Object.keys(record)) {
5838
+ if (key !== "claude") {
5839
+ throw new CliUsageError(`${file} credentials has an unknown key "${redactConfigValue(key)}": only claude is supported, e.g. ${CREDENTIALS_EXAMPLE}`);
5595
5840
  }
5596
5841
  }
5597
- let def;
5598
- if (routing.default !== undefined) {
5599
- def = parseRouteMapping(routing.default, "routing.default", file);
5842
+ if (record.claude === undefined)
5843
+ return {};
5844
+ const list = record.claude;
5845
+ if (!Array.isArray(list) || list.length === 0) {
5846
+ throw new CliUsageError(`${file} credentials.claude must list subscription, api_key or both, in the order to try them`);
5600
5847
  }
5601
- if (routing.disabled !== undefined && typeof routing.disabled !== "boolean") {
5602
- throw new CliUsageError(`${file} routing.disabled must be a boolean`);
5848
+ const seen = new Set;
5849
+ for (const [i, entry] of list.entries()) {
5850
+ if (typeof entry !== "string" || !CLAUDE_CREDENTIAL_KINDS.includes(entry)) {
5851
+ throw new CliUsageError(`${file} credentials.claude[${i}] must be "subscription" or "api_key"`);
5852
+ }
5853
+ if (seen.has(entry)) {
5854
+ throw new CliUsageError(`${file} credentials.claude lists "${entry}" twice`);
5855
+ }
5856
+ seen.add(entry);
5603
5857
  }
5604
- return {
5605
- ...mappings ? { mappings } : {},
5606
- ...def ? { default: def } : {},
5607
- ...routing.disabled !== undefined ? { disabled: routing.disabled } : {}
5608
- };
5858
+ return { claude: list };
5609
5859
  }
5610
5860
  function parseSummaryConfig(value, file) {
5611
5861
  if (value === undefined)
@@ -5622,12 +5872,12 @@ function parseSummaryConfig(value, file) {
5622
5872
  if (config.enabled !== undefined && typeof config.enabled !== "boolean") {
5623
5873
  throw new CliUsageError(`${file} summary.enabled must be a boolean`);
5624
5874
  }
5625
- if (config.model !== undefined && (typeof config.model !== "string" || config.model.trim().length === 0)) {
5626
- throw new CliUsageError(`${file} summary.model must be a non-empty string`);
5875
+ if (config.model !== undefined && config.model !== SUMMARY_MODEL_INIT_VALUE) {
5876
+ throw new CliUsageError(`${file} summary.model is gone: set the summary model per person, under models in your person config, e.g. ${SUMMARY_MODEL_EXAMPLE}`);
5627
5877
  }
5628
5878
  return {
5629
- ...config.enabled === undefined ? {} : { enabled: config.enabled },
5630
- ...config.model === undefined ? {} : { model: config.model }
5879
+ summary: config.enabled === undefined ? {} : { enabled: config.enabled },
5880
+ initModel: config.model !== undefined
5631
5881
  };
5632
5882
  }
5633
5883
  function parseNonNegativeInteger(value, key, file) {
@@ -5683,7 +5933,7 @@ function resolveMaxConcurrentSteps(config) {
5683
5933
  return config.max_concurrent_steps;
5684
5934
  }
5685
5935
  function resolveSummary(options, config) {
5686
- const model = options.model ?? config.summary?.model;
5936
+ const model = options.model;
5687
5937
  return {
5688
5938
  enabled: options.summary ?? config.summary?.enabled ?? true,
5689
5939
  ...model === undefined ? {} : { model }
@@ -5731,7 +5981,6 @@ function mergeConfig(global, repo) {
5731
5981
  const triggers = foldKey(layers, CONFIG_DIRECTION.parity_trigger_paths, (layer) => layer.parity_trigger_paths);
5732
5982
  const priors = foldKey(layers, CONFIG_DIRECTION.suspicion_priors, (layer) => layer.suspicion_priors);
5733
5983
  const summaryEnabled = foldKey(layers, SUMMARY_DIRECTION.enabled, (layer) => layer.summary?.enabled, (a, b) => a && b);
5734
- const summaryModel = foldKey(layers, SUMMARY_DIRECTION.model, (layer) => layer.summary?.model);
5735
5984
  const maxSteps = foldKey(layers, CONFIG_DIRECTION.max_verification_steps, (layer) => layer.max_verification_steps, Math.min);
5736
5985
  const maxConcurrentSteps = foldKey(layers, CONFIG_DIRECTION.max_concurrent_steps, (layer) => layer.max_concurrent_steps, Math.min);
5737
5986
  const narrowSizeLimit = (a, b) => {
@@ -5747,7 +5996,8 @@ function mergeConfig(global, repo) {
5747
5996
  const materialityGate = foldKey(layers, CONFIG_DIRECTION.materiality_gate, (layer) => layer.materiality_gate, (a, b) => a && b);
5748
5997
  const post = foldKey(layers, CONFIG_DIRECTION.post, (layer) => layer.post, (a, b) => a && b);
5749
5998
  const postMinSeverity = foldKey(layers, CONFIG_DIRECTION.post_min_severity, (layer) => layer.post_min_severity);
5750
- const routing = foldKey(layers, CONFIG_DIRECTION.routing, (layer) => layer.routing);
5999
+ const models = foldKey(layers, CONFIG_DIRECTION.models, (layer) => layer.models);
6000
+ const credentials = foldKey(layers, CONFIG_DIRECTION.credentials, (layer) => layer.credentials);
5751
6001
  const ciReviewPolicy = foldKey(layers, CONFIG_DIRECTION.ci_review_policy, (layer) => layer.ci_review_policy);
5752
6002
  const ciMaxAttempts = foldKey(layers, CONFIG_DIRECTION.ci_max_attempts, (layer) => layer.ci_max_attempts);
5753
6003
  const ciMaxReviews = foldKey(layers, CONFIG_DIRECTION.ci_max_reviews, (layer) => layer.ci_max_reviews);
@@ -5757,16 +6007,16 @@ function mergeConfig(global, repo) {
5757
6007
  const ciTrustedActors = foldKey(layers, CONFIG_DIRECTION.ci_trusted_actors, (layer) => layer.ci_trusted_actors, (a, b) => [...a ?? [], ...b ?? []]);
5758
6008
  const ciAdmissionObserveOnly = foldKey(layers, CONFIG_DIRECTION.ci_admission_observe_only, (layer) => layer.ci_admission_observe_only);
5759
6009
  const summary = {
5760
- ...summaryEnabled.value === undefined ? {} : { enabled: summaryEnabled.value },
5761
- ...summaryModel.value === undefined ? {} : { model: summaryModel.value }
6010
+ ...summaryEnabled.value === undefined ? {} : { enabled: summaryEnabled.value }
5762
6011
  };
5763
6012
  const effective = {
5764
6013
  parity_trigger_paths: triggers.value ?? [],
5765
6014
  suspicion_priors: priors.value ?? [],
5766
6015
  ...agentsDir.value === undefined ? {} : { agents_dir: agentsDir.value },
5767
6016
  ...defaultBase.value === undefined ? {} : { default_base: defaultBase.value },
5768
- ...summaryEnabled.value === undefined && summaryModel.value === undefined ? {} : { summary },
5769
- ...routing.value === undefined ? {} : { routing: routing.value },
6017
+ ...summaryEnabled.value === undefined ? {} : { summary },
6018
+ ...models.value === undefined ? {} : { models: models.value },
6019
+ ...credentials.value === undefined ? {} : { credentials: credentials.value },
5770
6020
  ...maxSteps.value === undefined ? {} : { max_verification_steps: maxSteps.value },
5771
6021
  ...maxConcurrentSteps.value === undefined ? {} : { max_concurrent_steps: maxConcurrentSteps.value },
5772
6022
  ...maxLines.value === undefined ? {} : { max_changed_lines: maxLines.value },
@@ -5789,8 +6039,9 @@ function mergeConfig(global, repo) {
5789
6039
  default_base: defaultBase.source,
5790
6040
  parity_trigger_paths: triggers.source,
5791
6041
  suspicion_priors: priors.source,
5792
- summary: { enabled: summaryEnabled.source, model: summaryModel.source },
5793
- routing: routing.source,
6042
+ summary: { enabled: summaryEnabled.source },
6043
+ models: models.source,
6044
+ credentials: credentials.source,
5794
6045
  max_verification_steps: maxSteps.source,
5795
6046
  max_concurrent_steps: maxConcurrentSteps.source,
5796
6047
  max_changed_lines: maxLines.source,
@@ -5822,23 +6073,19 @@ function optionalString(config, key, file) {
5822
6073
  function initTemplateOmissions(input) {
5823
6074
  const agentsDir = input.agentsDir === undefined || input.global?.agents_dir !== undefined && input.agentsDirFromFlag !== true;
5824
6075
  const summaryEnabled = input.global?.summary?.enabled !== undefined;
5825
- const summaryModel = input.global?.summary?.model !== undefined;
5826
6076
  return {
5827
6077
  agentsDir,
5828
6078
  summaryEnabled,
5829
- summaryModel,
5830
6079
  keys: [
5831
6080
  ...agentsDir ? ["agents_dir"] : [],
5832
- ...summaryEnabled ? ["summary.enabled"] : [],
5833
- ...summaryModel ? ["summary.model"] : []
6081
+ ...summaryEnabled ? ["summary.enabled"] : []
5834
6082
  ]
5835
6083
  };
5836
6084
  }
5837
6085
  function initConfigTemplate(input) {
5838
6086
  const omit = initTemplateOmissions(input);
5839
6087
  const summary = {
5840
- ...omit.summaryEnabled ? {} : { enabled: true },
5841
- ...omit.summaryModel ? {} : { model: DEFAULT_SUMMARY_MODEL }
6088
+ ...omit.summaryEnabled ? {} : { enabled: true }
5842
6089
  };
5843
6090
  return `${JSON.stringify({
5844
6091
  ...omit.agentsDir ? {} : { agents_dir: input.agentsDir },
@@ -5964,9 +6211,11 @@ function gotchasErrorMessage(gotchasPath, reason, present) {
5964
6211
  ].join(`
5965
6212
  `);
5966
6213
  }
5967
- var DEFAULT_HOP_BUDGET = 12, DEFAULT_WATCH_INTERVAL_MIN = 15, DEFAULT_GC_INTERVAL_MIN = 360, DEFAULT_HEAD_REF = "HEAD", DEFAULT_SUMMARY_MODEL = "haiku", HELP_TEXT, VALUE_FLAGS, BUNDLED_AGENTS_DIR_LABEL = "bundled default (from engine)", AGENT_FILE_PATTERNS, CONFIG_DIRECTION, SUMMARY_DIRECTION, EMPTY_LOCAL_CONFIG, KNOWN_CONFIG_KEYS, LOCAL_CONFIG_KEYS, GLOBAL_CONFIG_KEYS, REPO_CONFIG_LABEL = ".crysk/config.json", GLOBAL_CONFIG_LABEL = "~/.crysk/config.json", CREDENTIAL_KEY_NAMES, KNOWN_ROUTE_MAPPING_KEYS, DEFAULT_MAX_VERIFICATION_STEPS = 8, GOTCHAS_PLACEHOLDER_MARKER = "human-attention-required", GOTCHAS_TEMPLATE, REVIEW_MD_TEMPLATE, SETUP_GOTCHAS_FALLBACK, RETIRED_SCAFFOLD_LINES, SCAFFOLD_BODY_LINES, NO_REVIEW_INSTRUCTIONS = "This repository provides no review instructions (no REVIEW.md or gotchas file).";
6214
+ var DEFAULT_HOP_BUDGET = 12, DEFAULT_WATCH_INTERVAL_MIN = 15, DEFAULT_GC_INTERVAL_MIN = 360, DEFAULT_HEAD_REF = "HEAD", DEFAULT_SUMMARY_MODEL = "haiku", HELP_TEXT, VALUE_FLAGS, BUNDLED_AGENTS_DIR_LABEL = "bundled default (from engine)", AGENT_FILE_PATTERNS, RETIRED_AGENT_HINTS, CONFIG_DIRECTION, SUMMARY_DIRECTION, CLAUDE_CREDENTIAL_KINDS, EMPTY_LOCAL_CONFIG, KNOWN_CONFIG_KEYS, PERSON_ONLY_KEYS, LOCAL_CONFIG_KEYS, GLOBAL_CONFIG_KEYS, REPO_CONFIG_LABEL = ".crysk/config.json", GLOBAL_CONFIG_LABEL = "~/.crysk/config.json", REMOVED_ROUTING_MESSAGE = '`routing` is gone: set models per role, e.g. `"models": {"hunter.logic": ["claude:sonnet-latest"]}`', SUMMARY_MODEL_EXAMPLE = '`"models": {"summary": ["claude:haiku-latest"]}`', SUMMARY_MODEL_INIT_VALUE = "haiku", SUMMARY_MODEL_CONVERTED, CREDENTIALS_EXAMPLE = '`"credentials": {"claude": ["subscription", "api_key"]}`', DEFAULT_MAX_VERIFICATION_STEPS = 8, GOTCHAS_PLACEHOLDER_MARKER = "human-attention-required", GOTCHAS_TEMPLATE, REVIEW_MD_TEMPLATE, SETUP_GOTCHAS_FALLBACK, RETIRED_SCAFFOLD_LINES, SCAFFOLD_BODY_LINES, NO_REVIEW_INSTRUCTIONS = "This repository provides no review instructions (no REVIEW.md or gotchas file).";
5968
6215
  var init_preflight2 = __esm(() => {
5969
6216
  init_review_policy();
6217
+ init_model_name();
6218
+ init_routing();
5970
6219
  init_post_floor();
5971
6220
  init_spec();
5972
6221
  init_triage();
@@ -6179,7 +6428,11 @@ Options:
6179
6428
  default 8; 0 pauses verification), and optional
6180
6429
  max_concurrent_steps (cap on steps in flight at once;
6181
6430
  a positive integer; unset = unlimited)
6182
- --model <model> Override every agent's model
6431
+ --model <model> Override every step's model but the materiality judge's:
6432
+ claude:<name>-latest, claude:<full model name>,
6433
+ opencode:<provider>/<model>, or a bare alias (sonnet,
6434
+ opus, haiku, fable). A model only: per-role models and
6435
+ their effort go in "models" in ~/.crysk/config.json
6183
6436
  --summary Enable the engine-owned PR summary (default)
6184
6437
  --no-summary Disable the engine-owned PR summary
6185
6438
  --scout review only: run the diff-only scout stage before the
@@ -6294,13 +6547,17 @@ about how well a large diff reviews.`;
6294
6547
  "--kill"
6295
6548
  ]);
6296
6549
  AGENT_FILE_PATTERNS = ["deep-review-*.md", "review-*.md"];
6550
+ RETIRED_AGENT_HINTS = {
6551
+ "deep-review-lifecycle.md": "; the lifecycle hunter was retired from the default spec: delete the file, or keep the hunter with CRYSK_EXTRA_HUNTERS=lifecycle:deep-review-lifecycle.md"
6552
+ };
6297
6553
  CONFIG_DIRECTION = {
6298
6554
  agents_dir: "person",
6299
6555
  default_base: "repo",
6300
6556
  parity_trigger_paths: "repo",
6301
6557
  suspicion_priors: "repo",
6302
6558
  summary: "capped",
6303
- routing: "person",
6559
+ models: "person",
6560
+ credentials: "person",
6304
6561
  max_verification_steps: "capped",
6305
6562
  max_concurrent_steps: "capped",
6306
6563
  max_changed_lines: "capped",
@@ -6319,38 +6576,18 @@ about how well a large diff reviews.`;
6319
6576
  ci_admission_observe_only: "repo"
6320
6577
  };
6321
6578
  SUMMARY_DIRECTION = {
6322
- enabled: "capped",
6323
- model: "person"
6579
+ enabled: "capped"
6324
6580
  };
6581
+ CLAUDE_CREDENTIAL_KINDS = ["subscription", "api_key"];
6325
6582
  EMPTY_LOCAL_CONFIG = {
6326
6583
  parity_trigger_paths: [],
6327
6584
  suspicion_priors: []
6328
6585
  };
6329
6586
  KNOWN_CONFIG_KEYS = new Set(Object.keys(CONFIG_DIRECTION));
6330
- LOCAL_CONFIG_KEYS = new Set(Object.keys(CONFIG_DIRECTION).filter((key) => key !== "routing"));
6587
+ PERSON_ONLY_KEYS = new Set(["models", "credentials"]);
6588
+ LOCAL_CONFIG_KEYS = new Set(Object.keys(CONFIG_DIRECTION).filter((key) => !PERSON_ONLY_KEYS.has(key)));
6331
6589
  GLOBAL_CONFIG_KEYS = new Set(Object.keys(CONFIG_DIRECTION).filter((key) => CONFIG_DIRECTION[key] !== "repo"));
6332
- CREDENTIAL_KEY_NAMES = new Set([
6333
- "apikey",
6334
- "api_key",
6335
- "token",
6336
- "secret",
6337
- "password",
6338
- "bearer",
6339
- "auth",
6340
- "credential",
6341
- "credentials"
6342
- ]);
6343
- KNOWN_ROUTE_MAPPING_KEYS = new Set([
6344
- "logical",
6345
- "backend",
6346
- "provider",
6347
- "gateway",
6348
- "modelFamily",
6349
- "modelSnapshot",
6350
- "modelVariant",
6351
- "disabled",
6352
- "allowSpend"
6353
- ]);
6590
+ SUMMARY_MODEL_CONVERTED = ["claude:haiku-latest"];
6354
6591
  GOTCHAS_TEMPLATE = `<!-- ${GOTCHAS_PLACEHOLDER_MARKER}: delete THIS line once the gotchas below are real \u2014 Crysk refuses to review while it is here. -->
6355
6592
  # Repo gotchas
6356
6593
 
@@ -6803,12 +7040,12 @@ function isInFlightCommitStatus(statuses, nowMs, ttlMs = IN_FLIGHT_TTL_MS, conte
6803
7040
  });
6804
7041
  }
6805
7042
  var PR_COMMENT_MARKER_PREFIX, PR_REREVIEW_CLOSED_MARKER_PREFIX, PR_COMMENT_COVERAGE_PARTIAL_TOKEN = "coverage=partial", PR_FINDING_MARKER_PREFIX, COMMIT_STATUS_CONTEXT, LOCAL_COMMIT_STATUS_CONTEXT, RUN_STATUS_CONTEXTS, IN_FLIGHT_TTL_MS, COMMIT_STATUS_TIMEOUT_MS = 15000, CANCELLATION_COMMIT_STATUS_TIMEOUT_MS = 5000, COMMIT_STATUS_DESCRIPTION_MAX = 140, MANUAL_REVIEW_HOLD, HELD_VERDICT;
6806
- var init_preflight3 = __esm(() => {
6807
- init_publish();
7043
+ var init_preflight3 = __esm(async () => {
6808
7044
  init_preflight2();
6809
7045
  init_size_gate();
6810
7046
  init_brand();
6811
7047
  init_errors();
7048
+ await init_publish();
6812
7049
  PR_COMMENT_MARKER_PREFIX = `${MARKER_OPEN}report `;
6813
7050
  PR_REREVIEW_CLOSED_MARKER_PREFIX = `${MARKER_OPEN}rereview-closed `;
6814
7051
  PR_FINDING_MARKER_PREFIX = `${MARKER_OPEN}finding `;
@@ -7457,9 +7694,9 @@ init_findings_conformance();
7457
7694
  init_materiality();
7458
7695
  init_catalog();
7459
7696
  init_routing();
7460
- import { existsSync as existsSync12 } from "fs";
7461
- import { chmod, mkdir as mkdir7, realpath as realpath4 } from "fs/promises";
7462
- import path23 from "path";
7697
+ import { existsSync as existsSync13 } from "fs";
7698
+ import { chmod, mkdir as mkdir8, realpath as realpath4 } from "fs/promises";
7699
+ import path24 from "path";
7463
7700
 
7464
7701
  // src/rereview/adjudicate.ts
7465
7702
  init_boundary();
@@ -7867,7 +8104,7 @@ function applyWorsening(input) {
7867
8104
  }
7868
8105
 
7869
8106
  // src/rereview/state.ts
7870
- init_preflight3();
8107
+ await init_preflight3();
7871
8108
  init_findings();
7872
8109
  init_materiality_gate();
7873
8110
  init_brand();
@@ -9130,6 +9367,7 @@ function buildAdjudicationGroups(observations) {
9130
9367
  init_errors2();
9131
9368
 
9132
9369
  // src/diversity/identity.ts
9370
+ init_model_name();
9133
9371
  init_routing();
9134
9372
  init_spec();
9135
9373
  init_errors2();
@@ -9176,15 +9414,14 @@ function buildDiversityPlan(input) {
9176
9414
  continue;
9177
9415
  const specialty = resolveSpecialty(agent);
9178
9416
  for (const model of models) {
9179
- const parsed = parseLogicalIdentity(model);
9417
+ const parsed = { canonical: modelNameFromAlias(model).raw };
9180
9418
  const provisionalKey = diversityLegAgentKey(agent.key, deriveLegId(specialty, parsed.canonical, "pending"));
9181
9419
  const stepRoute = resolveStepRoute({
9182
9420
  stepKey: agentStepKey({ key: provisionalKey, role: "hunter" }),
9183
9421
  role: "hunter",
9184
9422
  cliModel: input.cliModel,
9185
9423
  specModel: model,
9186
- frontmatterModel: input.frontmatterModel?.(agent.key),
9187
- routingConfig: input.routingConfig
9424
+ frontmatterModel: input.frontmatterModel?.(agent.key)
9188
9425
  });
9189
9426
  const legId = deriveLegId(specialty, parsed.canonical, stepRoute.routeFingerprint);
9190
9427
  const agentKey = diversityLegAgentKey(agent.key, legId);
@@ -9360,7 +9597,6 @@ function prepareDiversityExecution(input) {
9360
9597
  spec: input.reviewSpec,
9361
9598
  c2SchemaVersion: SCHEMA_VERSION_V1_1,
9362
9599
  cliModel: input.cliModel,
9363
- routingConfig: input.routingConfig,
9364
9600
  frontmatterModel: input.frontmatterModel,
9365
9601
  target: frozenTarget,
9366
9602
  promptFingerprint: input.promptFingerprint,
@@ -9519,7 +9755,6 @@ function recordDiversityHunterResult(ledger, plan, agent, result, leg, executedR
9519
9755
  legId: resolvedLeg.legId,
9520
9756
  backend: routeProvenance.backend,
9521
9757
  provider: routeProvenance.provider,
9522
- ...routeProvenance.gateway === undefined ? {} : { gateway: routeProvenance.gateway },
9523
9758
  modelFamily: routeProvenance.modelFamily,
9524
9759
  modelSnapshot: routeProvenance.modelSnapshot,
9525
9760
  ...routeProvenance.modelVariant === undefined ? {} : { modelVariant: routeProvenance.modelVariant },
@@ -9585,83 +9820,406 @@ function buildDiversityPipelineRecord(ctx, partial) {
9585
9820
  if (!ctx.plan) {
9586
9821
  return { enabled: true, status: "failed" };
9587
9822
  }
9588
- const totals = ctx.ledger.attempts.reduce((acc, attempt) => ({
9589
- cash: acc.cash + (attempt.usage.cashCostUsd ?? 0),
9590
- notional: acc.notional + (attempt.usage.notionalCostUsd ?? 0)
9591
- }), { cash: 0, notional: 0 });
9592
- return {
9593
- enabled: true,
9594
- status: partial ? "partial" : "ok",
9595
- armId: ctx.plan.armId,
9596
- planFingerprint: ctx.plan.planFingerprint,
9597
- legCount: ctx.plan.legs.length,
9598
- attemptCount: ctx.ledger.attempts.length,
9599
- observationCount: ctx.ledger.observations.length,
9600
- failureCount: ctx.ledger.failures.length,
9601
- cashCostUsd: totals.cash,
9602
- notionalCostUsd: totals.notional
9603
- };
9823
+ const totals = ctx.ledger.attempts.reduce((acc, attempt) => ({
9824
+ cash: acc.cash + (attempt.usage.cashCostUsd ?? 0),
9825
+ notional: acc.notional + (attempt.usage.notionalCostUsd ?? 0)
9826
+ }), { cash: 0, notional: 0 });
9827
+ return {
9828
+ enabled: true,
9829
+ status: partial ? "partial" : "ok",
9830
+ armId: ctx.plan.armId,
9831
+ planFingerprint: ctx.plan.planFingerprint,
9832
+ legCount: ctx.plan.legs.length,
9833
+ attemptCount: ctx.ledger.attempts.length,
9834
+ observationCount: ctx.ledger.observations.length,
9835
+ failureCount: ctx.ledger.failures.length,
9836
+ cashCostUsd: totals.cash,
9837
+ notionalCostUsd: totals.notional
9838
+ };
9839
+ }
9840
+ function diversityDebugFromLedger(ctx) {
9841
+ if (!ctx.enabled || !ctx.plan)
9842
+ return;
9843
+ return {
9844
+ planFingerprint: ctx.plan.planFingerprint,
9845
+ attempts: ctx.ledger.attempts.map((attempt) => ({
9846
+ attemptId: attempt.attemptId,
9847
+ legId: attempt.legId,
9848
+ armId: attempt.armId,
9849
+ specialty: attempt.specialty,
9850
+ replicate: attempt.replicate,
9851
+ attempt: attempt.attempt,
9852
+ status: attempt.status,
9853
+ cashCostUsd: attempt.usage.cashCostUsd ?? null,
9854
+ notionalCostUsd: attempt.usage.notionalCostUsd ?? null
9855
+ })),
9856
+ observations: ctx.ledger.observations.map((record) => ({
9857
+ observationId: record.observation.observationId,
9858
+ attemptId: record.attemptId,
9859
+ legId: record.legId,
9860
+ armId: record.armId,
9861
+ specialty: record.observation.specialty,
9862
+ path: record.observation.path,
9863
+ backend: record.observation.backend,
9864
+ provider: record.observation.provider,
9865
+ modelFamily: record.observation.modelFamily,
9866
+ modelSnapshot: record.observation.modelSnapshot,
9867
+ ...record.observation.modelVariant === undefined ? {} : { modelVariant: record.observation.modelVariant }
9868
+ }))
9869
+ };
9870
+ }
9871
+
9872
+ // src/execution/atomic-write.ts
9873
+ import { mkdir as mkdir4, rename as rename2 } from "fs/promises";
9874
+ import path14 from "path";
9875
+ async function writeJsonAtomically(outPath, value, options = {}) {
9876
+ const tmpPath = `${outPath}.tmp`;
9877
+ await mkdir4(path14.dirname(outPath), { recursive: true });
9878
+ const text = options.compact ? JSON.stringify(value) : `${JSON.stringify(value, null, 2)}
9879
+ `;
9880
+ await Bun.write(tmpPath, text);
9881
+ await rename2(tmpPath, outPath);
9882
+ }
9883
+
9884
+ // src/execution/claude-session-trace.ts
9885
+ init_evidence_redaction();
9886
+ import { existsSync as existsSync7 } from "fs";
9887
+ import { mkdir as mkdir5, open as open2, unlink } from "fs/promises";
9888
+ import path15 from "path";
9889
+ var CLAUDE_TRACE_MISSES = [
9890
+ "session file missing",
9891
+ "more than one session file",
9892
+ "session trace write failed"
9893
+ ];
9894
+ var retained = new WeakMap;
9895
+ function claudeSessionTracePath(outPath, stepName, attempt) {
9896
+ return path15.join(path15.dirname(outPath), `trace.${stepName}.attempt${attempt}.jsonl`);
9897
+ }
9898
+ function claudeTraceCaptureAnnotation(reason) {
9899
+ return `[pr-hero] claude session trace was not copied (${reason})`;
9900
+ }
9901
+ function newClaudeSessionId() {
9902
+ return crypto.randomUUID();
9903
+ }
9904
+ function retainClaudeSession(request, sessionId) {
9905
+ retained.set(request, sessionId);
9906
+ }
9907
+ async function findSessionFile(configHome, sessionId) {
9908
+ const projects = path15.join(configHome, "projects");
9909
+ if (!existsSync7(projects))
9910
+ return "session file missing";
9911
+ const matches = [];
9912
+ const glob = new Bun.Glob(`**/${sessionId}.jsonl`);
9913
+ for await (const relative of glob.scan({ cwd: projects, onlyFiles: true })) {
9914
+ matches.push(path15.join(projects, relative));
9915
+ if (matches.length > 1)
9916
+ return "more than one session file";
9917
+ }
9918
+ const only = matches[0];
9919
+ return only === undefined ? "session file missing" : only;
9920
+ }
9921
+ async function copyRetainedClaudeSession(request, dest) {
9922
+ const noted = retained.get(request);
9923
+ if (noted === undefined) {
9924
+ await dropStaleTrace(dest);
9925
+ return;
9926
+ }
9927
+ try {
9928
+ const source = await findSessionFile(request.isolation.syntheticConfigHome, noted);
9929
+ if (source === "session file missing" || source === "more than one session file") {
9930
+ await dropStaleTrace(dest);
9931
+ return source;
9932
+ }
9933
+ await copySessionJsonl(source, dest);
9934
+ return;
9935
+ } catch {
9936
+ await dropStaleTrace(dest);
9937
+ return "session trace write failed";
9938
+ }
9939
+ }
9940
+ var MAX_LINE_BYTES = 4 * 1024 * 1024;
9941
+ var MAX_COPY_BYTES = 64 * 1024 * 1024;
9942
+ var OMITTED_LINE = JSON.stringify({ crysk: "session line omitted" });
9943
+ var TRUNCATED_LINE = `${JSON.stringify({ crysk: "session truncated" })}
9944
+ `;
9945
+ var NEWLINE = 10;
9946
+ async function copySessionJsonl(source, dest) {
9947
+ await mkdir5(path15.dirname(dest), { recursive: true });
9948
+ const out = await open2(dest, "w");
9949
+ const reader = Bun.file(source).stream().getReader();
9950
+ const encoder = new TextEncoder;
9951
+ const decoder = new TextDecoder;
9952
+ const truncatedBytes = encoder.encode(TRUNCATED_LINE).byteLength;
9953
+ let written = 0;
9954
+ let pending = [];
9955
+ let pendingBytes = 0;
9956
+ let overLimit = false;
9957
+ const emit = async (line, newline) => {
9958
+ const bytes = encoder.encode(newline ? `${line}
9959
+ ` : line);
9960
+ if (written + bytes.byteLength + truncatedBytes > MAX_COPY_BYTES) {
9961
+ await out.write(TRUNCATED_LINE);
9962
+ return false;
9963
+ }
9964
+ await out.write(bytes);
9965
+ written += bytes.byteLength;
9966
+ return true;
9967
+ };
9968
+ const finishLine = () => {
9969
+ const line = overLimit ? OMITTED_LINE : redactSessionLine(decoder.decode(Buffer.concat(pending)));
9970
+ pending = [];
9971
+ pendingBytes = 0;
9972
+ overLimit = false;
9973
+ return line;
9974
+ };
9975
+ const hold = (bytes) => {
9976
+ if (overLimit || bytes.byteLength === 0)
9977
+ return;
9978
+ if (pendingBytes + bytes.byteLength > MAX_LINE_BYTES) {
9979
+ overLimit = true;
9980
+ pending = [];
9981
+ pendingBytes = 0;
9982
+ return;
9983
+ }
9984
+ pending.push(bytes);
9985
+ pendingBytes += bytes.byteLength;
9986
+ };
9987
+ try {
9988
+ for (;; ) {
9989
+ const { done, value } = await reader.read();
9990
+ if (done)
9991
+ break;
9992
+ let start = 0;
9993
+ for (let at = value.indexOf(NEWLINE);at !== -1; at = value.indexOf(NEWLINE, start)) {
9994
+ hold(value.subarray(start, at));
9995
+ start = at + 1;
9996
+ if (!await emit(finishLine(), true))
9997
+ return;
9998
+ }
9999
+ hold(value.subarray(start));
10000
+ }
10001
+ if (pendingBytes > 0 || overLimit)
10002
+ await emit(finishLine(), false);
10003
+ } finally {
10004
+ await reader.cancel().catch(() => {
10005
+ return;
10006
+ });
10007
+ await out.close();
10008
+ }
10009
+ }
10010
+ var SESSION_SECRET_KEY = /authorization|cookie|password|secret|api.?key|access.?token|refresh.?token|^token$|^key$/i;
10011
+ var SESSION_SECRET_WORDS = new Set([
10012
+ "auth",
10013
+ "oauth",
10014
+ "cookie",
10015
+ "cookies",
10016
+ "credential",
10017
+ "credentials"
10018
+ ]);
10019
+ function isSessionSecretName(name) {
10020
+ if (isSecretName(name))
10021
+ return true;
10022
+ const parts = nameParts(name);
10023
+ return parts.some((part) => SESSION_SECRET_WORDS.has(part)) || parts.at(-1) === "session";
10024
+ }
10025
+ var MAX_DEPTH = 12;
10026
+ var MAX_NODES = 20000;
10027
+ function redactSessionLine(line) {
10028
+ if (line.length === 0)
10029
+ return line;
10030
+ try {
10031
+ return JSON.stringify(redactSessionValue(JSON.parse(line), 0, { nodes: 0 }));
10032
+ } catch {
10033
+ return OMITTED_LINE;
10034
+ }
10035
+ }
10036
+ function redactSessionValue(value, depth, budget) {
10037
+ if (++budget.nodes > MAX_NODES || depth > MAX_DEPTH) {
10038
+ throw new Error("session redaction limit");
10039
+ }
10040
+ if (typeof value === "string")
10041
+ return redactSessionString(value, depth, budget);
10042
+ if (Array.isArray(value)) {
10043
+ return value.map((item) => redactSessionValue(item, depth + 1, budget));
10044
+ }
10045
+ if (isPlainObject(value)) {
10046
+ const out = {};
10047
+ for (const [key, item] of Object.entries(value)) {
10048
+ if (SESSION_SECRET_KEY.test(key))
10049
+ out[key] = "[REDACTED]";
10050
+ else if (isSessionSecretName(key))
10051
+ out[key] = redactStrings(item, depth + 1, budget);
10052
+ else
10053
+ out[key] = redactSessionValue(item, depth + 1, budget);
10054
+ }
10055
+ return out;
10056
+ }
10057
+ return redactScalar(value);
10058
+ }
10059
+ function redactStrings(value, depth, budget) {
10060
+ if (++budget.nodes > MAX_NODES || depth > MAX_DEPTH) {
10061
+ throw new Error("session redaction limit");
10062
+ }
10063
+ if (typeof value === "string")
10064
+ return "[REDACTED]";
10065
+ if (Array.isArray(value)) {
10066
+ return value.map((item) => redactStrings(item, depth + 1, budget));
10067
+ }
10068
+ if (isPlainObject(value)) {
10069
+ const out = {};
10070
+ for (const [key, item] of Object.entries(value)) {
10071
+ out[key] = redactStrings(item, depth + 1, budget);
10072
+ }
10073
+ return out;
10074
+ }
10075
+ return redactScalar(value);
10076
+ }
10077
+ function isPlainObject(value) {
10078
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
10079
+ return false;
10080
+ }
10081
+ const proto = Object.getPrototypeOf(value);
10082
+ if (proto !== Object.prototype && proto !== null) {
10083
+ throw new Error("non-JSON session value");
10084
+ }
10085
+ return true;
10086
+ }
10087
+ function redactScalar(value) {
10088
+ if (value === null || typeof value === "boolean" || typeof value === "number") {
10089
+ return value;
10090
+ }
10091
+ throw new Error("non-JSON session value");
10092
+ }
10093
+ var TRACE_KEY_SHAPES = [
10094
+ /(?<![A-Za-z0-9])sk-[A-Za-z0-9_-]{8,}/g,
10095
+ /sk-(?:ant|proj|or|svcacct|admin)-[A-Za-z0-9_-]{8,}/g,
10096
+ /sk-[A-Za-z0-9]{32,}/g,
10097
+ /gh[pousr]_[A-Za-z0-9_]{20,}/g,
10098
+ /Bearer\s+\S+/gi,
10099
+ /AIza[0-9A-Za-z_-]{35}/g,
10100
+ /gsk_[A-Za-z0-9]{20,}/g,
10101
+ /xai-[A-Za-z0-9]{20,}/g
10102
+ ];
10103
+ var TRACE_KEYWORD_VALUE = new RegExp(String.raw`(api[_-]?key|token|password)([ \t"':=]+)(${EXPRESSION_VALUE}|\S+)`, "gi");
10104
+ var PROSE_AFTER_PASSWORD = new Set([
10105
+ "is",
10106
+ "was",
10107
+ "are",
10108
+ "were",
10109
+ "has",
10110
+ "have",
10111
+ "had",
10112
+ "will",
10113
+ "would",
10114
+ "can",
10115
+ "could",
10116
+ "must",
10117
+ "should",
10118
+ "not",
10119
+ "no",
10120
+ "in",
10121
+ "on",
10122
+ "at",
10123
+ "of",
10124
+ "or",
10125
+ "and",
10126
+ "to",
10127
+ "for",
10128
+ "from",
10129
+ "with",
10130
+ "expired",
10131
+ "invalid",
10132
+ "rejected",
10133
+ "revoked",
10134
+ "missing",
10135
+ "required",
10136
+ "provided",
10137
+ "found",
10138
+ "refused",
10139
+ "denied"
10140
+ ]);
10141
+ var SENTENCE_END = /[.,;:!?)\]"']+$/;
10142
+ function looksLikeKeyValue(word) {
10143
+ return /\d/.test(word) || /^[A-Za-z0-9_+/=.-]{16,}$/.test(word) && /[a-z]/.test(word) && /[A-Z]/.test(word);
10144
+ }
10145
+ function redactTraceDiagnostic(text) {
10146
+ let redacted = text;
10147
+ for (const shape of TRACE_KEY_SHAPES) {
10148
+ redacted = redacted.replace(shape, "[REDACTED]");
10149
+ }
10150
+ return redacted.replace(TRACE_KEYWORD_VALUE, (match, keyword, separator, value) => {
10151
+ if (value.startsWith("[REDACTED"))
10152
+ return match;
10153
+ const bare = value.replace(SENTENCE_END, "");
10154
+ const hidden = `${keyword}${separator}[REDACTED]`;
10155
+ if (!/^[ \t]+$/.test(separator)) {
10156
+ return isNonSecretValue(bare, keyword) ? match : hidden;
10157
+ }
10158
+ if (/^password$/i.test(keyword)) {
10159
+ return PROSE_AFTER_PASSWORD.has(bare.toLowerCase()) ? match : hidden;
10160
+ }
10161
+ return looksLikeKeyValue(value) ? hidden : match;
10162
+ });
10163
+ }
10164
+ function redactSessionString(value, depth, budget) {
10165
+ const trimmed = value.trim();
10166
+ const wrapped = trimmed.startsWith("{") && trimmed.endsWith("}") || trimmed.startsWith("[") && trimmed.endsWith("]");
10167
+ if (wrapped) {
10168
+ try {
10169
+ const inner = JSON.parse(redactSecretShapes(trimmed, isSessionSecretName, true));
10170
+ if (typeof inner === "object" && inner !== null) {
10171
+ return JSON.stringify(redactSessionValue(inner, depth + 1, budget));
10172
+ }
10173
+ } catch {}
10174
+ }
10175
+ return redactTraceDiagnostic(redactEvidenceText(redactSecretShapes(value, isSessionSecretName, true)));
9604
10176
  }
9605
- function diversityDebugFromLedger(ctx) {
9606
- if (!ctx.enabled || !ctx.plan)
10177
+ async function dropStaleTrace(dest) {
10178
+ await unlink(dest).catch(() => {
9607
10179
  return;
9608
- return {
9609
- planFingerprint: ctx.plan.planFingerprint,
9610
- attempts: ctx.ledger.attempts.map((attempt) => ({
9611
- attemptId: attempt.attemptId,
9612
- legId: attempt.legId,
9613
- armId: attempt.armId,
9614
- specialty: attempt.specialty,
9615
- replicate: attempt.replicate,
9616
- attempt: attempt.attempt,
9617
- status: attempt.status,
9618
- cashCostUsd: attempt.usage.cashCostUsd ?? null,
9619
- notionalCostUsd: attempt.usage.notionalCostUsd ?? null
9620
- })),
9621
- observations: ctx.ledger.observations.map((record) => ({
9622
- observationId: record.observation.observationId,
9623
- attemptId: record.attemptId,
9624
- legId: record.legId,
9625
- armId: record.armId,
9626
- specialty: record.observation.specialty,
9627
- path: record.observation.path,
9628
- backend: record.observation.backend,
9629
- provider: record.observation.provider,
9630
- ...record.observation.gateway === undefined ? {} : { gateway: record.observation.gateway },
9631
- modelFamily: record.observation.modelFamily,
9632
- modelSnapshot: record.observation.modelSnapshot,
9633
- ...record.observation.modelVariant === undefined ? {} : { modelVariant: record.observation.modelVariant }
9634
- }))
9635
- };
10180
+ });
9636
10181
  }
9637
10182
 
9638
- // src/execution/atomic-write.ts
9639
- import { mkdir as mkdir4, rename as rename2 } from "fs/promises";
9640
- import path14 from "path";
9641
- async function writeJsonAtomically(outPath, value, options = {}) {
9642
- const tmpPath = `${outPath}.tmp`;
9643
- await mkdir4(path14.dirname(outPath), { recursive: true });
9644
- const text = options.compact ? JSON.stringify(value) : `${JSON.stringify(value, null, 2)}
9645
- `;
9646
- await Bun.write(tmpPath, text);
9647
- await rename2(tmpPath, outPath);
10183
+ // src/execution/contracts.ts
10184
+ function effortApplied(route) {
10185
+ return route.backend === "claude-code" || route.backend === "opencode" && route.modelVariant !== undefined;
10186
+ }
10187
+ var TRANSPORT_FAILURE_CAUSE_LOOKUP = {
10188
+ auth_invalid: true,
10189
+ quota_exhausted: true,
10190
+ rate_limit: true,
10191
+ network_transient: true,
10192
+ protocol_truncation: true,
10193
+ protocol_mismatch: true,
10194
+ protocol_overflow: true,
10195
+ output_limit_exceeded: true,
10196
+ context_window_exceeded: true,
10197
+ safety_refusal: true,
10198
+ provider_configuration_invalid: true,
10199
+ model_unavailable: true,
10200
+ missing_provider_record: true,
10201
+ runtime_unavailable: true,
10202
+ remote_abort_unconfirmed: true
10203
+ };
10204
+ function isTransportFailureCause(value) {
10205
+ return typeof value === "string" && Object.hasOwn(TRANSPORT_FAILURE_CAUSE_LOOKUP, value);
9648
10206
  }
9649
10207
 
9650
10208
  // src/execution/harness.ts
9651
- import { mkdir as mkdir6 } from "fs/promises";
9652
- import path22 from "path";
10209
+ import { mkdir as mkdir7 } from "fs/promises";
10210
+ import path23 from "path";
9653
10211
 
9654
10212
  // src/model/exec-snapshots.ts
9655
10213
  import { rmSync as rmSync2 } from "fs";
9656
10214
  import { lstat, readdir, rm as rm2 } from "fs/promises";
9657
10215
  import { tmpdir } from "os";
9658
- import path15 from "path";
10216
+ import path16 from "path";
9659
10217
  var EXEC_SNAPSHOT_DIRNAME = "prhero-exec-snapshots";
9660
10218
  var STALE_SNAPSHOT_MAX_AGE_MS = 6 * 60 * 60 * 1000;
9661
10219
  var SNAPSHOT_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
9662
10220
  var OPPORTUNISTIC_SWEEP_BUDGET_MS = 2000;
9663
10221
  function defaultExecSnapshotBase() {
9664
- return path15.join(tmpdir(), EXEC_SNAPSHOT_DIRNAME);
10222
+ return path16.join(tmpdir(), EXEC_SNAPSHOT_DIRNAME);
9665
10223
  }
9666
10224
  function executionSnapshotDirName(digest, pid, uuid) {
9667
10225
  return `${digest.slice(0, 16)}-${pid}-${uuid}`;
@@ -9669,17 +10227,17 @@ function executionSnapshotDirName(digest, pid, uuid) {
9669
10227
  var registeredSnapshotDirs = new Set;
9670
10228
  var exitHookInstalled = false;
9671
10229
  function registerExecutionSnapshot(snapshotDir) {
9672
- registeredSnapshotDirs.add(path15.resolve(snapshotDir));
10230
+ registeredSnapshotDirs.add(path16.resolve(snapshotDir));
9673
10231
  if (!exitHookInstalled) {
9674
10232
  exitHookInstalled = true;
9675
10233
  process.on("exit", releaseAllExecutionSnapshots);
9676
10234
  }
9677
10235
  }
9678
10236
  function registeredDirFor(target) {
9679
- const resolved = path15.resolve(target);
10237
+ const resolved = path16.resolve(target);
9680
10238
  if (registeredSnapshotDirs.has(resolved))
9681
10239
  return resolved;
9682
- const parent = path15.dirname(resolved);
10240
+ const parent = path16.dirname(resolved);
9683
10241
  if (registeredSnapshotDirs.has(parent))
9684
10242
  return parent;
9685
10243
  return;
@@ -9740,7 +10298,7 @@ async function snapshotDirBytes(dir) {
9740
10298
  try {
9741
10299
  let total = 0;
9742
10300
  for (const name of await readdir(dir)) {
9743
- const stats = await lstat(path15.join(dir, name));
10301
+ const stats = await lstat(path16.join(dir, name));
9744
10302
  if (stats.isFile())
9745
10303
  total += stats.size;
9746
10304
  }
@@ -9780,7 +10338,7 @@ async function sweepStaleExecutionSnapshots(options = {}) {
9780
10338
  unprocessed: names.length - index
9781
10339
  };
9782
10340
  }
9783
- const entryPath = path15.join(base, name);
10341
+ const entryPath = path16.join(base, name);
9784
10342
  let stats;
9785
10343
  try {
9786
10344
  stats = await lstat(entryPath);
@@ -9792,7 +10350,7 @@ async function sweepStaleExecutionSnapshots(options = {}) {
9792
10350
  kind: stats.isSymbolicLink() ? "symlink" : stats.isDirectory() ? "directory" : "other",
9793
10351
  ownerUid: stats.uid,
9794
10352
  mtimeMs: stats.mtimeMs,
9795
- registeredByThisProcess: registeredSnapshotDirs.has(path15.resolve(entryPath))
10353
+ registeredByThisProcess: registeredSnapshotDirs.has(path16.resolve(entryPath))
9796
10354
  }, policy);
9797
10355
  if (decision.action === "keep") {
9798
10356
  kept++;
@@ -9816,7 +10374,7 @@ async function sweepStaleExecutionSnapshots(options = {}) {
9816
10374
  }
9817
10375
  var lastSweepAtMsByBase = new Map;
9818
10376
  async function sweepExecutionSnapshotsOpportunistically(snapshotBase, nowMs = Date.now(), budget = {}) {
9819
- const key = path15.resolve(snapshotBase);
10377
+ const key = path16.resolve(snapshotBase);
9820
10378
  const last = lastSweepAtMsByBase.get(key);
9821
10379
  if (last !== undefined && nowMs - last < SNAPSHOT_SWEEP_INTERVAL_MS) {
9822
10380
  return;
@@ -9844,7 +10402,7 @@ import {
9844
10402
  chmodSync,
9845
10403
  closeSync,
9846
10404
  constants,
9847
- existsSync as existsSync7,
10405
+ existsSync as existsSync8,
9848
10406
  mkdirSync as mkdirSync2,
9849
10407
  openSync,
9850
10408
  readFileSync as readFileSync3,
@@ -9853,14 +10411,14 @@ import {
9853
10411
  } from "fs";
9854
10412
  import { readFile, realpath } from "fs/promises";
9855
10413
  import { homedir as homedir2 } from "os";
9856
- import path16 from "path";
10414
+ import path17 from "path";
9857
10415
  async function verifyAllowlistedBytes(options, deps) {
9858
10416
  const { candidatePath, allowlist = [] } = options;
9859
10417
  const toRealpath = deps.realpathFn ?? realpath;
9860
10418
  const readBytes = deps.readFileFn ?? ((p) => readFile(p));
9861
10419
  const statFile = deps.statFn ?? ((p) => statSync(p));
9862
10420
  for (const entry of allowlist) {
9863
- if (!path16.isAbsolute(entry.absolutePath)) {
10421
+ if (!path17.isAbsolute(entry.absolutePath)) {
9864
10422
  return {
9865
10423
  approved: false,
9866
10424
  code: "executable_not_approved",
@@ -9868,7 +10426,7 @@ async function verifyAllowlistedBytes(options, deps) {
9868
10426
  };
9869
10427
  }
9870
10428
  }
9871
- if (!path16.isAbsolute(candidatePath)) {
10429
+ if (!path17.isAbsolute(candidatePath)) {
9872
10430
  return {
9873
10431
  approved: false,
9874
10432
  code: "executable_not_approved",
@@ -9917,7 +10475,7 @@ async function verifyAllowlistedBytes(options, deps) {
9917
10475
  reason: `Failed to read and hash binary: ${error.message}`
9918
10476
  };
9919
10477
  }
9920
- const matchingEntry = allowlist.find((entry) => path16.resolve(entry.absolutePath) === canonicalPath && entry.sha256.toLowerCase() === digest.toLowerCase());
10478
+ const matchingEntry = allowlist.find((entry) => path17.resolve(entry.absolutePath) === canonicalPath && entry.sha256.toLowerCase() === digest.toLowerCase());
9921
10479
  if (!matchingEntry) {
9922
10480
  return {
9923
10481
  approved: false,
@@ -9955,13 +10513,13 @@ async function verifyExecutableAuthority(options, deps = {}) {
9955
10513
  }
9956
10514
  const snapBase = options.snapshotDir ?? defaultExecSnapshotBase();
9957
10515
  await sweepExecutionSnapshotsOpportunistically(snapBase);
9958
- const snapDir = path16.join(snapBase, executionSnapshotDirName(digest, process.pid, randomUUID()));
10516
+ const snapDir = path17.join(snapBase, executionSnapshotDirName(digest, process.pid, randomUUID()));
9959
10517
  try {
9960
10518
  mkdirSync2(snapDir, { recursive: true, mode: 448 });
9961
10519
  registerExecutionSnapshot(snapDir);
9962
10520
  chmodSync(snapDir, 448);
9963
- const snapBinaryName = path16.basename(canonicalPath);
9964
- const snapBinaryPath = path16.join(snapDir, snapBinaryName);
10521
+ const snapBinaryName = path17.basename(canonicalPath);
10522
+ const snapBinaryPath = path17.join(snapDir, snapBinaryName);
9965
10523
  const fd = openSync(snapBinaryPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 448);
9966
10524
  try {
9967
10525
  writeSync(fd, content);
@@ -10000,22 +10558,22 @@ async function verifyExecutableAuthority(options, deps = {}) {
10000
10558
  }
10001
10559
  var CLAUDE_BINARY_NAME = "claude";
10002
10560
  async function resolveClaudeCanonicalBinary(lookup, deps = {}) {
10003
- const exists = deps.existsFn ?? existsSync7;
10561
+ const exists = deps.existsFn ?? existsSync8;
10004
10562
  const toRealpath = deps.realpathFn ?? realpath;
10005
10563
  const readBytes = deps.readFileFn ?? ((p) => readFile(p));
10006
10564
  let candidate;
10007
10565
  if (lookup.binaryPath !== undefined) {
10008
- if (!path16.isAbsolute(lookup.binaryPath)) {
10566
+ if (!path17.isAbsolute(lookup.binaryPath)) {
10009
10567
  return {
10010
10568
  error: `binary override must be an absolute path: ${lookup.binaryPath}`
10011
10569
  };
10012
10570
  }
10013
10571
  candidate = lookup.binaryPath;
10014
10572
  } else {
10015
- const searchDirs = (lookup.env?.PATH ?? process.env.PATH ?? "").split(path16.delimiter).filter((dir) => dir.length > 0);
10573
+ const searchDirs = (lookup.env?.PATH ?? process.env.PATH ?? "").split(path17.delimiter).filter((dir) => dir.length > 0);
10016
10574
  candidate = "";
10017
10575
  for (const dir of searchDirs) {
10018
- const probe = path16.join(dir, CLAUDE_BINARY_NAME);
10576
+ const probe = path17.join(dir, CLAUDE_BINARY_NAME);
10019
10577
  if (exists(probe)) {
10020
10578
  candidate = probe;
10021
10579
  break;
@@ -10049,7 +10607,7 @@ var CLAUDE_CAPABILITY_STATICS = {
10049
10607
  };
10050
10608
  function claudeCredentialProjectionReady(options = {}) {
10051
10609
  const platform = options.platform ?? process.platform;
10052
- const exists = options.existsFn ?? existsSync7;
10610
+ const exists = options.existsFn ?? existsSync8;
10053
10611
  return platform === "darwin" && exists("/usr/bin/security");
10054
10612
  }
10055
10613
  function defaultKeychainCredentialPresent() {
@@ -10061,15 +10619,19 @@ function defaultKeychainCredentialPresent() {
10061
10619
  ]).exitCode === 0;
10062
10620
  }
10063
10621
  var CLAUDE_SESSION_FILES2 = [
10064
- ".claude.json",
10065
- path16.join(".claude", "session.json"),
10066
- path16.join(".claude", ".credentials.json")
10622
+ path17.join(".claude", ".credentials.json")
10623
+ ];
10624
+ var CLAUDE_CREDENTIAL_ENV = [
10625
+ "CRYSK_CLAUDE_OAUTH_TOKEN",
10626
+ "CLAUDE_CODE_OAUTH_TOKEN",
10627
+ "CRYSK_CLAUDE_API_KEY",
10628
+ "ANTHROPIC_API_KEY"
10067
10629
  ];
10068
10630
  function defaultClaudeAuthProbe(env, home, exists, platform, keychainProbe) {
10069
- const hasToken = Boolean(env.CLAUDE_CODE_OAUTH_TOKEN?.trim()) || Boolean(env.ANTHROPIC_API_KEY?.trim());
10631
+ const hasToken = CLAUDE_CREDENTIAL_ENV.some((name) => Boolean(env[name]?.trim()));
10070
10632
  if (hasToken)
10071
10633
  return "passed";
10072
- const hasSessionFile = CLAUDE_SESSION_FILES2.some((file) => exists(path16.join(home, file)));
10634
+ const hasSessionFile = CLAUDE_SESSION_FILES2.some((file) => exists(path17.join(home, file)));
10073
10635
  if (hasSessionFile)
10074
10636
  return "passed";
10075
10637
  if (platform === "darwin" && exists("/usr/bin/security")) {
@@ -10080,7 +10642,7 @@ function defaultClaudeAuthProbe(env, home, exists, platform, keychainProbe) {
10080
10642
  async function produceClaudeCapabilityReport(options = {}) {
10081
10643
  const env = options.env ?? process.env;
10082
10644
  const home = options.home ?? homedir2();
10083
- const existsFn = options.existsFn ?? existsSync7;
10645
+ const existsFn = options.existsFn ?? existsSync8;
10084
10646
  const issues = [];
10085
10647
  const resolved = await resolveClaudeCanonicalBinary({ binaryPath: options.binaryPath, env }, {
10086
10648
  existsFn,
@@ -10248,14 +10810,14 @@ function exactBindingCapabilityGate(report) {
10248
10810
  // src/security/credential-broker.ts
10249
10811
  import { randomUUID as randomUUID2 } from "crypto";
10250
10812
  import {
10251
- existsSync as existsSync8,
10813
+ existsSync as existsSync9,
10252
10814
  lstatSync,
10253
10815
  mkdirSync as mkdirSync3,
10254
10816
  rmSync as rmSync3,
10255
10817
  writeFileSync as writeFileSync2
10256
10818
  } from "fs";
10257
10819
  import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
10258
- import path17 from "path";
10820
+ import path18 from "path";
10259
10821
  var CLAUDE_CREDENTIALS_KEYCHAIN_SERVICE = "Claude Code-credentials";
10260
10822
  var SECURITY_BIN = "/usr/bin/security";
10261
10823
 
@@ -10276,7 +10838,7 @@ class KeychainCredentialBroker {
10276
10838
  if (options.readerFn !== undefined) {
10277
10839
  this.readerFn = options.readerFn;
10278
10840
  } else {
10279
- if (!existsSync8(this.securityBinPath)) {
10841
+ if (!existsSync9(this.securityBinPath)) {
10280
10842
  throw new Error(`Pinned security binary not found at ${this.securityBinPath}`);
10281
10843
  }
10282
10844
  this.readerFn = (service) => this.readKeychain(service);
@@ -10311,10 +10873,10 @@ class KeychainCredentialBroker {
10311
10873
  return this.buildProjection(input.kind, oauthRecord);
10312
10874
  }
10313
10875
  buildProjection(kind, oauthRecord) {
10314
- const projectionRoot = path17.join(tmpdir2(), "prhero-cred-projections", randomUUID2());
10315
- const claudeDir = path17.join(projectionRoot, ".claude");
10316
- const syntheticTmp = path17.join(projectionRoot, "tmp");
10317
- const credentialsFile = path17.join(claudeDir, ".credentials.json");
10876
+ const projectionRoot = path18.join(tmpdir2(), "prhero-cred-projections", randomUUID2());
10877
+ const claudeDir = path18.join(projectionRoot, ".claude");
10878
+ const syntheticTmp = path18.join(projectionRoot, "tmp");
10879
+ const credentialsFile = path18.join(claudeDir, ".credentials.json");
10318
10880
  mkdirSync3(projectionRoot, { recursive: true, mode: 448 });
10319
10881
  mkdirSync3(claudeDir, { recursive: true, mode: 448 });
10320
10882
  mkdirSync3(syntheticTmp, { recursive: true, mode: 448 });
@@ -10323,8 +10885,8 @@ class KeychainCredentialBroker {
10323
10885
  writeFileSync2(credentialsFile, payload, { mode: 384 });
10324
10886
  for (const component of [
10325
10887
  tmpdir2(),
10326
- path17.dirname(path17.dirname(credentialsFile)),
10327
- path17.dirname(credentialsFile),
10888
+ path18.dirname(path18.dirname(credentialsFile)),
10889
+ path18.dirname(credentialsFile),
10328
10890
  credentialsFile
10329
10891
  ]) {
10330
10892
  const stats = lstatSync(component);
@@ -10367,15 +10929,15 @@ class KeychainCredentialBroker {
10367
10929
  return stdout.trim();
10368
10930
  }
10369
10931
  }
10370
- var OPENCODE_AUTH_RELATIVE_PATH = path17.join(".local", "share", "opencode", "auth.json");
10932
+ var OPENCODE_AUTH_RELATIVE_PATH = path18.join(".local", "share", "opencode", "auth.json");
10371
10933
  function openCodeProjectionLayout(projectionRoot, parentDir = tmpdir2()) {
10372
- const localDir = path17.join(projectionRoot, ".local");
10373
- const xdgDataHome = path17.join(localDir, "share");
10374
- const xdgConfigHome = path17.join(projectionRoot, ".config");
10375
- const opencodeDataDir = path17.join(xdgDataHome, "opencode");
10376
- const opencodeConfigDir = path17.join(xdgConfigHome, "opencode");
10377
- const syntheticTmp = path17.join(projectionRoot, "tmp");
10378
- const authFile = path17.join(opencodeDataDir, "auth.json");
10934
+ const localDir = path18.join(projectionRoot, ".local");
10935
+ const xdgDataHome = path18.join(localDir, "share");
10936
+ const xdgConfigHome = path18.join(projectionRoot, ".config");
10937
+ const opencodeDataDir = path18.join(xdgDataHome, "opencode");
10938
+ const opencodeConfigDir = path18.join(xdgConfigHome, "opencode");
10939
+ const syntheticTmp = path18.join(projectionRoot, "tmp");
10940
+ const authFile = path18.join(opencodeDataDir, "auth.json");
10379
10941
  const directories = [
10380
10942
  projectionRoot,
10381
10943
  localDir,
@@ -10399,8 +10961,8 @@ function openCodeProjectionLayout(projectionRoot, parentDir = tmpdir2()) {
10399
10961
  var OPENCODE_OAUTH_PROVIDER = "openai";
10400
10962
  function resolveOpenCodeAuthPath(env = process.env, homeDir = homedir3()) {
10401
10963
  const dataHome = env.XDG_DATA_HOME;
10402
- const base = dataHome !== undefined && dataHome.length > 0 ? dataHome : path17.join(homeDir, ".local", "share");
10403
- return path17.join(base, "opencode", "auth.json");
10964
+ const base = dataHome !== undefined && dataHome.length > 0 ? dataHome : path18.join(homeDir, ".local", "share");
10965
+ return path18.join(base, "opencode", "auth.json");
10404
10966
  }
10405
10967
 
10406
10968
  class OpenCodeAuthBroker {
@@ -10420,34 +10982,41 @@ class OpenCodeAuthBroker {
10420
10982
  if (input.kind !== "opencode_chatgpt_oauth") {
10421
10983
  throw new Error(`Unsupported credential kind: ${input.kind} (OpenCodeAuthBroker projects only opencode_chatgpt_oauth)`);
10422
10984
  }
10423
- let raw;
10424
- try {
10425
- raw = await this.readerFn();
10426
- } catch {
10427
- throw new CredentialProjectionError("source_read_failed");
10428
- }
10429
- let parsed;
10430
- try {
10431
- parsed = JSON.parse(raw);
10432
- } catch {
10433
- throw new CredentialProjectionError("malformed_payload");
10434
- }
10435
- if (typeof parsed !== "object" || parsed === null) {
10436
- throw new CredentialProjectionError("malformed_payload");
10437
- }
10438
- const record = parsed.openai;
10439
- if (typeof record !== "object" || record === null) {
10440
- throw new CredentialProjectionError("missing_subscription_record");
10441
- }
10442
- if (record.type !== "oauth") {
10443
- throw new CredentialProjectionError("missing_subscription_record");
10985
+ const lookup = await lookupOpenCodeOAuthRecord(this.readerFn);
10986
+ if (!lookup.ok) {
10987
+ throw new CredentialProjectionError(lookup.failureClass);
10444
10988
  }
10445
- return buildOpenCodeProjection(input.kind, OPENCODE_OAUTH_PROVIDER, record);
10989
+ return buildOpenCodeProjection(input.kind, OPENCODE_OAUTH_PROVIDER, lookup.record);
10990
+ }
10991
+ }
10992
+ async function lookupOpenCodeOAuthRecord(readerFn) {
10993
+ let raw;
10994
+ try {
10995
+ raw = await readerFn();
10996
+ } catch {
10997
+ return { ok: false, failureClass: "source_read_failed" };
10998
+ }
10999
+ let parsed;
11000
+ try {
11001
+ parsed = JSON.parse(raw);
11002
+ } catch {
11003
+ return { ok: false, failureClass: "malformed_payload" };
11004
+ }
11005
+ if (typeof parsed !== "object" || parsed === null) {
11006
+ return { ok: false, failureClass: "malformed_payload" };
10446
11007
  }
11008
+ const record = parsed.openai;
11009
+ if (typeof record !== "object" || record === null) {
11010
+ return { ok: false, failureClass: "missing_subscription_record" };
11011
+ }
11012
+ if (record.type !== "oauth") {
11013
+ return { ok: false, failureClass: "missing_subscription_record" };
11014
+ }
11015
+ return { ok: true, record };
10447
11016
  }
10448
11017
  function buildOpenCodeProjection(kind, provider, record) {
10449
- const parentDir = path17.join(tmpdir2(), "prhero-cred-projections");
10450
- const layout = openCodeProjectionLayout(path17.join(parentDir, randomUUID2()), parentDir);
11018
+ const parentDir = path18.join(tmpdir2(), "prhero-cred-projections");
11019
+ const layout = openCodeProjectionLayout(path18.join(parentDir, randomUUID2()), parentDir);
10451
11020
  for (const dir of layout.directories) {
10452
11021
  mkdirSync3(dir, { recursive: true, mode: 448 });
10453
11022
  }
@@ -10567,8 +11136,8 @@ class OpenCodeFreeBroker {
10567
11136
  if (lookup.ok) {
10568
11137
  return buildOpenCodeProjection(input.kind, this.provider, lookup.record);
10569
11138
  }
10570
- const parentDir = path17.join(tmpdir2(), "prhero-cred-projections");
10571
- const layout = openCodeProjectionLayout(path17.join(parentDir, randomUUID2()), parentDir);
11139
+ const parentDir = path18.join(tmpdir2(), "prhero-cred-projections");
11140
+ const layout = openCodeProjectionLayout(path18.join(parentDir, randomUUID2()), parentDir);
10572
11141
  for (const dir of layout.directories) {
10573
11142
  mkdirSync3(dir, { recursive: true, mode: 448 });
10574
11143
  }
@@ -10605,12 +11174,12 @@ init_redact();
10605
11174
  // src/security/workspace-read-broker.ts
10606
11175
  init_boundary();
10607
11176
  import {
10608
- existsSync as existsSync9,
11177
+ existsSync as existsSync10,
10609
11178
  lstatSync as lstatSync2,
10610
11179
  readFileSync as readFileSync4,
10611
11180
  realpathSync
10612
11181
  } from "fs";
10613
- import path18 from "path";
11182
+ import path19 from "path";
10614
11183
  var DEFAULT_MAX_FILE_BYTES = 512 * 1024;
10615
11184
  var DEFAULT_MAX_AGGREGATE_BYTES = 8 * 1024 * 1024;
10616
11185
  var DEFAULT_SENSITIVE_BASENAME_PATTERNS = [
@@ -10639,7 +11208,7 @@ var PINNED_GIT_PATHS = [
10639
11208
  "/opt/homebrew/bin/git",
10640
11209
  "/usr/local/bin/git"
10641
11210
  ];
10642
- function resolvePinnedGitPath(override, existsFn = existsSync9) {
11211
+ function resolvePinnedGitPath(override, existsFn = existsSync10) {
10643
11212
  if (override !== undefined) {
10644
11213
  return existsFn(override) ? override : null;
10645
11214
  }
@@ -10660,26 +11229,26 @@ function buildStrippedGitEnv() {
10660
11229
  return childEnv;
10661
11230
  }
10662
11231
  function isInsideRoot(candidate, root) {
10663
- const rel = path18.relative(root, candidate);
10664
- return !rel.startsWith("..") && !path18.isAbsolute(rel);
11232
+ const rel = path19.relative(root, candidate);
11233
+ return !rel.startsWith("..") && !path19.isAbsolute(rel);
10665
11234
  }
10666
11235
  function resolveCanonicalPath(targetPath) {
10667
11236
  try {
10668
11237
  return realpathSync(targetPath);
10669
11238
  } catch {
10670
- let curr = path18.dirname(targetPath);
10671
- const trail = [path18.basename(targetPath)];
10672
- while (curr !== path18.dirname(curr)) {
10673
- if (existsSync9(curr)) {
11239
+ let curr = path19.dirname(targetPath);
11240
+ const trail = [path19.basename(targetPath)];
11241
+ while (curr !== path19.dirname(curr)) {
11242
+ if (existsSync10(curr)) {
10674
11243
  try {
10675
11244
  const canonicalAncestor = realpathSync(curr);
10676
- return path18.join(canonicalAncestor, ...trail);
11245
+ return path19.join(canonicalAncestor, ...trail);
10677
11246
  } catch {
10678
11247
  return null;
10679
11248
  }
10680
11249
  }
10681
- trail.unshift(path18.basename(curr));
10682
- curr = path18.dirname(curr);
11250
+ trail.unshift(path19.basename(curr));
11251
+ curr = path19.dirname(curr);
10683
11252
  }
10684
11253
  return null;
10685
11254
  }
@@ -10694,7 +11263,7 @@ class WorkspaceReadBroker {
10694
11263
  aggregateBytes = 0;
10695
11264
  constructor(options) {
10696
11265
  const root = typeof options === "string" ? options : options.workspaceRoot;
10697
- this.workspaceRoot = path18.resolve(root);
11266
+ this.workspaceRoot = path19.resolve(root);
10698
11267
  try {
10699
11268
  this.canonicalRoot = realpathSync(this.workspaceRoot);
10700
11269
  } catch {
@@ -10705,11 +11274,11 @@ class WorkspaceReadBroker {
10705
11274
  this.maxAggregateBytes = typeof options === "object" && options.maxAggregateBytes !== undefined ? options.maxAggregateBytes : DEFAULT_MAX_AGGREGATE_BYTES;
10706
11275
  }
10707
11276
  checkSensitiveRelative(rel) {
10708
- const normalizedRel = rel.split(path18.sep).join("/");
11277
+ const normalizedRel = rel.split(path19.sep).join("/");
10709
11278
  if (DEFAULT_SENSITIVE_RELATIVE_PATHS.includes(normalizedRel)) {
10710
11279
  return true;
10711
11280
  }
10712
- const basename = path18.basename(normalizedRel);
11281
+ const basename = path19.basename(normalizedRel);
10713
11282
  for (const pattern of DEFAULT_SENSITIVE_BASENAME_PATTERNS) {
10714
11283
  if (pattern.test(basename))
10715
11284
  return true;
@@ -10725,8 +11294,8 @@ class WorkspaceReadBroker {
10725
11294
  const candidates = [this.canonicalRoot, this.workspaceRoot];
10726
11295
  let rel = null;
10727
11296
  for (const base of candidates) {
10728
- const candidateRel = path18.relative(base, resolvedPath);
10729
- if (!candidateRel.startsWith("..") && !path18.isAbsolute(candidateRel)) {
11297
+ const candidateRel = path19.relative(base, resolvedPath);
11298
+ if (!candidateRel.startsWith("..") && !path19.isAbsolute(candidateRel)) {
10730
11299
  if (candidateRel.length === 0)
10731
11300
  return null;
10732
11301
  rel = candidateRel;
@@ -10736,8 +11305,8 @@ class WorkspaceReadBroker {
10736
11305
  if (rel === null)
10737
11306
  return "";
10738
11307
  let walked = this.canonicalRoot;
10739
- for (const segment of rel.split(path18.sep)) {
10740
- walked = path18.join(walked, segment);
11308
+ for (const segment of rel.split(path19.sep)) {
11309
+ walked = path19.join(walked, segment);
10741
11310
  let stats;
10742
11311
  try {
10743
11312
  stats = lstatSync2(walked);
@@ -10758,15 +11327,15 @@ class WorkspaceReadBroker {
10758
11327
  reason: symlinkComponent.length > 0 ? `Symlink traversal rejected at component '${symlinkComponent}' of ${lexicalResolvedPath}` : `Read path does not resolve lexically below the workspace root: ${lexicalResolvedPath}`
10759
11328
  };
10760
11329
  }
10761
- let relToWorkspace = path18.relative(this.workspaceRoot, canonicalPath);
10762
- if (relToWorkspace.startsWith("..") || path18.isAbsolute(relToWorkspace)) {
10763
- relToWorkspace = path18.basename(canonicalPath);
11330
+ let relToWorkspace = path19.relative(this.workspaceRoot, canonicalPath);
11331
+ if (relToWorkspace.startsWith("..") || path19.isAbsolute(relToWorkspace)) {
11332
+ relToWorkspace = path19.basename(canonicalPath);
10764
11333
  }
10765
11334
  if (this.checkSensitiveRelative(relToWorkspace)) {
10766
11335
  return {
10767
11336
  approved: false,
10768
11337
  code: "path_not_approved",
10769
- reason: `Sensitive path denied: ${relToWorkspace.split(path18.sep).join("/")}`
11338
+ reason: `Sensitive path denied: ${relToWorkspace.split(path19.sep).join("/")}`
10770
11339
  };
10771
11340
  }
10772
11341
  return null;
@@ -10775,7 +11344,7 @@ class WorkspaceReadBroker {
10775
11344
  const auth = this.authorizePath(targetPath);
10776
11345
  if (!auth.approved)
10777
11346
  return auth;
10778
- const lexicalResolved = path18.isAbsolute(targetPath) ? path18.resolve(targetPath) : path18.resolve(this.workspaceRoot, targetPath);
11347
+ const lexicalResolved = path19.isAbsolute(targetPath) ? path19.resolve(targetPath) : path19.resolve(this.workspaceRoot, targetPath);
10779
11348
  const readDenial = this.authorizeRead(lexicalResolved, auth.canonicalPath);
10780
11349
  if (readDenial !== null)
10781
11350
  return readDenial;
@@ -10832,7 +11401,7 @@ class WorkspaceReadBroker {
10832
11401
  this.aggregateBytes = 0;
10833
11402
  }
10834
11403
  authorizePath(candidatePath) {
10835
- const resolvedPath = path18.isAbsolute(candidatePath) ? path18.resolve(candidatePath) : path18.resolve(this.workspaceRoot, candidatePath);
11404
+ const resolvedPath = path19.isAbsolute(candidatePath) ? path19.resolve(candidatePath) : path19.resolve(this.workspaceRoot, candidatePath);
10836
11405
  const canonical = resolveCanonicalPath(resolvedPath);
10837
11406
  if (!canonical) {
10838
11407
  return {
@@ -10876,7 +11445,7 @@ class WorkspaceReadBroker {
10876
11445
  };
10877
11446
  }
10878
11447
  i++;
10879
- const nextResolved = path18.isAbsolute(target) ? path18.resolve(target) : path18.resolve(currentDir, target);
11448
+ const nextResolved = path19.isAbsolute(target) ? path19.resolve(target) : path19.resolve(currentDir, target);
10880
11449
  const canonical = resolveCanonicalPath(nextResolved);
10881
11450
  if (!canonical || !isInsideRoot(canonical, this.canonicalRoot)) {
10882
11451
  return {
@@ -10925,33 +11494,36 @@ class WorkspaceReadBroker {
10925
11494
  // src/transport-registry.ts
10926
11495
  import { readFile as readFile4 } from "fs/promises";
10927
11496
  import os2 from "os";
10928
- import path20 from "path";
11497
+ import path21 from "path";
10929
11498
  import { pathToFileURL } from "url";
11499
+ init_routing();
10930
11500
  init_assets();
10931
11501
  init_home_preflight();
10932
11502
 
10933
11503
  // src/runner-authority.ts
10934
- import { existsSync as existsSync10 } from "fs";
11504
+ init_crysk_secrets();
11505
+ import { existsSync as existsSync11 } from "fs";
10935
11506
  import { readFile as readFile2, realpath as realpath2 } from "fs/promises";
10936
- import path19 from "path";
11507
+ import path20 from "path";
11508
+ init_routing();
10937
11509
  var OPENCODE_BINARY_NAME = "opencode";
10938
11510
  async function resolveOpenCodeCanonicalBinary(lookup, deps = {}) {
10939
- const exists = deps.existsFn ?? existsSync10;
11511
+ const exists = deps.existsFn ?? existsSync11;
10940
11512
  const toRealpath = deps.realpathFn ?? realpath2;
10941
11513
  const readBytes = deps.readFileFn ?? ((p) => readFile2(p));
10942
11514
  let candidate;
10943
11515
  if (lookup.binaryPath !== undefined) {
10944
- if (!path19.isAbsolute(lookup.binaryPath)) {
11516
+ if (!path20.isAbsolute(lookup.binaryPath)) {
10945
11517
  return {
10946
11518
  error: `binary override must be an absolute path: ${lookup.binaryPath}`
10947
11519
  };
10948
11520
  }
10949
11521
  candidate = lookup.binaryPath;
10950
11522
  } else {
10951
- const searchDirs = (lookup.env?.PATH ?? process.env.PATH ?? "").split(path19.delimiter).filter((dir) => dir.length > 0);
11523
+ const searchDirs = (lookup.env?.PATH ?? process.env.PATH ?? "").split(path20.delimiter).filter((dir) => dir.length > 0);
10952
11524
  candidate = "";
10953
11525
  for (const dir of searchDirs) {
10954
- const probe = path19.join(dir, OPENCODE_BINARY_NAME);
11526
+ const probe = path20.join(dir, OPENCODE_BINARY_NAME);
10955
11527
  if (exists(probe)) {
10956
11528
  candidate = probe;
10957
11529
  break;
@@ -10974,7 +11546,7 @@ async function resolveOpenCodeCanonicalBinary(lookup, deps = {}) {
10974
11546
  }
10975
11547
  }
10976
11548
  function claudeCredentialBroker() {
10977
- return process.platform === "darwin" && existsSync10("/usr/bin/security") ? new KeychainCredentialBroker : undefined;
11549
+ return process.platform === "darwin" && existsSync11("/usr/bin/security") ? new KeychainCredentialBroker : undefined;
10978
11550
  }
10979
11551
  async function verifyConfiguredExecutable(backend, candidatePath, options, deps = {}) {
10980
11552
  const configuredAllowlist = options.executableAllowlists?.[backend];
@@ -11023,7 +11595,7 @@ async function withOpenCodeDiscoveryAllowlist(options, deps = {}) {
11023
11595
  }
11024
11596
  function planUsesBackend(plan, backend) {
11025
11597
  const seen = new Set;
11026
- for (const step of plan.steps) {
11598
+ for (const step of planRoutes(plan)) {
11027
11599
  if (!seen.has(step.route.backend)) {
11028
11600
  seen.add(step.route.backend);
11029
11601
  if (step.route.backend === backend) {
@@ -11070,11 +11642,16 @@ async function withClaudeDiscoveryAllowlist(options, deps = {}) {
11070
11642
  }
11071
11643
  };
11072
11644
  }
11073
- function credentialKindForRoute(backend, provider, env = {}, hasBroker = false) {
11645
+ function credentialKindForRoute(backend, provider, env = {}, hasBroker = false, openCodeSecretNames) {
11074
11646
  if (backend === "claude-code") {
11075
11647
  return !hasBroker && envBillsMetered(env) ? "provider_api_token" : "claude_subscription_oauth";
11076
11648
  }
11077
11649
  if (backend === "opencode") {
11650
+ const choice = openCodeSecretNames === undefined ? undefined : chooseOpenCodeSecret(provider, openCodeSecretNames);
11651
+ if (choice?.kind === "api_key")
11652
+ return "provider_api_token";
11653
+ if (choice?.kind === "oauth")
11654
+ return "opencode_chatgpt_oauth";
11078
11655
  return provider === OPENCODE_OAUTH_PROVIDER ? "opencode_chatgpt_oauth" : "provider_api_token";
11079
11656
  }
11080
11657
  throw new Error(`No credential authority is bound for backend "${backend}"`);
@@ -11091,6 +11668,21 @@ function openCodeCredentialBrokerForKind(kind, provider) {
11091
11668
  }
11092
11669
  return new OpenCodeAuthBroker;
11093
11670
  }
11671
+ function createOpenCodeBrokerPool(make = openCodeCredentialBrokerForKind) {
11672
+ const brokers = new Map;
11673
+ return (kind, provider) => {
11674
+ const key = JSON.stringify([kind, provider]);
11675
+ let broker = brokers.get(key);
11676
+ if (broker === undefined) {
11677
+ broker = make(kind, provider);
11678
+ brokers.set(key, broker);
11679
+ }
11680
+ return broker;
11681
+ };
11682
+ }
11683
+ function openCodeBrokerForRoute(options, kind, provider) {
11684
+ return options.credentialBrokers?.opencode ?? options.openCodeBrokerFor?.(kind, provider) ?? openCodeCredentialBrokerForKind(kind, provider);
11685
+ }
11094
11686
  async function resolveBindingAuthority(backend, provider, options, deps = {}) {
11095
11687
  if (backend === "claude-code") {
11096
11688
  const resolved = await resolveClaudeCanonicalBinary(options, deps);
@@ -11101,7 +11693,7 @@ async function resolveBindingAuthority(backend, provider, options, deps = {}) {
11101
11693
  if ("error" in verified) {
11102
11694
  return { error: verified.error };
11103
11695
  }
11104
- const broker = options.credentialBrokers?.["claude-code"] ?? claudeCredentialBroker();
11696
+ const broker = options.claudeCredential === "api_key" ? undefined : options.credentialBrokers?.["claude-code"] ?? claudeCredentialBroker();
11105
11697
  const credentialKind = credentialKindForRoute(backend, provider, options.env ?? process.env, broker !== undefined);
11106
11698
  const metered = credentialKindBillsMetered(credentialKind);
11107
11699
  return {
@@ -11130,7 +11722,7 @@ async function resolveBindingAuthority(backend, provider, options, deps = {}) {
11130
11722
  if ("error" in verified) {
11131
11723
  return { error: verified.error };
11132
11724
  }
11133
- const credentialKind = credentialKindForRoute(backend, provider);
11725
+ const credentialKind = credentialKindForRoute(backend, provider, {}, false, options.openCodeSecretNames);
11134
11726
  return {
11135
11727
  binding: {
11136
11728
  backend,
@@ -11140,7 +11732,7 @@ async function resolveBindingAuthority(backend, provider, options, deps = {}) {
11140
11732
  executableAllowlist: verified.allowlist,
11141
11733
  credentialKind,
11142
11734
  credentialRef: `opencode-auth:${provider}`,
11143
- credentialBroker: options.credentialBrokers?.opencode ?? openCodeCredentialBrokerForKind(credentialKind, provider),
11735
+ credentialBroker: openCodeBrokerForRoute(options, credentialKind, provider),
11144
11736
  bucketId: "opencode"
11145
11737
  }
11146
11738
  };
@@ -11164,7 +11756,8 @@ async function resolveRunnerAuthority(options, deps = {}) {
11164
11756
  binaryPath: binding.binaryPath,
11165
11757
  workspaceRoot: binding.workspaceRoot,
11166
11758
  executableAllowlist: binding.executableAllowlist,
11167
- ...binding.credentialBroker ? { credentialBroker: binding.credentialBroker } : {}
11759
+ ...binding.credentialBroker ? { credentialBroker: binding.credentialBroker } : {},
11760
+ ...options.env === undefined ? {} : { childEnv: options.env }
11168
11761
  }
11169
11762
  };
11170
11763
  }
@@ -11181,7 +11774,7 @@ init_routing();
11181
11774
  // src/execution/bucket-id.ts
11182
11775
  init_home_preflight();
11183
11776
  import { createHmac, randomBytes as nodeRandomBytes } from "crypto";
11184
- import { existsSync as existsSync11, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
11777
+ import { existsSync as existsSync12, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
11185
11778
  var UNKNOWN_SCOPE_SENTINEL = "unknown";
11186
11779
  var BUCKET_KEY_BYTES = 32;
11187
11780
  function encodeField(value) {
@@ -11204,7 +11797,7 @@ function deriveBucketId(input, localKey) {
11204
11797
  return createHmac("sha256", localKey).update(bucketIdentityMessage(input)).digest("hex");
11205
11798
  }
11206
11799
  function loadOrCreateBucketKey(home, deps = {}) {
11207
- const exists = deps.existsFn ?? existsSync11;
11800
+ const exists = deps.existsFn ?? existsSync12;
11208
11801
  const readBytes = deps.readFileFn ?? ((p) => readFileSync5(p));
11209
11802
  const writeBytes = deps.writeFileFn ?? ((p, data) => writeFileSync3(p, data, { mode: 384, flag: "wx" }));
11210
11803
  const mkdir = deps.mkdirFn ?? ((p) => mkdirSync4(p, { recursive: true }));
@@ -11530,7 +12123,9 @@ class ClaudeCodeCliTransport {
11530
12123
  if (request.mcpConfigPath) {
11531
12124
  args.push("--mcp-config", request.mcpConfigPath, "--strict-mcp-config");
11532
12125
  }
11533
- args.push("--setting-sources", "", "--tools", request.tools.join(","), "--permission-mode", "bypassPermissions", "--model", spawnModelForClaudeCli(request.route, request.executionModel), "--effort", request.effort, "--exclude-dynamic-system-prompt-sections");
12126
+ args.push("--setting-sources", "", "--tools", request.tools.join(","), "--permission-mode", "bypassPermissions", "--model", claudeCliModel(request.route), "--effort", request.effort, "--exclude-dynamic-system-prompt-sections");
12127
+ const claudeSessionId = newClaudeSessionId();
12128
+ args.push("--session-id", claudeSessionId);
11534
12129
  const start = performance.now();
11535
12130
  const promptDenial = await this.verifyPromptIntegrity(request);
11536
12131
  if (promptDenial !== undefined) {
@@ -11562,6 +12157,7 @@ class ClaudeCodeCliTransport {
11562
12157
  };
11563
12158
  }
11564
12159
  ACTIVE_CHILD_PROCS.add(proc);
12160
+ retainClaudeSession(request, claudeSessionId);
11565
12161
  let cascadePromise;
11566
12162
  let provenPgid;
11567
12163
  let notifyCascadeStart = () => {};
@@ -15228,7 +15824,7 @@ async function launchProjectedOpenCodeServer(options) {
15228
15824
  var OPENCODE_SDK_PACKAGE_SPECIFIER = "@opencode-ai/sdk/package.json";
15229
15825
  var OPENCODE_SDK_V2_SPECIFIER = "@opencode-ai/sdk/v2/client";
15230
15826
  function openCodeSdkPackageJsonPath(nodeModulesDir) {
15231
- return path20.join(nodeModulesDir, "@opencode-ai", "sdk", "package.json");
15827
+ return path21.join(nodeModulesDir, "@opencode-ai", "sdk", "package.json");
15232
15828
  }
15233
15829
  function createDynamicImport() {
15234
15830
  return new Function("specifier", "return import(specifier)");
@@ -15277,7 +15873,7 @@ function resolveOpenCodeSdkV2Entry(packageJson, packageDir) {
15277
15873
  if (relative === undefined) {
15278
15874
  throw new OpenCodeSdkUnavailableError(openCodeSdkUnavailableMessage());
15279
15875
  }
15280
- return pathToFileURL(path20.resolve(packageDir, relative)).href;
15876
+ return pathToFileURL(path21.resolve(packageDir, relative)).href;
15281
15877
  }
15282
15878
  function readOpenCodeV2Export(exportsField) {
15283
15879
  if (typeof exportsField !== "object" || exportsField === null || Array.isArray(exportsField)) {
@@ -15342,7 +15938,7 @@ async function readOpenCodeSdkPackage(options, dynamicImport) {
15342
15938
  return {
15343
15939
  version: packageJson.version,
15344
15940
  packageJson,
15345
- packageDir: plan.packageJsonPath !== undefined ? path20.dirname(plan.packageJsonPath) : "",
15941
+ packageDir: plan.packageJsonPath !== undefined ? path21.dirname(plan.packageJsonPath) : "",
15346
15942
  plan
15347
15943
  };
15348
15944
  }
@@ -15711,7 +16307,7 @@ async function admitRoutePlan(plan, registryOrCapabilities, optionsOrRegistry, m
15711
16307
  }
15712
16308
  const reports = new Map;
15713
16309
  const mode = options.mode ?? "production";
15714
- for (const step of plan.steps) {
16310
+ for (const step of planRoutes(plan)) {
15715
16311
  const backend = step.route.backend;
15716
16312
  if (!registry.has(backend)) {
15717
16313
  throw new RouteAdmissionError(redactDiagnostic(`Step "${step.stepKey}" route backend "${backend}" is not registered`));
@@ -15824,8 +16420,8 @@ function sumUsage(a, b) {
15824
16420
  // src/execution/attempt-evidence.ts
15825
16421
  import { createHash as createHash8 } from "crypto";
15826
16422
  init_evidence_redaction();
15827
- import { mkdir as mkdir5, readFile as readFile5, realpath as realpath3 } from "fs/promises";
15828
- import path21 from "path";
16423
+ import { mkdir as mkdir6, readFile as readFile5, realpath as realpath3 } from "fs/promises";
16424
+ import path22 from "path";
15829
16425
  var evidenceSha256 = (value) => createHash8("sha256").update(value).digest("hex");
15830
16426
  function parseCaptureWrapper(redactedJson) {
15831
16427
  let value;
@@ -15894,7 +16490,7 @@ async function persistAttemptEvidence(step, request, execution) {
15894
16490
  }
15895
16491
  if (evidence.delivered) {
15896
16492
  evidence.outputSha256 = evidenceSha256(await readFile5(step.outPath));
15897
- evidence.outputPath = path21.basename(step.outPath);
16493
+ evidence.outputPath = path22.basename(step.outPath);
15898
16494
  }
15899
16495
  const capture = outcome?.diagnosticEvidence;
15900
16496
  if (capture) {
@@ -15938,14 +16534,14 @@ async function persistAttemptEvidence(step, request, execution) {
15938
16534
  };
15939
16535
  } else {
15940
16536
  const captureFile = file.replace(/\.json$/, ".capture.json");
15941
- await mkdir5(path21.dirname(file), { recursive: true });
16537
+ await mkdir6(path22.dirname(file), { recursive: true });
15942
16538
  await writeJsonAtomically(captureFile, safe, { compact: true });
15943
16539
  const bytes = await readFile5(captureFile);
15944
16540
  evidence.capture = {
15945
16541
  schema: capture.schema,
15946
16542
  status: capture.status,
15947
16543
  sha256: evidenceSha256(bytes),
15948
- relativePath: path21.basename(captureFile)
16544
+ relativePath: path22.basename(captureFile)
15949
16545
  };
15950
16546
  }
15951
16547
  } catch (error) {
@@ -15957,7 +16553,7 @@ async function persistAttemptEvidence(step, request, execution) {
15957
16553
  }
15958
16554
  }
15959
16555
  }
15960
- await mkdir5(path21.dirname(file), { recursive: true });
16556
+ await mkdir6(path22.dirname(file), { recursive: true });
15961
16557
  await writeJsonAtomically(file, redactEvidence(evidence));
15962
16558
  }
15963
16559
  async function freezeAttemptEvidenceIdentity(request, step) {
@@ -15987,16 +16583,16 @@ async function freezeAttemptEvidenceIdentity(request, step) {
15987
16583
  route: request.route,
15988
16584
  systemPromptSha256: request.systemPromptSha256,
15989
16585
  userPromptSha256: evidenceSha256(request.userPrompt),
15990
- systemPromptPath: path21.relative(path21.dirname(file), step.systemPromptPath),
16586
+ systemPromptPath: path22.relative(path22.dirname(file), step.systemPromptPath),
15991
16587
  toolNames: [...request.tools],
15992
16588
  effort: request.effort,
15993
- effortApplied: request.route.backend === "claude-code",
16589
+ effortApplied: effortApplied(request.route),
15994
16590
  ...frozen
15995
16591
  };
15996
- await mkdir5(path21.dirname(file), { recursive: true });
16592
+ await mkdir6(path22.dirname(file), { recursive: true });
15997
16593
  await writeJsonAtomically(file, plan);
15998
16594
  frozen.requestPlan = {
15999
- relativePath: path21.basename(file),
16595
+ relativePath: path22.basename(file),
16000
16596
  sha256: evidenceSha256(await readFile5(file))
16001
16597
  };
16002
16598
  })();
@@ -16122,28 +16718,6 @@ class ConcurrencyLimiter {
16122
16718
  }
16123
16719
  }
16124
16720
 
16125
- // src/execution/contracts.ts
16126
- var TRANSPORT_FAILURE_CAUSE_LOOKUP = {
16127
- auth_invalid: true,
16128
- quota_exhausted: true,
16129
- rate_limit: true,
16130
- network_transient: true,
16131
- protocol_truncation: true,
16132
- protocol_mismatch: true,
16133
- protocol_overflow: true,
16134
- output_limit_exceeded: true,
16135
- context_window_exceeded: true,
16136
- safety_refusal: true,
16137
- provider_configuration_invalid: true,
16138
- model_unavailable: true,
16139
- missing_provider_record: true,
16140
- runtime_unavailable: true,
16141
- remote_abort_unconfirmed: true
16142
- };
16143
- function isTransportFailureCause(value) {
16144
- return typeof value === "string" && Object.hasOwn(TRANSPORT_FAILURE_CAUSE_LOOKUP, value);
16145
- }
16146
-
16147
16721
  // src/execution/failure-policy.ts
16148
16722
  var DEFAULT_MAX_TRANSIENT_ATTEMPTS = 3;
16149
16723
  var DEFAULT_MAX_RETRY_AFTER_DELAY_MS = 60000;
@@ -16609,9 +17183,22 @@ var PROJECTION_WARNING_ANNOTATION = /^\[pr-hero\] credential projection unavaila
16609
17183
  function projectionWarningAnnotation(failureClass) {
16610
17184
  return `[pr-hero] credential projection unavailable (${failureClass}); child runs with operator environment`;
16611
17185
  }
17186
+ function copyClaudeSessionTrace(step, request, attempt) {
17187
+ return copyRetainedClaudeSession(request, claudeSessionTracePath(step.outPath, step.name, attempt)).catch(() => "session trace write failed");
17188
+ }
17189
+ async function withClaudeSessionTrace(step, request, attempt, outcome) {
17190
+ const reason = await copyClaudeSessionTrace(step, request, attempt);
17191
+ if (reason === undefined)
17192
+ return outcome;
17193
+ return {
17194
+ ...outcome,
17195
+ stderrTail: `${outcome.stderrTail}
17196
+ ${claudeTraceCaptureAnnotation(reason)}`
17197
+ };
17198
+ }
16612
17199
  function isHarnessStderrAnnotation(line) {
16613
17200
  const trimmed = line.trim();
16614
- return trimmed === DESTROY_FAILED_ANNOTATION || trimmed === AMBIENT_METERED_ANNOTATION || PROJECTION_WARNING_ANNOTATION.test(trimmed);
17201
+ return trimmed === DESTROY_FAILED_ANNOTATION || trimmed === AMBIENT_METERED_ANNOTATION || PROJECTION_WARNING_ANNOTATION.test(trimmed) || CLAUDE_TRACE_MISSES.some((reason) => trimmed === claudeTraceCaptureAnnotation(reason));
16615
17202
  }
16616
17203
  function receiptPathFor(step, attempt) {
16617
17204
  return settlementReceiptPath(step.outPath, step.name, attempt);
@@ -16625,7 +17212,7 @@ function formatRetryReminder(parseError) {
16625
17212
  }
16626
17213
  async function writeAttemptLog(step, attempt, kind, outcome, classification, cause, rejection) {
16627
17214
  const logPath = attemptLogPath(step.outPath, step.name, attempt);
16628
- await mkdir6(path22.dirname(logPath), { recursive: true });
17215
+ await mkdir7(path23.dirname(logPath), { recursive: true });
16629
17216
  await Bun.write(logPath, [
16630
17217
  `step: ${step.name}`,
16631
17218
  `attempt: ${attempt}`,
@@ -16715,6 +17302,16 @@ class StepExecutionHarness {
16715
17302
  }
16716
17303
  async run(step) {
16717
17304
  let canonicalCwd = step.cwd;
17305
+ if (step.fallbackRoutes !== undefined && step.fallbackRoutes.length > 0) {
17306
+ return {
17307
+ name: step.name,
17308
+ status: "failed",
17309
+ usage: zeroUsage(),
17310
+ attempts: 0,
17311
+ stderrTail: `Step "${step.name}" lists ${step.fallbackRoutes.length} fallback model(s), and this runner runs one model per step; run it through a runner that tries fallbacks (MultiProviderRunner, ClaudeCodeRunner)`,
17312
+ resultText: ""
17313
+ };
17314
+ }
16718
17315
  const effectiveBackend = step.route?.backend ?? step.backend ?? "claude-code";
16719
17316
  let transport;
16720
17317
  if (this.explicitTransport !== undefined) {
@@ -17169,7 +17766,7 @@ ${line}`;
17169
17766
  finalText: "",
17170
17767
  usage: normalizeUnavailableUsage({
17171
17768
  wallMs: harnessWatchdogMs ?? 0,
17172
- billingMode: transport.billingMode
17769
+ billingMode: transport.backend === "claude-code" ? envBillsMetered(this.projectedEnv) ? "metered" : "subscription" : transport.billingMode
17173
17770
  }),
17174
17771
  stderrTail: `Step timed out after ${harnessWatchdogMs}ms`,
17175
17772
  timedOut: true
@@ -17318,6 +17915,9 @@ ${line}`;
17318
17915
  let attempts = 0;
17319
17916
  let lastOutcome;
17320
17917
  let lastFailureCause;
17918
+ let lastCause;
17919
+ let spendFenced = false;
17920
+ const attemptOffset = step.attemptOffset ?? 0;
17321
17921
  let cancelHit = false;
17322
17922
  const reservations = [];
17323
17923
  let reserveToken = beginStep();
@@ -17335,9 +17935,10 @@ ${line}`;
17335
17935
  }
17336
17936
  attempts++;
17337
17937
  const kind = pendingFormatPrompt === undefined ? "attempt" : "format-retry";
17938
+ const attemptNumber = attemptOffset + attempts;
17338
17939
  const request = {
17339
- sessionId: `${step.name}-${Date.now()}-${attempts}`,
17340
- attempt: attempts,
17940
+ sessionId: `${step.name}-${Date.now()}-${attemptNumber}`,
17941
+ attempt: attemptNumber,
17341
17942
  executionModel: step.model,
17342
17943
  effort: step.effort,
17343
17944
  route: step.route ?? (transport.defaultRoute ? {
@@ -17366,7 +17967,7 @@ ${line}`;
17366
17967
  credentialProjectionId: fallbackCredentialProjectionId,
17367
17968
  env: childEnv,
17368
17969
  syntheticHome: childEnv.HOME ?? "",
17369
- syntheticConfigHome: childEnv.CLAUDE_CONFIG_DIR ?? path22.join(childEnv.HOME ?? "", ".claude"),
17970
+ syntheticConfigHome: childEnv.CLAUDE_CONFIG_DIR ?? path23.join(childEnv.HOME ?? "", ".claude"),
17370
17971
  syntheticTmp: childEnv.TMPDIR ?? "",
17371
17972
  verifiedBinaryPath
17372
17973
  }
@@ -17374,7 +17975,7 @@ ${line}`;
17374
17975
  pendingFormatPrompt = undefined;
17375
17976
  const attemptResult = await this.runAttempt({
17376
17977
  step,
17377
- attempt: attempts,
17978
+ attempt: attemptNumber,
17378
17979
  kind,
17379
17980
  request,
17380
17981
  deadlineMs,
@@ -17406,6 +18007,11 @@ ${line}`;
17406
18007
  };
17407
18008
  }
17408
18009
  lastFailureCause = attemptResult.resolution.kind === "cause" && isTransportFailureCause(attemptResult.resolution.cause) ? attemptResult.resolution.cause : undefined;
18010
+ if (attemptResult.fenced === true) {
18011
+ spendFenced = true;
18012
+ } else {
18013
+ lastCause = attemptResult.resolution.kind === "cause" ? attemptResult.resolution.cause : undefined;
18014
+ }
17409
18015
  if (attemptResult.resolution.kind === "legacy_terminal") {
17410
18016
  break;
17411
18017
  }
@@ -17449,7 +18055,7 @@ ${line}`;
17449
18055
  break;
17450
18056
  }
17451
18057
  if (cancelHit) {
17452
- const receiptPointer = attempts >= 1 ? `see ${receiptPathFor(step, attempts)}` : "no attempt was admitted, so no receipt was written";
18058
+ const receiptPointer = attempts >= 1 ? `see ${receiptPathFor(step, attemptOffset + attempts)}` : "no attempt was admitted, so no receipt was written";
17453
18059
  return {
17454
18060
  name: step.name,
17455
18061
  status: "failed",
@@ -17473,6 +18079,8 @@ ${line}`;
17473
18079
  attempts,
17474
18080
  ...reservations.length === 0 ? {} : { reservations },
17475
18081
  ...lastFailureCause === undefined ? {} : { failureCause: lastFailureCause },
18082
+ ...lastCause === undefined ? {} : { finalCause: lastCause },
18083
+ ...spendFenced ? { spendFenced: true } : {},
17476
18084
  ...lastOutcome?.failureDetail === undefined ? {} : { failureDetail: lastOutcome.failureDetail },
17477
18085
  ...lastOutcome?.failureCredential === undefined ? {} : { failureCredential: lastOutcome.failureCredential },
17478
18086
  stderrTail: lastOutcome?.stderrTail ?? "",
@@ -17590,7 +18198,8 @@ ${line}`;
17590
18198
  usage: normalizeUnavailableUsage({ wallMs: 0 }),
17591
18199
  stderrTail: error.message
17592
18200
  },
17593
- resolution: { kind: "legacy_terminal" }
18201
+ resolution: { kind: "legacy_terminal" },
18202
+ fenced: true
17594
18203
  };
17595
18204
  }
17596
18205
  throw error;
@@ -17745,9 +18354,10 @@ ${line}`;
17745
18354
  this.attemptAdmissionGate?.reportUnconfirmedRemote?.(this.rateLimitBucketId);
17746
18355
  }
17747
18356
  if (execution.cancelled) {
18357
+ await copyClaudeSessionTrace(step, request, attempt);
17748
18358
  return { kind: "cancelled" };
17749
18359
  }
17750
- const outcome = execution.outcome;
18360
+ const outcome = await withClaudeSessionTrace(step, request, attempt, execution.outcome);
17751
18361
  if (execution.delivery?.delivered) {
17752
18362
  return { kind: "delivered", outcome, parsed: execution.delivery.parsed };
17753
18363
  }
@@ -17773,6 +18383,135 @@ function completionToStatus(outcome) {
17773
18383
  return outcome.completion === "success" ? "completed" : outcome.completion;
17774
18384
  }
17775
18385
 
18386
+ // src/execution/model-fallback.ts
18387
+ var PROVIDER_FAILURES = new Set([
18388
+ "rate_limit",
18389
+ "quota_exhausted",
18390
+ "network_transient",
18391
+ "protocol_truncation",
18392
+ "watchdog_timeout",
18393
+ "model_unavailable"
18394
+ ]);
18395
+ function fallbackMove(cause) {
18396
+ if (cause === undefined)
18397
+ return "stop";
18398
+ if (cause === "auth_invalid")
18399
+ return "next_credential";
18400
+ return PROVIDER_FAILURES.has(cause) ? "next" : "stop";
18401
+ }
18402
+ function ranRoute(result) {
18403
+ return result.modelAttempts?.findLast((entry) => entry.status !== "skipped")?.route;
18404
+ }
18405
+ async function runWithFallback(input) {
18406
+ const { step } = input;
18407
+ const fallbacks = step.fallbackRoutes ?? [];
18408
+ if (step.route === undefined || fallbacks.length === 0) {
18409
+ return input.runOn(step);
18410
+ }
18411
+ const candidates = [step.route, ...fallbacks];
18412
+ const effortOf = (index) => index === 0 ? step.effort : step.fallbackEfforts?.[index - 1] ?? step.effort;
18413
+ const modelAttempts = [];
18414
+ const results = [];
18415
+ const refusedCredentials = new Set;
18416
+ let attemptsSoFar = 0;
18417
+ for (const [index, route] of candidates.entries()) {
18418
+ if (index > 0 && input.cancelled())
18419
+ break;
18420
+ const credential = input.credentialOf(route);
18421
+ if (credential !== undefined && refusedCredentials.has(credential)) {
18422
+ modelAttempts.push({
18423
+ route,
18424
+ status: "skipped",
18425
+ attempts: 0,
18426
+ effort: effortOf(index),
18427
+ cause: "auth_invalid"
18428
+ });
18429
+ continue;
18430
+ }
18431
+ const {
18432
+ fallbackRoutes: _list,
18433
+ fallbackEfforts: _efforts,
18434
+ routeKey: _key,
18435
+ ...single
18436
+ } = step;
18437
+ const result = await input.runOn({
18438
+ ...single,
18439
+ route,
18440
+ effort: effortOf(index),
18441
+ ...index === 0 && step.routeKey !== undefined ? { routeKey: step.routeKey } : {},
18442
+ ...attemptsSoFar === 0 ? {} : { attemptOffset: attemptsSoFar },
18443
+ ...index === 0 ? {} : { model: route.modelSnapshot || step.model }
18444
+ });
18445
+ const reached = reachedAttempts(result);
18446
+ attemptsSoFar += reached;
18447
+ results.push(result);
18448
+ if (reached === 0) {
18449
+ modelAttempts.push({
18450
+ route,
18451
+ status: "skipped",
18452
+ attempts: 0,
18453
+ effort: effortOf(index)
18454
+ });
18455
+ if (result.spendFenced === true)
18456
+ continue;
18457
+ break;
18458
+ }
18459
+ modelAttempts.push({
18460
+ route,
18461
+ status: result.status,
18462
+ attempts: reached,
18463
+ effort: effortOf(index),
18464
+ ...result.status === "ok" || result.finalCause === undefined ? {} : { cause: result.finalCause },
18465
+ ...result.usageV2 === undefined ? {} : { usageV2: result.usageV2 }
18466
+ });
18467
+ if (result.status === "ok")
18468
+ break;
18469
+ const move = fallbackMove(result.finalCause);
18470
+ if (move === "stop")
18471
+ break;
18472
+ if (move === "next_credential") {
18473
+ if (credential === undefined)
18474
+ break;
18475
+ refusedCredentials.add(credential);
18476
+ }
18477
+ }
18478
+ return mergeResults(results, modelAttempts, attemptsSoFar);
18479
+ }
18480
+ function reachedAttempts(result) {
18481
+ return result.attempts - (result.spendFenced === true ? 1 : 0);
18482
+ }
18483
+ function mergeResults(results, modelAttempts, attempts) {
18484
+ const ranIndex = results.findLastIndex((result) => reachedAttempts(result) > 0);
18485
+ const reported = ranIndex === -1 ? results.length - 1 : ranIndex;
18486
+ const last = results[reported];
18487
+ const notRun = results.slice(reported + 1).map((result) => result.stderrTail.trim()).filter((tail) => tail.length > 0);
18488
+ let usageV2;
18489
+ for (const result of results) {
18490
+ if (result.usageV2 === undefined)
18491
+ continue;
18492
+ usageV2 = usageV2 === undefined ? result.usageV2 : sumNormalizedUsage(usageV2, result.usageV2);
18493
+ }
18494
+ const reservations = results.flatMap((result) => result.reservations ?? []);
18495
+ const {
18496
+ usageV2: _lastUsage,
18497
+ reservations: _lastReservations,
18498
+ spendFenced: _lastFenced,
18499
+ ...outcome
18500
+ } = last;
18501
+ return {
18502
+ ...outcome,
18503
+ ...notRun.length === 0 ? {} : {
18504
+ stderrTail: [outcome.stderrTail, ...notRun].filter((tail) => tail.length > 0).join(`
18505
+ `)
18506
+ },
18507
+ usage: usageV2 !== undefined ? projectLegacyUsage(usageV2) : results.map((result) => result.usage).reduce(sumUsage),
18508
+ ...usageV2 === undefined ? {} : { usageV2 },
18509
+ ...reservations.length === 0 ? {} : { reservations },
18510
+ attempts,
18511
+ modelAttempts
18512
+ };
18513
+ }
18514
+
17776
18515
  // src/review/pipeline.ts
17777
18516
  init_evidence_redaction();
17778
18517
  init_redact();
@@ -17892,7 +18631,9 @@ function buildStepArgv(step) {
17892
18631
 
17893
18632
  class ClaudeCodeRunner {
17894
18633
  harness;
18634
+ signal;
17895
18635
  constructor(options = {}) {
18636
+ this.signal = options.signal;
17896
18637
  this.harness = new StepExecutionHarness({
17897
18638
  workspaceRoot: options.workspaceRoot,
17898
18639
  executableAllowlist: options.executableAllowlist,
@@ -17907,7 +18648,12 @@ class ClaudeCodeRunner {
17907
18648
  });
17908
18649
  }
17909
18650
  async run(step) {
17910
- return this.harness.run(step);
18651
+ return runWithFallback({
18652
+ step,
18653
+ runOn: (single) => this.harness.run(single),
18654
+ credentialOf: (route) => route.backend === "claude-code" ? "claude-code" : undefined,
18655
+ cancelled: () => this.signal?.aborted === true
18656
+ });
17911
18657
  }
17912
18658
  }
17913
18659
 
@@ -17957,7 +18703,7 @@ function makeProofRefResolver(worktree, patch) {
17957
18703
  const cached = memo.get(candidate);
17958
18704
  if (cached !== undefined)
17959
18705
  return cached;
17960
- let resolved = named.has(candidate) || existsSync12(path23.join(worktree, candidate));
18706
+ let resolved = named.has(candidate) || existsSync13(path24.join(worktree, candidate));
17961
18707
  if (!resolved && !candidate.includes("/")) {
17962
18708
  baseNames ??= treeBaseNames(worktree, named);
17963
18709
  if (baseNames === undefined) {
@@ -17974,11 +18720,11 @@ function treeBaseNames(worktree, named) {
17974
18720
  if (listed === undefined)
17975
18721
  return;
17976
18722
  const paths = [...named, ...listed];
17977
- return new Set(paths.filter(Boolean).map((p) => path23.posix.basename(p)));
18723
+ return new Set(paths.filter(Boolean).map((p) => path24.posix.basename(p)));
17978
18724
  }
17979
18725
  function pathsHaveBaseName(paths, name) {
17980
18726
  for (const p of paths)
17981
- if (path23.posix.basename(p) === name)
18727
+ if (path24.posix.basename(p) === name)
17982
18728
  return true;
17983
18729
  return false;
17984
18730
  }
@@ -18243,18 +18989,17 @@ async function execute(input, deps, state) {
18243
18989
  }
18244
18990
  const reviewSpec = validateReviewSpec(input.spec ?? defaultReviewSpec());
18245
18991
  state.refuterConfigured = reviewSpec.agents.some((a) => a.role === "refuter");
18246
- const effectiveRoutingConfig = input.routingConfig ?? input.config?.effective?.routing;
18992
+ const effectiveModels = input.models ?? input.config?.effective?.models;
18247
18993
  const frontmatterByKey = new Map;
18248
18994
  for (const agent of reviewSpec.agents) {
18249
18995
  try {
18250
- const parsed = await parseAgentFile(path23.join(input.agentsDir, agent.file));
18996
+ const parsed = await parseAgentFile(path24.join(input.agentsDir, agent.file));
18251
18997
  frontmatterByKey.set(agent.key, parsed.model);
18252
18998
  } catch {}
18253
18999
  }
18254
19000
  let diversityCtx = prepareDiversityExecution({
18255
19001
  reviewSpec,
18256
19002
  cliModel: input.model,
18257
- routingConfig: effectiveRoutingConfig,
18258
19003
  frontmatterModel: (agentKey) => frontmatterByKey.get(agentKey),
18259
19004
  target: input.diversityTarget,
18260
19005
  runtimeTarget: reviewSpec.multiModelDiversity?.enabled ? {
@@ -18295,7 +19040,7 @@ async function execute(input, deps, state) {
18295
19040
  routePlan = buildResolvedRoutePlan({
18296
19041
  agents: diversityCtx.routeAgents,
18297
19042
  cliModel: input.model,
18298
- routingConfig: effectiveRoutingConfig,
19043
+ models: effectiveModels,
18299
19044
  frontmatterModel: (agentKey) => frontmatterByKey.get(agentKey),
18300
19045
  ...input.summarizer === undefined ? {} : {
18301
19046
  summarizer: {
@@ -18320,8 +19065,9 @@ async function execute(input, deps, state) {
18320
19065
  ...input.materiality === undefined ? {} : { materiality: true }
18321
19066
  });
18322
19067
  } catch (error) {
18323
- if (effectiveRoutingConfig !== undefined)
19068
+ if (effectiveModels !== undefined || error instanceof InvalidModelError) {
18324
19069
  throw error;
19070
+ }
18325
19071
  routePlan = undefined;
18326
19072
  }
18327
19073
  }
@@ -18358,7 +19104,7 @@ async function execute(input, deps, state) {
18358
19104
  ]);
18359
19105
  state.boundaryNonce = boundaryNonce;
18360
19106
  state.reviewInstructions = gotchas;
18361
- const stepsDir = path23.join(input.runDir, "steps");
19107
+ const stepsDir = path24.join(input.runDir, "steps");
18362
19108
  const leadsBlock = skipDiscovery || ceilingAborted(deps, state) ? "" : await runScout(input, deps, state, patch, stepsDir, boundaryNonce);
18363
19109
  const stepTimeoutMs = input.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS;
18364
19110
  const huntersAdmitted = !ceilingAborted(deps, state);
@@ -18367,7 +19113,7 @@ async function execute(input, deps, state) {
18367
19113
  for (const hunter of huntersAdmitted ? hunters : []) {
18368
19114
  const agent = await parseAgentFile(agentPromptPath(input, hunter.file));
18369
19115
  const name = `hunter-${hunter.key}`;
18370
- const systemPromptPath = path23.join(stepsDir, `${name}.system.md`);
19116
+ const systemPromptPath = path24.join(stepsDir, `${name}.system.md`);
18371
19117
  const shared = input.sharedPrefix === true && routeSharesPrefix(routeForStepKey(routePlan, name));
18372
19118
  const body = renderAgentBody(agent.body, {
18373
19119
  priors: input.suspicionPriors,
@@ -18379,7 +19125,7 @@ async function execute(input, deps, state) {
18379
19125
  await writeSystemPrompt(systemPromptPath, `${SHARED_PREFIX_HEADER}
18380
19126
 
18381
19127
  ${sharedBlock}`);
18382
- const bodyPath = path23.join(stepsDir, `${name}.body.md`);
19128
+ const bodyPath = path24.join(stepsDir, `${name}.body.md`);
18383
19129
  await Bun.write(bodyPath, body);
18384
19130
  await chmod(bodyPath, 384);
18385
19131
  } else {
@@ -18394,12 +19140,12 @@ ${SHARED_PREFIX_CLOSING}` : sharedBlock,
18394
19140
  tools: agent.tools,
18395
19141
  mcpConfigPath: input.mcpConfigPath,
18396
19142
  model: resolveModel(input, hunter.model, agent.model, hunter.file),
18397
- effort: resolveEffort(agent.effort, "hunter"),
19143
+ ...stepEffortFields(routePlan, name, agent.effort, defaultEffortForRole("hunter")),
18398
19144
  cwd: input.worktree,
18399
- outPath: path23.join(stepsDir, `${name}.draft.json`),
19145
+ outPath: path24.join(stepsDir, `${name}.draft.json`),
18400
19146
  timeoutMs: stepTimeoutMs,
18401
19147
  maxAttempts: DEFAULT_STEP_MAX_ATTEMPTS,
18402
- ...routeForStepKey(routePlan, name) === undefined ? {} : { route: routeForStepKey(routePlan, name) },
19148
+ ...stepRouteFields(routePlan, name),
18403
19149
  parse: (finalText) => {
18404
19150
  const extracted = extractJsonObject(finalText);
18405
19151
  if (extracted === undefined) {
@@ -18428,8 +19174,8 @@ ${SHARED_PREFIX_CLOSING}` : sharedBlock,
18428
19174
  let summarizerConstructionFailed = false;
18429
19175
  if (input.summarizer && !skipDiscovery && huntersAdmitted) {
18430
19176
  const name = "summarizer";
18431
- const systemPromptPath = path23.join(stepsDir, `${name}.system.md`);
18432
- const outPath = path23.join(stepsDir, `${name}.summary.json`);
19177
+ const systemPromptPath = path24.join(stepsDir, `${name}.system.md`);
19178
+ const outPath = path24.join(stepsDir, `${name}.summary.json`);
18433
19179
  summarizerMeta = {
18434
19180
  name,
18435
19181
  model: input.summarizer.model ?? input.model ?? "unresolved",
@@ -18443,7 +19189,8 @@ ${SHARED_PREFIX_CLOSING}` : sharedBlock,
18443
19189
  const agent = await parseAgentFile(input.summarizer.promptPath);
18444
19190
  await writeSystemPrompt(systemPromptPath, agent.body);
18445
19191
  summarizerMeta.model = resolveModel(input, input.summarizer.model, agent.model, input.summarizer.promptPath);
18446
- summarizerMeta.effort = resolveEffort(agent.effort, "summarizer");
19192
+ const summarizerEffort = stepEffortFields(routePlan, name, agent.effort, defaultEffortForRole("summarizer"));
19193
+ summarizerMeta.effort = summarizerEffort.effort;
18447
19194
  summarizerMeta.tools = agent.tools;
18448
19195
  summarizerSpec = {
18449
19196
  name,
@@ -18452,10 +19199,10 @@ ${SHARED_PREFIX_CLOSING}` : sharedBlock,
18452
19199
  tools: agent.tools,
18453
19200
  mcpConfigPath: input.mcpConfigPath,
18454
19201
  model: summarizerMeta.model,
18455
- effort: summarizerMeta.effort,
19202
+ ...summarizerEffort,
18456
19203
  cwd: input.worktree,
18457
19204
  outPath,
18458
- ...routeForStepKey(routePlan, name) === undefined ? {} : { route: routeForStepKey(routePlan, name) },
19205
+ ...stepRouteFields(routePlan, name),
18459
19206
  timeoutMs: 5 * 60 * 1000,
18460
19207
  maxAttempts: 1,
18461
19208
  parse: (finalText) => {
@@ -18560,14 +19307,14 @@ ${SHARED_PREFIX_CLOSING}` : sharedBlock,
18560
19307
  const warmName = `warmup-${index + 1}`;
18561
19308
  const warmSpec = {
18562
19309
  name: warmName,
18563
- systemPromptPath: path23.join(stepsDir, `${warmName}.system.md`),
19310
+ systemPromptPath: path24.join(stepsDir, `${warmName}.system.md`),
18564
19311
  prompt: "Do not call any tool. This is a cache warm-up, not the review. Reply with exactly: OK",
18565
19312
  tools: first.spec.tools,
18566
19313
  mcpConfigPath: first.spec.mcpConfigPath,
18567
19314
  model: first.spec.model,
18568
19315
  effort: first.spec.effort,
18569
19316
  cwd: first.spec.cwd,
18570
- outPath: path23.join(stepsDir, `${warmName}.out.txt`),
19317
+ outPath: path24.join(stepsDir, `${warmName}.out.txt`),
18571
19318
  ...first.spec.route === undefined ? {} : { route: first.spec.route },
18572
19319
  timeoutMs: 2 * 60 * 1000,
18573
19320
  maxAttempts: 1,
@@ -18784,17 +19531,17 @@ async function runRefuter(input, deps, state, batch, options) {
18784
19531
  claim: s.claim,
18785
19532
  proof_refs: s.proof_refs
18786
19533
  })), null, 2);
18787
- await Bun.write(path23.join(options.stepsDir, "refuter-batch.json"), `${batchJson}
19534
+ await Bun.write(path24.join(options.stepsDir, "refuter-batch.json"), `${batchJson}
18788
19535
  `);
18789
19536
  const agent = await parseAgentFile(agentPromptPath(input, options.agent.file));
18790
- const systemPromptPath = path23.join(options.stepsDir, "refuter.system.md");
19537
+ const systemPromptPath = path24.join(options.stepsDir, "refuter.system.md");
18791
19538
  await writeSystemPrompt(systemPromptPath, renderAgentBody(agent.body, {
18792
19539
  priors: [],
18793
19540
  gotchas: state.reviewInstructions ?? NO_REVIEW_INSTRUCTIONS,
18794
19541
  nonce: options.nonce
18795
19542
  }));
18796
19543
  const model = resolveModel(input, options.agent.model, agent.model, options.agent.file);
18797
- const effort = resolveEffort(agent.effort, "refuter");
19544
+ const effortFields = stepEffortFields(state.routePlan, agentStepKey(options.agent), agent.effort, defaultEffortForRole("refuter"));
18798
19545
  const forged = [];
18799
19546
  const specs = [];
18800
19547
  for (const survivor of batch) {
@@ -18818,14 +19565,12 @@ async function runRefuter(input, deps, state, batch, options) {
18818
19565
  tools: agent.tools,
18819
19566
  mcpConfigPath: input.mcpConfigPath,
18820
19567
  model,
18821
- effort,
19568
+ ...effortFields,
18822
19569
  cwd: input.worktree,
18823
- outPath: path23.join(options.stepsDir, `refuter-${survivor.id}.result.json`),
19570
+ outPath: path24.join(options.stepsDir, `refuter-${survivor.id}.result.json`),
18824
19571
  timeoutMs: options.stepTimeoutMs,
18825
19572
  maxAttempts: DEFAULT_STEP_MAX_ATTEMPTS,
18826
- ...routeForStepKey(state.routePlan, agentStepKey(options.agent)) === undefined ? {} : {
18827
- route: routeForStepKey(state.routePlan, agentStepKey(options.agent))
18828
- },
19573
+ ...stepRouteFields(state.routePlan, agentStepKey(options.agent)),
18829
19574
  parse: (finalText) => {
18830
19575
  const extracted = extractJsonObject(finalText);
18831
19576
  if (extracted === undefined) {
@@ -18912,14 +19657,14 @@ async function runVerify(input, deps, state, queued, options) {
18912
19657
  })), null, 2)}
18913
19658
  `);
18914
19659
  const agent = await parseAgentFile(agentPromptPath(input, options.agent.file));
18915
- const systemPromptPath = path23.join(options.stepsDir, "verifier.system.md");
19660
+ const systemPromptPath = path24.join(options.stepsDir, "verifier.system.md");
18916
19661
  await writeSystemPrompt(systemPromptPath, renderAgentBody(agent.body, {
18917
19662
  priors: [],
18918
19663
  gotchas: state.reviewInstructions ?? NO_REVIEW_INSTRUCTIONS,
18919
19664
  nonce: options.nonce
18920
19665
  }));
18921
19666
  const model = resolveModel(input, options.agent.model, agent.model, options.agent.file);
18922
- const effort = resolveEffort(agent.effort, "verifier");
19667
+ const effortFields = stepEffortFields(state.routePlan, agentStepKey(options.agent), agent.effort, defaultEffortForRole("verifier"));
18923
19668
  const forged = [];
18924
19669
  const specs = [];
18925
19670
  for (const subject of subjects) {
@@ -18929,7 +19674,7 @@ async function runVerify(input, deps, state, queued, options) {
18929
19674
  continue;
18930
19675
  }
18931
19676
  const dir = verifyArtifactDir(options.stepsDir, subject.vId);
18932
- await mkdir7(dir, { recursive: true });
19677
+ await mkdir8(dir, { recursive: true });
18933
19678
  const spec = {
18934
19679
  name: verifyStepName(subject.vId),
18935
19680
  systemPromptPath,
@@ -18937,14 +19682,12 @@ async function runVerify(input, deps, state, queued, options) {
18937
19682
  tools: agent.tools,
18938
19683
  mcpConfigPath: input.mcpConfigPath,
18939
19684
  model,
18940
- effort,
19685
+ ...effortFields,
18941
19686
  cwd: input.worktree,
18942
- outPath: path23.join(dir, "result.json"),
19687
+ outPath: path24.join(dir, "result.json"),
18943
19688
  timeoutMs: options.stepTimeoutMs,
18944
19689
  maxAttempts: DEFAULT_STEP_MAX_ATTEMPTS,
18945
- ...routeForStepKey(state.routePlan, agentStepKey(options.agent)) === undefined ? {} : {
18946
- route: routeForStepKey(state.routePlan, agentStepKey(options.agent))
18947
- },
19690
+ ...stepRouteFields(state.routePlan, agentStepKey(options.agent)),
18948
19691
  parse: (finalText) => {
18949
19692
  const extracted = extractJsonObject(finalText);
18950
19693
  if (extracted === undefined) {
@@ -19044,17 +19787,17 @@ async function runAdjudicate(input, deps, state, queue, options) {
19044
19787
  }
19045
19788
  const body = await Bun.file(adjudicatorPrompt).text();
19046
19789
  const agent = await parseAgentFile(agentPromptPath(input, options.agent.file));
19047
- const systemPromptPath = path23.join(options.stepsDir, "adjudicator.system.md");
19790
+ const systemPromptPath = path24.join(options.stepsDir, "adjudicator.system.md");
19048
19791
  await writeSystemPrompt(systemPromptPath, body);
19049
19792
  const model = resolveModel(input, options.agent.model, agent.model, options.agent.file);
19050
- const effort = resolveEffort(agent.effort, "refuter");
19793
+ const effortFields = stepEffortFields(state.routePlan, agentStepKey(options.agent), agent.effort, defaultEffortForRole("refuter"));
19051
19794
  const specs = [];
19052
19795
  for (const [index, subject] of queue.entries()) {
19053
19796
  const prompt = composeAdjudicationPrompt(subject, options.nonce);
19054
19797
  if (prompt === null)
19055
19798
  continue;
19056
- const dir = path23.join(options.stepsDir, "adjudicate", subject.priorId);
19057
- await mkdir7(dir, { recursive: true });
19799
+ const dir = path24.join(options.stepsDir, "adjudicate", subject.priorId);
19800
+ await mkdir8(dir, { recursive: true });
19058
19801
  const spec = {
19059
19802
  name: `adjudicate-${subject.priorId}`,
19060
19803
  systemPromptPath,
@@ -19062,14 +19805,12 @@ async function runAdjudicate(input, deps, state, queue, options) {
19062
19805
  tools: agent.tools,
19063
19806
  mcpConfigPath: input.mcpConfigPath,
19064
19807
  model,
19065
- effort,
19808
+ ...effortFields,
19066
19809
  cwd: input.worktree,
19067
- outPath: path23.join(dir, "result.json"),
19810
+ outPath: path24.join(dir, "result.json"),
19068
19811
  timeoutMs: options.stepTimeoutMs,
19069
19812
  maxAttempts: DEFAULT_STEP_MAX_ATTEMPTS,
19070
- ...routeForStepKey(state.routePlan, agentStepKey(options.agent)) === undefined ? {} : {
19071
- route: routeForStepKey(state.routePlan, agentStepKey(options.agent))
19072
- },
19813
+ ...stepRouteFields(state.routePlan, agentStepKey(options.agent)),
19073
19814
  parse: parseAdjudicationResult,
19074
19815
  onRetry: (info) => emit(deps, { kind: "step-retry", ...info })
19075
19816
  };
@@ -19138,8 +19879,8 @@ async function runScout(input, deps, state, patch, stepsDir, nonce) {
19138
19879
  return "";
19139
19880
  }
19140
19881
  const name = "scout";
19141
- const systemPromptPath = path23.join(stepsDir, `${name}.system.md`);
19142
- const outPath = path23.join(stepsDir, `${name}.leads.json`);
19882
+ const systemPromptPath = path24.join(stepsDir, `${name}.system.md`);
19883
+ const outPath = path24.join(stepsDir, `${name}.leads.json`);
19143
19884
  const meta = {
19144
19885
  name,
19145
19886
  model: input.scout.model ?? input.model ?? "unresolved",
@@ -19182,7 +19923,8 @@ async function runScout(input, deps, state, patch, stepsDir, nonce) {
19182
19923
  await writeSystemPrompt(systemPromptPath, agent.body);
19183
19924
  meta.model = resolveModel(input, input.scout.model, agent.model ?? DEFAULT_SCOUT_MODEL, input.scout.promptPath);
19184
19925
  record.model = meta.model;
19185
- meta.effort = resolveEffort(agent.effort, "scout");
19926
+ const scoutEffort = stepEffortFields(state.routePlan, name, agent.effort, defaultEffortForRole("scout"));
19927
+ meta.effort = scoutEffort.effort;
19186
19928
  record.prompt_sha256 = new Bun.CryptoHasher("sha256").update(raw).digest("hex");
19187
19929
  spec = {
19188
19930
  name,
@@ -19191,12 +19933,12 @@ async function runScout(input, deps, state, patch, stepsDir, nonce) {
19191
19933
  tools: meta.tools,
19192
19934
  mcpConfigPath: input.mcpConfigPath,
19193
19935
  model: meta.model,
19194
- effort: meta.effort,
19936
+ ...scoutEffort,
19195
19937
  cwd: input.worktree,
19196
19938
  outPath,
19197
19939
  timeoutMs: SCOUT_TIMEOUT_MS,
19198
19940
  maxAttempts: 1,
19199
- ...routeForStepKey(state.routePlan, name) === undefined ? {} : { route: routeForStepKey(state.routePlan, name) },
19941
+ ...stepRouteFields(state.routePlan, name),
19200
19942
  parse: (finalText) => {
19201
19943
  const extracted = extractJsonObject(finalText);
19202
19944
  if (extracted === undefined) {
@@ -19212,7 +19954,7 @@ async function runScout(input, deps, state, patch, stepsDir, nonce) {
19212
19954
  }
19213
19955
  if (spec.route !== undefined) {
19214
19956
  meta.route = spec.route;
19215
- meta.effort_applied = spec.route.backend === "claude-code";
19957
+ Object.assign(meta, routeEffortFields(spec.route));
19216
19958
  const routedModel = effectiveExecutionModel(spec);
19217
19959
  meta.model = routedModel;
19218
19960
  record.model = routedModel;
@@ -19227,6 +19969,7 @@ async function runScout(input, deps, state, patch, stepsDir, nonce) {
19227
19969
  }
19228
19970
  state.perAgent.scout = perAgentEntry(result);
19229
19971
  recordSettlement(meta, result, input.runDir);
19972
+ record.model = meta.model;
19230
19973
  state.usageTotal = sumUsage(state.usageTotal, result.usage);
19231
19974
  accumulateUsageV2(state, result);
19232
19975
  if (result.status !== "ok")
@@ -19318,8 +20061,8 @@ async function runConsolidation(input, deps, state, stepsDir, nonce) {
19318
20061
  return;
19319
20062
  }
19320
20063
  const name = "consolidate";
19321
- const systemPromptPath = path23.join(stepsDir, `${name}.system.md`);
19322
- const outPath = path23.join(stepsDir, `${name}.plan.json`);
20064
+ const systemPromptPath = path24.join(stepsDir, `${name}.system.md`);
20065
+ const outPath = path24.join(stepsDir, `${name}.plan.json`);
19323
20066
  const meta = {
19324
20067
  name,
19325
20068
  model: input.consolidate.model ?? input.model ?? "unresolved",
@@ -19350,7 +20093,8 @@ async function runConsolidation(input, deps, state, stepsDir, nonce) {
19350
20093
  await writeSystemPrompt(systemPromptPath, agent.body);
19351
20094
  meta.model = resolveModel(input, input.consolidate.model, agent.model ?? DEFAULT_CONSOLIDATE_MODEL, input.consolidate.promptPath);
19352
20095
  record.model = meta.model;
19353
- meta.effort = agent.effort ?? DEFAULT_CONSOLIDATE_EFFORT;
20096
+ const consolidateEffort = stepEffortFields(state.routePlan, name, agent.effort, DEFAULT_CONSOLIDATE_EFFORT);
20097
+ meta.effort = consolidateEffort.effort;
19354
20098
  record.prompt_sha256 = new Bun.CryptoHasher("sha256").update(raw).digest("hex");
19355
20099
  spec = {
19356
20100
  name,
@@ -19359,12 +20103,12 @@ async function runConsolidation(input, deps, state, stepsDir, nonce) {
19359
20103
  tools: meta.tools,
19360
20104
  mcpConfigPath: input.mcpConfigPath,
19361
20105
  model: meta.model,
19362
- effort: meta.effort,
20106
+ ...consolidateEffort,
19363
20107
  cwd: input.worktree,
19364
20108
  outPath,
19365
20109
  timeoutMs: CONSOLIDATE_TIMEOUT_MS,
19366
20110
  maxAttempts: CONSOLIDATE_MAX_ATTEMPTS,
19367
- ...routeForStepKey(state.routePlan, name) === undefined ? {} : { route: routeForStepKey(state.routePlan, name) },
20111
+ ...stepRouteFields(state.routePlan, name),
19368
20112
  parse: (finalText) => {
19369
20113
  const extracted = extractJsonObject(finalText);
19370
20114
  if (extracted === undefined) {
@@ -19381,7 +20125,7 @@ async function runConsolidation(input, deps, state, stepsDir, nonce) {
19381
20125
  }
19382
20126
  if (spec.route !== undefined) {
19383
20127
  meta.route = spec.route;
19384
- meta.effort_applied = spec.route.backend === "claude-code";
20128
+ Object.assign(meta, routeEffortFields(spec.route));
19385
20129
  const routedModel = effectiveExecutionModel(spec);
19386
20130
  meta.model = routedModel;
19387
20131
  record.model = routedModel;
@@ -19396,6 +20140,7 @@ async function runConsolidation(input, deps, state, stepsDir, nonce) {
19396
20140
  }
19397
20141
  state.perAgent.consolidate = perAgentEntry(result);
19398
20142
  recordSettlement(meta, result, input.runDir);
20143
+ record.model = meta.model;
19399
20144
  state.usageTotal = sumUsage(state.usageTotal, result.usage);
19400
20145
  accumulateUsageV2(state, result);
19401
20146
  if (result.status !== "ok") {
@@ -19428,13 +20173,13 @@ function skippedMateriality(input, state) {
19428
20173
  };
19429
20174
  }
19430
20175
  async function materialityWindow(worktree, relPath, line) {
19431
- if (path23.isAbsolute(relPath))
20176
+ if (path24.isAbsolute(relPath))
19432
20177
  return null;
19433
20178
  try {
19434
20179
  const root = await realpath4(worktree);
19435
- const target = await realpath4(path23.join(root, relPath));
19436
- const rel = path23.relative(root, target);
19437
- if (rel === "" || rel === ".." || rel.startsWith(`..${path23.sep}`) || path23.isAbsolute(rel)) {
20180
+ const target = await realpath4(path24.join(root, relPath));
20181
+ const rel = path24.relative(root, target);
20182
+ if (rel === "" || rel === ".." || rel.startsWith(`..${path24.sep}`) || path24.isAbsolute(rel)) {
19438
20183
  return null;
19439
20184
  }
19440
20185
  const file = Bun.file(target);
@@ -19476,9 +20221,10 @@ async function runMaterialityJudge(input, deps, state, stepsDir, nonce) {
19476
20221
  route = routeForStepKey(state.routePlan, MATERIALITY_STEP_KEY);
19477
20222
  if (route === undefined || !isMeasuredJudgeRoute(route)) {
19478
20223
  record.status = "unsupported_route";
19479
- record.reason = route !== undefined || resolveMaterialityJudgeRoute(input.routingConfig ?? input.config?.effective?.routing) === undefined ? "judge route is not the measured claude-code route" : "route plan carries no judge step";
20224
+ record.reason = route !== undefined || resolveMaterialityJudgeRoute(input.models ?? input.config?.effective?.models) === undefined ? "judge route is not the measured claude-code route" : "route plan carries no judge step";
19480
20225
  return;
19481
20226
  }
20227
+ record.model = route.modelSnapshot;
19482
20228
  }
19483
20229
  if (judge.length === 0)
19484
20230
  return;
@@ -19498,8 +20244,8 @@ async function runMaterialityJudge(input, deps, state, stepsDir, nonce) {
19498
20244
  judge.splice(waves * cap);
19499
20245
  }
19500
20246
  }
19501
- const systemPromptPath = path23.join(stepsDir, "materiality.system.md");
19502
- const mcpConfigPath = path23.join(stepsDir, "materiality.mcp.json");
20247
+ const systemPromptPath = path24.join(stepsDir, "materiality.system.md");
20248
+ const mcpConfigPath = path24.join(stepsDir, "materiality.mcp.json");
19503
20249
  try {
19504
20250
  const raw = await Bun.file(input.materiality.promptPath).text();
19505
20251
  const agent = parseAgentSource(raw);
@@ -19514,7 +20260,7 @@ async function runMaterialityJudge(input, deps, state, stepsDir, nonce) {
19514
20260
  return;
19515
20261
  }
19516
20262
  const prTitle = input.prTitle !== undefined && input.prTitle.trim() !== "" ? input.prTitle : MATERIALITY_TITLE_FALLBACK;
19517
- const effort = defaultEffortForRole("other");
20263
+ const { effort } = stepEffortFields(state.routePlan, MATERIALITY_STEP_KEY, undefined, defaultEffortForRole("other"));
19518
20264
  const specs = [];
19519
20265
  const ownerPolicy = state.reviewInstructions === undefined || state.reviewInstructions === NO_REVIEW_INSTRUCTIONS ? undefined : ownerPolicyText(state.reviewInstructions);
19520
20266
  for (const finding of judge) {
@@ -19529,18 +20275,18 @@ async function runMaterialityJudge(input, deps, state, stepsDir, nonce) {
19529
20275
  record.skipped_unsafe++;
19530
20276
  continue;
19531
20277
  }
19532
- const dir = path23.join(stepsDir, "materiality", finding.id);
19533
- await mkdir7(dir, { recursive: true });
20278
+ const dir = path24.join(stepsDir, "materiality", finding.id);
20279
+ await mkdir8(dir, { recursive: true });
19534
20280
  const spec = {
19535
20281
  name: `materiality-${finding.id}`,
19536
20282
  systemPromptPath,
19537
20283
  prompt,
19538
20284
  tools: [],
19539
20285
  mcpConfigPath,
19540
- model: MATERIALITY_JUDGE_MODEL,
20286
+ model: route?.modelSnapshot ?? MATERIALITY_JUDGE_MODEL,
19541
20287
  effort,
19542
20288
  cwd: input.worktree,
19543
- outPath: path23.join(dir, "result.json"),
20289
+ outPath: path24.join(dir, "result.json"),
19544
20290
  timeoutMs: MATERIALITY_TIMEOUT_MS,
19545
20291
  maxAttempts: MATERIALITY_MAX_ATTEMPTS,
19546
20292
  ...route === undefined ? {} : { route },
@@ -19730,8 +20476,9 @@ function failureDetailOf(raw) {
19730
20476
  }
19731
20477
  function hunterFailureOf(spec, result) {
19732
20478
  const cause = result?.failureCause;
19733
- const provider = spec.route?.provider.trim();
19734
- const model = spec.route?.modelSnapshot.trim();
20479
+ const route = (result === undefined ? undefined : ranRoute(result)) ?? spec.route;
20480
+ const provider = route?.provider.trim();
20481
+ const model = route?.modelSnapshot.trim();
19735
20482
  const detail = failureDetailOf(result?.failureDetail);
19736
20483
  return {
19737
20484
  name: spec.name,
@@ -19801,7 +20548,7 @@ async function writePipelinePlan(input, state) {
19801
20548
  steps: state.steps
19802
20549
  };
19803
20550
  try {
19804
- await writeJsonAtomically(path23.join(input.runDir, "pipeline.json"), plan);
20551
+ await writeJsonAtomically(path24.join(input.runDir, "pipeline.json"), plan);
19805
20552
  } catch (error) {
19806
20553
  state.snapshotWritten = false;
19807
20554
  throw error;
@@ -19855,8 +20602,26 @@ function resolveModel(input, specModel, frontmatterModel, agentName) {
19855
20602
  }
19856
20603
  return model;
19857
20604
  }
19858
- function resolveEffort(frontmatterEffort, role) {
19859
- return frontmatterEffort ?? defaultEffortForRole(role);
20605
+ function stepEffortFields(routePlan, stepKey, frontmatterEffort, roleDefault) {
20606
+ const base = frontmatterEffort ?? roleDefault;
20607
+ const step = routePlan?.steps.find((s) => s.stepKey === stepKey);
20608
+ if (step === undefined)
20609
+ return { effort: base };
20610
+ return {
20611
+ effort: entryEffort(step, base),
20612
+ ...step.fallbacks === undefined || step.fallbacks.length === 0 ? {} : {
20613
+ fallbackEfforts: step.fallbacks.map((fallback) => entryEffort(fallback, base))
20614
+ }
20615
+ };
20616
+ }
20617
+ function entryEffort(step, base) {
20618
+ if (step.route.backend !== "claude-code" || step.effort === undefined) {
20619
+ return base;
20620
+ }
20621
+ if (!isEffort(step.effort)) {
20622
+ throw new Error(`${step.stepKey}: effort ${JSON.stringify(step.effort)} is not a Claude effort level`);
20623
+ }
20624
+ return step.effort;
19860
20625
  }
19861
20626
  function perAgentEntry(result) {
19862
20627
  return {
@@ -19901,21 +20666,33 @@ function routeSharesPrefix(route) {
19901
20666
  function routeForStepKey(routePlan, stepKey) {
19902
20667
  return routePlan?.steps.find((step) => step.stepKey === stepKey)?.route;
19903
20668
  }
20669
+ function stepRouteFields(routePlan, stepKey) {
20670
+ const step = routePlan?.steps.find((s) => s.stepKey === stepKey);
20671
+ if (step === undefined)
20672
+ return {};
20673
+ return {
20674
+ route: step.route,
20675
+ ...step.fallbacks === undefined || step.fallbacks.length === 0 ? {} : { fallbackRoutes: step.fallbacks.map((fallback) => fallback.route) }
20676
+ };
20677
+ }
20678
+ function routeExecutionModel(route, fallback) {
20679
+ if (route.backend === "claude-code") {
20680
+ return claudeCliModel(route);
20681
+ }
20682
+ return route.modelSnapshot || fallback;
20683
+ }
19904
20684
  function effectiveExecutionModel(spec) {
19905
20685
  if (spec.route === undefined) {
19906
20686
  return spec.model;
19907
20687
  }
19908
- if (spec.route.backend === "claude-code") {
19909
- return spawnModelForClaudeCli(spec.route, spec.model);
19910
- }
19911
- return spec.route?.model ?? (spec.route.modelSnapshot || spec.model);
20688
+ return routeExecutionModel(spec.route, spec.model);
19912
20689
  }
19913
20690
  function stepMeta(spec) {
19914
20691
  return {
19915
20692
  name: spec.name,
19916
20693
  model: effectiveExecutionModel(spec),
19917
20694
  effort: spec.effort,
19918
- ...spec.route === undefined ? {} : { effort_applied: spec.route.backend === "claude-code" },
20695
+ ...spec.route === undefined ? {} : routeEffortFields(spec.route),
19919
20696
  tools: spec.tools,
19920
20697
  systemPromptPath: spec.systemPromptPath,
19921
20698
  outPath: spec.outPath,
@@ -19923,6 +20700,12 @@ function stepMeta(spec) {
19923
20700
  ...spec.route === undefined ? {} : { route: spec.route }
19924
20701
  };
19925
20702
  }
20703
+ function routeEffortFields(route) {
20704
+ return {
20705
+ effort_applied: effortApplied(route),
20706
+ ...route.modelVariant === undefined ? {} : { variant: route.modelVariant }
20707
+ };
20708
+ }
19926
20709
  function accumulateUsageV2(state, result) {
19927
20710
  if (result.usageV2 === undefined)
19928
20711
  return;
@@ -19935,6 +20718,27 @@ function recordSettlement(meta, result, runDir) {
19935
20718
  if (result.reservations !== undefined && result.reservations.length > 0) {
19936
20719
  meta.reservations = result.reservations;
19937
20720
  }
20721
+ if (result.modelAttempts !== undefined) {
20722
+ const firstEffort = meta.effort;
20723
+ const ran = result.modelAttempts.findLast((entry) => entry.status !== "skipped");
20724
+ if (ran !== undefined) {
20725
+ meta.route = ran.route;
20726
+ meta.model = routeExecutionModel(ran.route, meta.model);
20727
+ meta.effort = ran.effort ?? firstEffort;
20728
+ delete meta.variant;
20729
+ Object.assign(meta, routeEffortFields(ran.route));
20730
+ }
20731
+ meta.model_attempts = result.modelAttempts.map((entry) => ({
20732
+ model: routeExecutionModel(entry.route, meta.model),
20733
+ route: entry.route,
20734
+ status: entry.status,
20735
+ attempts: entry.attempts,
20736
+ effort: entry.effort ?? firstEffort,
20737
+ ...routeEffortFields(entry.route),
20738
+ ...entry.cause === undefined ? {} : { cause: entry.cause },
20739
+ ...entry.usageV2 === undefined ? {} : { usage_v2: entry.usageV2 }
20740
+ }));
20741
+ }
19938
20742
  meta.status = result.status;
19939
20743
  meta.attempts = result.attempts;
19940
20744
  if (result.attempts < 1) {
@@ -19944,9 +20748,18 @@ function recordSettlement(meta, result, runDir) {
19944
20748
  }
19945
20749
  return;
19946
20750
  }
19947
- meta.attemptEvidencePath = path23.relative(runDir, attemptEvidencePath(meta.outPath, meta.name, result.attempts));
19948
- meta.attemptLogPath = path23.relative(runDir, attemptLogPath(meta.outPath, meta.name, result.attempts));
19949
- meta.settlementReceiptPath = path23.relative(runDir, settlementReceiptPath(meta.outPath, meta.name, result.attempts));
20751
+ meta.attemptEvidencePath = path24.relative(runDir, attemptEvidencePath(meta.outPath, meta.name, result.attempts));
20752
+ meta.attemptLogPath = path24.relative(runDir, attemptLogPath(meta.outPath, meta.name, result.attempts));
20753
+ meta.settlementReceiptPath = path24.relative(runDir, settlementReceiptPath(meta.outPath, meta.name, result.attempts));
20754
+ const tracePaths = [];
20755
+ for (let attempt = 1;attempt <= result.attempts; attempt++) {
20756
+ const absolute = claudeSessionTracePath(meta.outPath, meta.name, attempt);
20757
+ if (existsSync13(absolute)) {
20758
+ tracePaths.push(path24.relative(runDir, absolute));
20759
+ }
20760
+ }
20761
+ if (tracePaths.length > 0)
20762
+ meta.tracePaths = tracePaths;
19950
20763
  }
19951
20764
  var FAILURE_REASON_MAX = 500;
19952
20765
  function redactFailureText(raw) {
@@ -19967,7 +20780,7 @@ function recordStepFailure(meta, error) {
19967
20780
  init_preflight2();
19968
20781
 
19969
20782
  // src/review/report.ts
19970
- init_preflight3();
20783
+ await init_preflight3();
19971
20784
  init_findings();
19972
20785
  init_brand();
19973
20786
  init_published_text();
@@ -20724,27 +21537,22 @@ function duration(ms) {
20724
21537
  function round2(value) {
20725
21538
  return Math.round(value * 100) / 100;
20726
21539
  }
20727
- function formatModelRoute(route, logicalIdentity) {
20728
- const variant = route.modelVariant ? `#${route.modelVariant}` : "";
20729
- const modelName = route.modelSnapshot || route.modelFamily;
20730
- const target = `${route.provider}/${modelName}${variant}`;
20731
- const gateway = route.gateway ?? "direct";
20732
- const dims = `[${gateway}, ${route.backend}]`;
20733
- if (logicalIdentity && logicalIdentity !== target) {
20734
- return `${logicalIdentity} -> ${target} ${dims}`;
20735
- }
20736
- return `${target} ${dims}`;
20737
- }
20738
- function formatStepRoute(step, rawLogical) {
20739
- return formatModelRoute(step.route, rawLogical ?? step.logicalIdentity);
21540
+ function formatStepRoute(step) {
21541
+ return step.effort === undefined ? step.logicalIdentity : `${step.logicalIdentity} (effort ${step.effort})`;
20740
21542
  }
20741
- function envelopeModel(options, agentFiles) {
21543
+ function envelopeModel(options, agentFiles, routePlan) {
20742
21544
  if (options.model)
20743
21545
  return options.model;
20744
21546
  const models = new Set;
20745
- for (const agent of agentFiles.values()) {
20746
- if (agent.model)
20747
- models.add(agent.model);
21547
+ const agentSteps = (routePlan?.steps ?? []).filter((step) => step.role === "hunter" || step.role === "refuter");
21548
+ if (agentSteps.length > 0) {
21549
+ for (const step of agentSteps)
21550
+ models.add(step.route.modelSnapshot);
21551
+ } else {
21552
+ for (const agent of agentFiles.values()) {
21553
+ if (agent.model)
21554
+ models.add(agent.model);
21555
+ }
20748
21556
  }
20749
21557
  if (models.size === 0)
20750
21558
  return "unspecified";
@@ -20754,14 +21562,14 @@ function envelopeModel(options, agentFiles) {
20754
21562
  // src/index.ts
20755
21563
  init_spec();
20756
21564
  var ENGINE_NAME = "pr-hero";
20757
- var ENGINE_VERSION = "0.4.0";
21565
+ var ENGINE_VERSION = "0.5.0";
20758
21566
  export {
20759
21567
  ACTIVE_CHILD_PROCS,
20760
21568
  ACTIVE_SERVER_CLOSERS,
20761
21569
  AGENT_FILE_PATTERNS,
20762
21570
  AGENT_NAMES,
20763
- AmbiguousMappingError,
20764
21571
  BUNDLED_AGENTS_DIR_LABEL,
21572
+ CLAUDE_CREDENTIAL_KINDS,
20765
21573
  CODEGRAPH_MANDATE,
20766
21574
  CONFIG_DIRECTION,
20767
21575
  ClaudeCodeRunner,
@@ -20793,15 +21601,17 @@ export {
20793
21601
  GOTCHAS_PLACEHOLDER_MARKER,
20794
21602
  GOTCHAS_TEMPLATE,
20795
21603
  HELP_TEXT,
21604
+ InvalidModelError,
20796
21605
  MATERIALITY_JUDGE_MODEL,
20797
21606
  MATERIALITY_STEP_KEY,
20798
21607
  MATERIALITY_TITLE_FALLBACK,
20799
- MODEL_CATALOG,
21608
+ MEASURED_JUDGE_MODELS,
20800
21609
  ModelRoutingError,
20801
21610
  NO_REVIEW_INSTRUCTIONS,
20802
21611
  OpenCodeProductionGatedError,
20803
21612
  OpenCodeVersionAdmissionError,
20804
21613
  PIPELINE_SCHEMA_VERSION,
21614
+ REMOVED_ROUTING_MESSAGE,
20805
21615
  REVIEW_MD_TEMPLATE,
20806
21616
  RUNTIME_PREAMBLE,
20807
21617
  ReviewSpecValidationError,
@@ -20812,8 +21622,6 @@ export {
20812
21622
  SUMMARY_DIRECTION,
20813
21623
  SUPPORTED_OPENCODE_SDK_VERSION,
20814
21624
  SUPPORTED_OPENCODE_SERVER_VERSION,
20815
- UnauthorizedRouteError,
20816
- UnmappedRouteError,
20817
21625
  admitDiversityRoutePlan,
20818
21626
  admitOpenCodeVersionPair,
20819
21627
  admitRoutePlan,
@@ -20821,7 +21629,6 @@ export {
20821
21629
  agentStepKey,
20822
21630
  agentsDirProblems,
20823
21631
  agentsDirSeat,
20824
- aliasCanonical,
20825
21632
  allExcludedMessage,
20826
21633
  assertBasenameOnly,
20827
21634
  assertOutsideRepo,
@@ -20834,6 +21641,7 @@ export {
20834
21641
  checkD1_11Readiness,
20835
21642
  claimSimilarity,
20836
21643
  classifyFailure,
21644
+ claudeCliModel,
20837
21645
  closeAllServers,
20838
21646
  clusterByRootCause,
20839
21647
  code,
@@ -20851,7 +21659,6 @@ export {
20851
21659
  extractAnchor,
20852
21660
  extractJsonObject,
20853
21661
  formatElapsed,
20854
- formatModelRoute,
20855
21662
  formatStepRoute,
20856
21663
  freezeRoutePlan,
20857
21664
  gotchasErrorMessage,
@@ -20867,17 +21674,16 @@ export {
20867
21674
  isFullCommitId,
20868
21675
  isLinkablePath,
20869
21676
  isMeasuredJudgeRoute,
20870
- isModelAlias,
20871
21677
  isNotCausedByPr,
20872
21678
  isSafeSlug,
20873
21679
  isTerminalSessionFailure,
20874
21680
  isTransientSessionFailure,
20875
21681
  isVacuousHunt,
21682
+ judgeModelChoice,
20876
21683
  killAllChildProcesses,
20877
21684
  listPaths,
20878
21685
  loadOpenCodeSdk,
20879
21686
  localReviewSpec,
20880
- lookupAlias,
20881
21687
  makeProofRefResolver,
20882
21688
  mergeAndDedupe,
20883
21689
  mergeConfig,
@@ -20892,13 +21698,12 @@ export {
20892
21698
  parseFindingCommentBadge,
20893
21699
  parseGlobalConfig,
20894
21700
  parseLocalConfig,
20895
- parseLogicalIdentity,
20896
21701
  parseNumstat,
20897
21702
  parseNumstatFiles,
20898
21703
  parseRemoteHead,
20899
- parseRoutingConfig,
20900
21704
  parseUsage,
20901
21705
  planOpenCodeSdkImport,
21706
+ planRoutes,
20902
21707
  preflightAgentsDir,
20903
21708
  promptSetFingerprint,
20904
21709
  promptSetIdentity,
@@ -20918,29 +21723,30 @@ export {
20918
21723
  resolveAgentsDir,
20919
21724
  resolveAgentsDirSetting,
20920
21725
  resolveBaseRef,
20921
- resolveLogicalModel,
20922
21726
  resolveMaterialityGate,
20923
21727
  resolveMaterialityJudgeRoute,
20924
21728
  resolveMaxConcurrentSteps,
20925
21729
  resolveMaxVerificationSteps,
21730
+ resolveModelEntryRoute,
20926
21731
  resolveModelRoute,
20927
21732
  resolveOpenCodeSdkV2Entry,
20928
21733
  resolvePost,
20929
21734
  resolveScout,
20930
21735
  resolveSharedPrefix,
20931
21736
  resolveSpecialty,
21737
+ resolveStepModel,
21738
+ resolveStepModels,
20932
21739
  resolveStepRoute,
20933
21740
  resolveSummary,
20934
21741
  rootCauseIdByFinding,
21742
+ routeForModel,
20935
21743
  routeSharesPrefix,
20936
- routingNeedsOpenCodeSdk,
20937
21744
  runDirCandidate,
20938
21745
  runPipeline,
20939
21746
  scanAidEmoji,
20940
21747
  serversShuttingDown,
20941
21748
  settlementReceiptPath,
20942
21749
  severityEmoji,
20943
- spawnModelForClaudeCli,
20944
21750
  stepFailureReason,
20945
21751
  sumUsage,
20946
21752
  validateDraftFinding,