crysk 0.3.0 → 0.3.2

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 (71) hide show
  1. package/README.md +11 -5
  2. package/dist/SKILL-6j27707y.md +140 -0
  3. package/dist/SKILL-816621e5.md +74 -0
  4. package/dist/SKILL-bnh7nrjz.md +74 -0
  5. package/dist/SKILL-fv8x6hhx.md +140 -0
  6. package/dist/SKILL-nv32jpc5.md +74 -0
  7. package/dist/SKILL-qnfc8yp3.md +539 -0
  8. package/dist/SKILL-xr56f0b6.md +140 -0
  9. package/dist/SKILL-y8rv8msh.md +134 -0
  10. package/dist/SKILL-ygka1bs0.md +515 -0
  11. package/dist/SKILL-yz6wk92g.md +542 -0
  12. package/dist/ci-admission-09k2ba89.md +126 -0
  13. package/dist/ci-admission-f19qh39t.md +128 -0
  14. package/dist/ci-admission-qk9r9taq.md +124 -0
  15. package/dist/ci-admission-tcqsj7b2.md +126 -0
  16. package/dist/cli.js +2463 -1573
  17. package/dist/index.js +1464 -911
  18. package/dist/materiality-f1qwnvg1.md +27 -0
  19. package/package.json +4 -3
  20. package/prompts/materiality.md +27 -0
  21. package/skills/crysk/SKILL.md +2 -2
  22. package/skills/crysk-ci-setup/SKILL.md +13 -7
  23. package/skills/crysk-ci-setup/references/ci-admission.md +8 -2
  24. package/skills/crysk-loop/SKILL.md +62 -16
  25. package/src/asset-manifest.ts +2 -0
  26. package/src/assets.ts +4 -1
  27. package/src/brand.ts +11 -9
  28. package/src/ci/cli-record.ts +1 -1
  29. package/src/ci/gates.ts +59 -6
  30. package/src/ci/outcome.ts +2 -1
  31. package/src/ci/override.ts +11 -10
  32. package/src/ci/publish.ts +44 -103
  33. package/src/ci/reporter.ts +36 -7
  34. package/src/ci/review-admission.ts +11 -2
  35. package/src/ci/review-levels.ts +21 -0
  36. package/src/ci/setup.ts +1 -2
  37. package/src/commands/post.ts +17 -0
  38. package/src/compare/loop.ts +356 -0
  39. package/src/compare/materiality.ts +266 -0
  40. package/src/compare/noise.ts +166 -0
  41. package/src/diversity/projection.ts +3 -0
  42. package/src/index.ts +1 -1
  43. package/src/model/routing.ts +62 -0
  44. package/src/pr/admission.ts +191 -42
  45. package/src/pr/answered-findings.ts +169 -0
  46. package/src/pr/ci-admission-gate.ts +80 -2
  47. package/src/pr/discovery.ts +17 -5
  48. package/src/pr/inline.ts +15 -1
  49. package/src/pr/plan.ts +5 -0
  50. package/src/pr/post-floor.ts +30 -0
  51. package/src/pr/posting.ts +4 -0
  52. package/src/pr/pr-status.ts +73 -1
  53. package/src/pr/pr.ts +50 -34
  54. package/src/pr/preflight.ts +2 -2
  55. package/src/pr/publish-outcome.ts +4 -0
  56. package/src/pr/review-pr.ts +65 -26
  57. package/src/pr/teardown.ts +1 -1
  58. package/src/rereview/prepare.ts +16 -0
  59. package/src/rereview/state.ts +206 -25
  60. package/src/review/boundary.ts +4 -1
  61. package/src/review/dedupe.ts +48 -4
  62. package/src/review/findings.ts +47 -1
  63. package/src/review/materiality-gate.ts +134 -0
  64. package/src/review/pipeline.ts +521 -41
  65. package/src/review/preflight.ts +69 -0
  66. package/src/review/report.ts +73 -10
  67. package/src/review/review.ts +16 -0
  68. package/src/review/route-preflight.ts +29 -1
  69. package/src/review/run.ts +2 -0
  70. package/src/ui/config.ts +8 -0
  71. package/src/updater.ts +1 -1
package/dist/index.js CHANGED
@@ -1,20 +1,15 @@
1
1
  // @bun
2
- var __defProp = Object.defineProperty;
3
- var __returnValue = (v) => v;
4
- function __exportSetter(name, newValue) {
5
- this[name] = __returnValue.bind(null, newValue);
6
- }
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, {
10
- get: all[name],
11
- enumerable: true,
12
- configurable: true,
13
- set: __exportSetter.bind(all, name)
14
- });
2
+ var __esm = (fn, res, err) => () => {
3
+ if (fn)
4
+ try {
5
+ res = fn(fn = 0);
6
+ } catch (e) {
7
+ err = [e];
8
+ }
9
+ if (err)
10
+ throw err[0];
11
+ return res;
15
12
  };
16
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
- var __require = import.meta.require;
18
13
 
19
14
  // src/errors.ts
20
15
  function withRecordClass(error, cls) {
@@ -501,6 +496,23 @@ function agentStepKey(agent) {
501
496
  }
502
497
  return agent.key;
503
498
  }
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 {
509
+ return;
510
+ }
511
+ return isMeasuredJudgeRoute(step.route) ? step : undefined;
512
+ }
513
+ function isMeasuredJudgeRoute(route) {
514
+ return route.backend === "claude-code" && route.provider === "anthropic" && (route.gateway === undefined || route.gateway === "direct");
515
+ }
504
516
  function buildResolvedRoutePlan(input) {
505
517
  const stepRoutes = [];
506
518
  for (const agent of input.agents) {
@@ -541,6 +553,11 @@ function buildResolvedRoutePlan(input) {
541
553
  routingConfig: input.routingConfig
542
554
  }));
543
555
  }
556
+ if (input.materiality) {
557
+ const judge = resolveMaterialityJudgeRoute(input.routingConfig);
558
+ if (judge !== undefined)
559
+ stepRoutes.push(judge);
560
+ }
544
561
  return createResolvedRoutePlan(stepRoutes);
545
562
  }
546
563
  function spawnModelForClaudeCli(route, executionModel) {
@@ -560,7 +577,7 @@ function spawnModelForClaudeCli(route, executionModel) {
560
577
  } catch {}
561
578
  return route.modelSnapshot;
562
579
  }
563
- var ModelRoutingError, UnmappedRouteError, AmbiguousMappingError, UnauthorizedRouteError, SLASH_GRAMMAR_REGEX;
580
+ var ModelRoutingError, UnmappedRouteError, AmbiguousMappingError, UnauthorizedRouteError, SLASH_GRAMMAR_REGEX, MATERIALITY_STEP_KEY = "materiality", MATERIALITY_JUDGE_MODEL = "sonnet";
564
581
  var init_routing = __esm(() => {
565
582
  init_redact();
566
583
  init_catalog();
@@ -576,105 +593,200 @@ var init_routing = __esm(() => {
576
593
  SLASH_GRAMMAR_REGEX = /^([a-zA-Z0-9_-]+)\/([a-zA-Z0-9._-]+)(?:#([a-zA-Z0-9._-]+))?$/;
577
594
  });
578
595
 
579
- // src/review/spec.ts
580
- function isSafeSlug(value) {
581
- return value.length >= 1 && value.length <= 64 && SAFE_SLUG_RE.test(value);
596
+ // src/compare/materiality.ts
597
+ function normalizeClaim(text) {
598
+ const flat = text.replace(/\s+/g, " ").trim();
599
+ if (flat.length <= CLAIM_CHAR_CAP)
600
+ return flat;
601
+ return `${flat.slice(0, CLAIM_CHAR_CAP - 1).trimEnd()}\u2026`;
602
+ }
603
+ function parseJudgeVerdict(finalText) {
604
+ const trimmed = finalText.trim();
605
+ const start = trimmed.indexOf("{");
606
+ const end = trimmed.lastIndexOf("}");
607
+ if (start < 0 || end < start) {
608
+ throw new Error("judge returned no JSON object");
609
+ }
610
+ const parsed = JSON.parse(trimmed.slice(start, end + 1));
611
+ if (typeof parsed !== "object" || parsed === null) {
612
+ throw new Error("judge JSON is not an object");
613
+ }
614
+ const { label, reason } = parsed;
615
+ if (label !== "material" && label !== "immaterial") {
616
+ throw new Error(`judge label is not material|immaterial: ${String(label)}`);
617
+ }
618
+ if (typeof reason !== "string" || reason.trim() === "") {
619
+ throw new Error("judge reason is missing");
620
+ }
621
+ return { label, reason: reason.trim() };
582
622
  }
583
- function resolveSpecialty(agent) {
584
- return agent.specialty ?? agent.key;
623
+ var CLAIM_CHAR_CAP = 600, SECONDARY_LOW_CATEGORIES;
624
+ var init_materiality = __esm(() => {
625
+ SECONDARY_LOW_CATEGORIES = new Set([
626
+ "style",
627
+ "speculative",
628
+ "doc_defect"
629
+ ]);
630
+ });
631
+
632
+ // src/review/boundary.ts
633
+ function generateBoundaryNonce() {
634
+ const bytes = new Uint8Array(BOUNDARY_NONCE_CHARS / 2);
635
+ crypto.getRandomValues(bytes);
636
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
585
637
  }
586
- function must(condition, message) {
587
- if (!condition)
588
- throw new ReviewSpecValidationError(message);
638
+ function blockForgesNonce(content, nonce) {
639
+ return content.includes(nonce);
589
640
  }
590
- function validateReviewSpec(candidate) {
591
- must(typeof candidate === "object" && candidate !== null, "review spec must be an object");
592
- const spec = candidate;
593
- must(Array.isArray(spec.agents), "spec.agents must be an array");
594
- const diversityEnabled = spec.multiModelDiversity !== undefined && typeof spec.multiModelDiversity === "object" && spec.multiModelDiversity !== null && spec.multiModelDiversity.enabled === true;
595
- if (spec.multiModelDiversity !== undefined) {
596
- const diversity = spec.multiModelDiversity;
597
- must(diversity.enabled === true, "multiModelDiversity.enabled must be true when present");
598
- must(typeof diversity.armId === "string" && isSafeSlug(diversity.armId), "multiModelDiversity.armId must be a safe slug");
599
- must(typeof diversity.maxLegs === "number" && Number.isInteger(diversity.maxLegs) && diversity.maxLegs >= 1, "multiModelDiversity.maxLegs must be a positive integer");
600
- must(typeof diversity.cashCapUsd === "number" && Number.isFinite(diversity.cashCapUsd) && diversity.cashCapUsd > 0, "multiModelDiversity.cashCapUsd must be a positive number");
641
+ function selectBoundaryNonce(blocks, generate = generateBoundaryNonce) {
642
+ for (let attempt = 0;attempt < MAX_NONCE_ATTEMPTS; attempt++) {
643
+ const nonce = generate();
644
+ if (!blocks.some((block) => blockForgesNonce(block, nonce)))
645
+ return nonce;
601
646
  }
602
- const agents = spec.agents;
603
- const keys = new Set;
604
- const hunterSpecialties = new Set;
605
- let hunterCount = 0;
606
- let refuterCount = 0;
607
- agents.forEach((entry, i) => {
608
- must(typeof entry === "object" && entry !== null, `agents[${i}] must be an object`);
609
- const a = entry;
610
- must(typeof a.key === "string" && a.key.length > 0, `agents[${i}].key required`);
611
- must(isSafeSlug(a.key), `agents[${i}].key "${a.key}" is not a safe slug (^[a-z0-9]+(?:-[a-z0-9]+)*$, 1-64 chars)`);
612
- must(!keys.has(a.key), `agents[${i}].key duplicates "${a.key}"`);
613
- keys.add(a.key);
614
- must(a.specialty === undefined || typeof a.specialty === "string" && isSafeSlug(a.specialty), `agents[${i}].specialty must be a safe slug when present`);
615
- must(typeof a.file === "string" && a.file.length > 0, `agents[${i}].file required`);
616
- must(a.role === "hunter" || a.role === "refuter", `agents[${i}].role must be hunter|refuter`);
617
- must(a.models === undefined || diversityEnabled && Array.isArray(a.models) && a.models.length >= 1 && a.models.every((model) => typeof model === "string" && model.length > 0), diversityEnabled ? `agents[${i}].models must be a non-empty string array when multiModelDiversity is enabled` : `agents[${i}].models is not supported in D2; fan-out is a D3 capability`);
618
- if (diversityEnabled && Array.isArray(a.models)) {
619
- for (const model of a.models) {
620
- try {
621
- parseLogicalIdentity(model);
622
- } catch (error) {
623
- must(false, `agents[${i}].models contains invalid model identity "${model}": ${error.message}`);
624
- }
625
- }
626
- }
627
- must(a.model === undefined || typeof a.model === "string" && a.model.length > 0, `agents[${i}].model must be a non-empty string when present`);
628
- if (a.model !== undefined) {
629
- try {
630
- parseLogicalIdentity(a.model);
631
- } catch (error) {
632
- must(false, `agents[${i}].model "${a.model}" is not a valid model identity: ${error.message}`);
633
- }
647
+ throw new BoundaryNonceError(`no boundary nonce survived ${MAX_NONCE_ATTEMPTS} attempts against ${blocks.length} blocks`);
648
+ }
649
+ function wrapBlock(tag, nonce, content) {
650
+ if (content.length === 0)
651
+ return "";
652
+ if (blockForgesNonce(content, nonce)) {
653
+ throw new BoundaryNonceError(`<${tag}> content carries the run's boundary nonce and could forge its own closing tag`);
654
+ }
655
+ return `<${tag} ${nonce}>
656
+ ${content}
657
+ </${tag} ${nonce}>`;
658
+ }
659
+ var BOUNDARY_NONCE_CHARS = 8, MAX_NONCE_ATTEMPTS = 16, BoundaryNonceError;
660
+ var init_boundary = __esm(() => {
661
+ BoundaryNonceError = class BoundaryNonceError extends Error {
662
+ };
663
+ });
664
+
665
+ // src/security/evidence-redaction.ts
666
+ 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) => {
668
+ try {
669
+ const url = new URL(text);
670
+ url.username = "";
671
+ url.password = "";
672
+ for (const key of [...url.searchParams.keys()])
673
+ if (SECRET.test(key))
674
+ url.searchParams.set(key, "[REDACTED]");
675
+ return url.toString();
676
+ } catch {
677
+ return "[REDACTED URL]";
634
678
  }
635
- if (a.role === "hunter") {
636
- hunterCount++;
637
- const specialty = a.specialty === undefined ? a.key : a.specialty;
638
- if (!diversityEnabled || a.models === undefined) {
639
- must(!hunterSpecialties.has(specialty), `agents[${i}] specialty "${specialty}" duplicates another hunter's effective specialty`);
640
- hunterSpecialties.add(specialty);
641
- }
642
- must(a.trigger === undefined || a.trigger === "input" || Array.isArray(a.trigger) && a.trigger.every((p) => typeof p === "string" && p.length > 0), `agents[${i}].trigger must be "input" or a string array`);
643
- } else {
644
- refuterCount++;
645
- must(a.specialty === undefined, `agents[${i}] is a refuter and cannot carry a specialty`);
646
- must(a.trigger === undefined, `agents[${i}] is a refuter and cannot carry a trigger`);
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]");
680
+ }
681
+ function redactEvidence(value, depth = 0, budget = { nodes: 0 }) {
682
+ if (++budget.nodes > 20000 || depth > 12)
683
+ throw new Error("capture shape limit");
684
+ if (typeof value === "string") {
685
+ if (value.length > MAX_BYTES)
686
+ throw new Error("capture string limit");
687
+ return redactEvidenceText(value);
688
+ }
689
+ if (value === null || typeof value === "boolean" || typeof value === "number")
690
+ return value;
691
+ if (value === undefined)
692
+ return null;
693
+ if (typeof value !== "object")
694
+ throw new Error("non-JSON capture value");
695
+ const proto = Object.getPrototypeOf(value);
696
+ if (proto !== Object.prototype && proto !== Array.prototype && proto !== null)
697
+ throw new Error("non-JSON capture object");
698
+ const result = {};
699
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
700
+ if (key === "length" && Array.isArray(value))
701
+ continue;
702
+ if (!("value" in descriptor))
703
+ throw new Error("capture accessor rejected");
704
+ if (!descriptor.enumerable)
705
+ continue;
706
+ result[key] = SECRET.test(key) ? "[REDACTED]" : redactEvidence(descriptor.value, depth + 1, budget);
707
+ }
708
+ return Array.isArray(value) ? Object.values(result) : result;
709
+ }
710
+ var MAX_BYTES, SECRET;
711
+ var init_evidence_redaction = __esm(() => {
712
+ MAX_BYTES = 4 * 1024 * 1024;
713
+ SECRET = /authorization|cookie|password|secret|api.?key|access.?token|refresh.?token|^token$|^key$/i;
714
+ });
715
+
716
+ // src/review/materiality-gate.ts
717
+ function isSafetyProtected(f) {
718
+ return SAFETY_PATTERN.test(f.claim) || SAFETY_PATTERN.test(f.path);
719
+ }
720
+ function codeWindow(fileText, line) {
721
+ const lines = fileText.split(`
722
+ `);
723
+ if (lines.length > 1 && lines.at(-1) === "")
724
+ lines.pop();
725
+ const first = Math.max(1, line - MATERIALITY_WINDOW_LINES);
726
+ const last = Math.min(lines.length, line + MATERIALITY_WINDOW_LINES);
727
+ const out = [];
728
+ for (let n = first;n <= last; n++) {
729
+ out.push(`${n}${n === line ? ">" : " "} ${lines[n - 1]}`);
730
+ }
731
+ return redactEvidenceText(out.join(`
732
+ `));
733
+ }
734
+ function renderMaterialityPrompt(input, nonce) {
735
+ const title = input.prTitle.replace(/\s+/g, " ").trim();
736
+ const claim = normalizeClaim(redactEvidenceText(input.claim));
737
+ if (/[\u0000-\u001f\u007f]/.test(input.path))
738
+ return null;
739
+ const filePath = input.path.replace(/\s+/g, " ").trim();
740
+ const window = input.window ?? "";
741
+ if ([title, claim, filePath, window].some((part) => blockForgesNonce(part, nonce))) {
742
+ return null;
743
+ }
744
+ const parts = [
745
+ "Pull request title:",
746
+ wrapBlock("pr_title", nonce, title),
747
+ "",
748
+ "Review comment:",
749
+ wrapBlock("review_comment", nonce, claim),
750
+ "",
751
+ `File: ${filePath}`
752
+ ];
753
+ if (input.window !== null) {
754
+ parts.push("", "Code:", wrapBlock("code_window", nonce, window));
755
+ }
756
+ return parts.join(`
757
+ `);
758
+ }
759
+ function materialityCandidates(findings, protectedIds = new Set) {
760
+ const judge = [];
761
+ let protectedCount = 0;
762
+ for (const f of findings) {
763
+ if (f.tier !== "blocking")
764
+ continue;
765
+ if (isProtected(f, protectedIds))
766
+ protectedCount++;
767
+ else
768
+ judge.push(f);
769
+ }
770
+ return { judge, protectedCount };
771
+ }
772
+ function isProtected(f, protectedIds) {
773
+ return isSafetyProtected(f) || f.id !== undefined && protectedIds.has(f.id);
774
+ }
775
+ function applyMaterialityVerdicts(findings, verdicts, protectedIds = new Set) {
776
+ return findings.map((f) => {
777
+ const verdict = verdicts.get(f.id);
778
+ if (f.tier !== "blocking" || verdict?.label !== "immaterial" || isProtected(f, protectedIds)) {
779
+ return f;
647
780
  }
781
+ return { ...f, tier: "advisory", materiality: verdict };
648
782
  });
649
- must(hunterCount >= 1, "spec needs at least one hunter");
650
- must(refuterCount <= 1, "spec allows at most one refuter");
651
- return spec;
652
- }
653
- function defaultReviewSpec() {
654
- return {
655
- agents: [
656
- {
657
- key: "reliability",
658
- file: "deep-review-reliability.md",
659
- role: "hunter"
660
- },
661
- { key: "resilience", file: "deep-review-resilience.md", role: "hunter" },
662
- {
663
- key: "parity",
664
- file: "deep-review-parity.md",
665
- role: "hunter",
666
- trigger: "input"
667
- },
668
- { key: "refuter", file: "review-refuter.md", role: "refuter" }
669
- ]
670
- };
671
783
  }
672
- var SAFE_SLUG_RE, ReviewSpecValidationError;
673
- var init_spec = __esm(() => {
674
- init_routing();
675
- SAFE_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
676
- ReviewSpecValidationError = class ReviewSpecValidationError extends Error {
677
- };
784
+ var SAFETY_PATTERN, MATERIALITY_WINDOW_LINES = 25;
785
+ var init_materiality_gate = __esm(() => {
786
+ init_materiality();
787
+ init_boundary();
788
+ init_evidence_redaction();
789
+ SAFETY_PATTERN = /\b(auth\w*|credential\w*|secret\w*|passw\w*|token\w*|api[ _-]?key\w*|permission\w*|privilege\w*|access[ -]control|sandbox\w*|symlink\w*|isolation|escap\w+ (the )?(sandbox|worktree)|inject\w*|xss|csrf|ssrf|rce|traversal|sanitiz\w*|encrypt\w*|decrypt\w*|signature\w*|verif\w+ (the )?signature|data loss|lose[sd]? (the )?(data|rows|records|findings|audit)|corrupt\w*|overwrit\w+|delet\w+ (the )?(user|data|rows|records|cache)|leak\w* (the )?(secret|token|credential|key)|lost[ -]update\w*|los[et]s? (the )?(user'?s? |concurrent |other )?(edit|update|write|change)s?|silently (drop|discard|overwrit|delet|lost)\w*|(is|are|gets?) (silently )?lost|hard[- ]delet\w*|(race|concurren\w*)[^.]{0,80}(overwrit|delet|hard-delet|clobber|drop)\w*)\b/i;
678
790
  });
679
791
 
680
792
  // src/review/findings.ts
@@ -690,20 +802,20 @@ function isValidSpecialtySlug(value) {
690
802
  return value.length >= 1 && value.length <= 64 && SPECIALTY_SLUG_RE.test(value);
691
803
  }
692
804
  function validateEngineString(value, label) {
693
- must3(typeof value === "string", `${label} required`);
805
+ must(typeof value === "string", `${label} required`);
694
806
  const raw = value;
695
807
  const trimmed = raw.trim();
696
- must3(trimmed === raw, `${label} must be trimmed`);
697
- must3(trimmed.length >= 1 && trimmed.length <= 128, `${label} must be 1-128 characters`);
698
- must3(isControlFree(trimmed), `${label} must not contain control characters`);
808
+ must(trimmed === raw, `${label} must be trimmed`);
809
+ must(trimmed.length >= 1 && trimmed.length <= 128, `${label} must be 1-128 characters`);
810
+ must(isControlFree(trimmed), `${label} must not contain control characters`);
699
811
  return trimmed;
700
812
  }
701
813
  function validateEngineIdentity(candidate, options) {
702
814
  if (candidate === undefined) {
703
- must3(!options.required, "engine required");
815
+ must(!options.required, "engine required");
704
816
  return;
705
817
  }
706
- must3(typeof candidate === "object" && candidate !== null, "engine must be an object");
818
+ must(typeof candidate === "object" && candidate !== null, "engine must be an object");
707
819
  const engine = candidate;
708
820
  const name = validateEngineString(engine.name, "engine.name");
709
821
  const version = validateEngineString(engine.version, "engine.version");
@@ -714,91 +826,91 @@ function validateEngineIdentity(candidate, options) {
714
826
  ...revision === undefined ? {} : { revision }
715
827
  };
716
828
  }
717
- function must3(condition, message) {
829
+ function must(condition, message) {
718
830
  if (!condition)
719
831
  throw new FindingsValidationError(message);
720
832
  }
721
- function normalizeOptionalString2(f, key, label) {
833
+ function normalizeOptionalString(f, key, label) {
722
834
  if (f[key] === null) {
723
835
  delete f[key];
724
836
  return;
725
837
  }
726
- must3(f[key] === undefined || typeof f[key] === "string", `${label} must be a string when present`);
838
+ must(f[key] === undefined || typeof f[key] === "string", `${label} must be a string when present`);
727
839
  }
728
840
  function validateFinding(candidate, index) {
729
- must3(typeof candidate === "object" && candidate !== null, `findings[${index}] must be an object`);
841
+ must(typeof candidate === "object" && candidate !== null, `findings[${index}] must be an object`);
730
842
  const f = candidate;
731
- must3(typeof f.id === "string" && f.id.length > 0, `findings[${index}].id required`);
732
- must3(typeof f.category === "number" && f.category >= 1 && f.category <= 14, `findings[${index}].category must be 1-14`);
733
- must3(typeof f.path === "string" && f.path.length > 0, `findings[${index}].path required`);
734
- must3(typeof f.line === "number", `findings[${index}].line must be a number`);
735
- must3(SEVERITIES2.includes(f.severity), `findings[${index}].severity invalid`);
736
- must3(EVIDENCE_CLASSES2.includes(f.evidence_class), `findings[${index}].evidence_class invalid`);
737
- must3(REFUTER_VERDICTS.includes(f.refuter_verdict), `findings[${index}].refuter_verdict invalid`);
738
- must3(CAUSAL_DISPOSITIONS2.includes(f.causal_disposition), `findings[${index}].causal_disposition invalid`);
739
- must3(typeof f.claim === "string" && f.claim.length > 0, `findings[${index}].claim required`);
740
- must3(Array.isArray(f.proof_refs), `findings[${index}].proof_refs must be an array`);
741
- must3(HUNTERS.includes(f.hunter), `findings[${index}].hunter invalid`);
742
- must3(TIERS.includes(f.tier), `findings[${index}].tier invalid`);
743
- must3(typeof f.hops_used === "number", `findings[${index}].hops_used must be a number`);
744
- must3(Array.isArray(f.hop_trail), `findings[${index}].hop_trail must be an array`);
745
- must3(typeof f.dedupe_key === "string" && f.dedupe_key.length > 0, `findings[${index}].dedupe_key required`);
746
- must3(f.proof_refs.every((ref) => typeof ref === "string"), `findings[${index}].proof_refs must contain only strings`);
747
- normalizeOptionalString2(f, "symbol", `findings[${index}].symbol`);
748
- normalizeOptionalString2(f, "root_cause_id", `findings[${index}].root_cause_id`);
843
+ must(typeof f.id === "string" && f.id.length > 0, `findings[${index}].id required`);
844
+ must(typeof f.category === "number" && f.category >= 1 && f.category <= 14, `findings[${index}].category must be 1-14`);
845
+ must(typeof f.path === "string" && f.path.length > 0, `findings[${index}].path required`);
846
+ must(typeof f.line === "number", `findings[${index}].line must be a number`);
847
+ must(SEVERITIES.includes(f.severity), `findings[${index}].severity invalid`);
848
+ must(EVIDENCE_CLASSES.includes(f.evidence_class), `findings[${index}].evidence_class invalid`);
849
+ must(REFUTER_VERDICTS.includes(f.refuter_verdict), `findings[${index}].refuter_verdict invalid`);
850
+ must(CAUSAL_DISPOSITIONS.includes(f.causal_disposition), `findings[${index}].causal_disposition invalid`);
851
+ must(typeof f.claim === "string" && f.claim.length > 0, `findings[${index}].claim required`);
852
+ must(Array.isArray(f.proof_refs), `findings[${index}].proof_refs must be an array`);
853
+ must(HUNTERS.includes(f.hunter), `findings[${index}].hunter invalid`);
854
+ must(TIERS.includes(f.tier), `findings[${index}].tier invalid`);
855
+ must(typeof f.hops_used === "number", `findings[${index}].hops_used must be a number`);
856
+ must(Array.isArray(f.hop_trail), `findings[${index}].hop_trail must be an array`);
857
+ must(typeof f.dedupe_key === "string" && f.dedupe_key.length > 0, `findings[${index}].dedupe_key required`);
858
+ must(f.proof_refs.every((ref) => typeof ref === "string"), `findings[${index}].proof_refs must contain only strings`);
859
+ normalizeOptionalString(f, "symbol", `findings[${index}].symbol`);
860
+ normalizeOptionalString(f, "root_cause_id", `findings[${index}].root_cause_id`);
749
861
  return f;
750
862
  }
751
863
  function validateFindingV11(candidate, index) {
752
- must3(typeof candidate === "object" && candidate !== null, `findings[${index}] must be an object`);
864
+ must(typeof candidate === "object" && candidate !== null, `findings[${index}] must be an object`);
753
865
  const f = candidate;
754
- must3(typeof f.id === "string" && f.id.length > 0, `findings[${index}].id required`);
755
- must3(typeof f.category === "number" && f.category >= 1 && f.category <= 15, `findings[${index}].category must be 1-15`);
756
- must3(typeof f.path === "string" && f.path.length > 0, `findings[${index}].path required`);
757
- must3(typeof f.line === "number", `findings[${index}].line must be a number`);
758
- must3(SEVERITIES2.includes(f.severity), `findings[${index}].severity invalid`);
759
- must3(EVIDENCE_CLASSES2.includes(f.evidence_class), `findings[${index}].evidence_class invalid`);
760
- must3(REFUTER_VERDICTS.includes(f.refuter_verdict), `findings[${index}].refuter_verdict invalid`);
761
- must3(CAUSAL_DISPOSITIONS2.includes(f.causal_disposition), `findings[${index}].causal_disposition invalid`);
762
- must3(typeof f.claim === "string" && f.claim.length > 0, `findings[${index}].claim required`);
763
- must3(Array.isArray(f.proof_refs), `findings[${index}].proof_refs must be an array`);
764
- must3(typeof f.hunter === "string" && isValidSpecialtySlug(f.hunter), `findings[${index}].hunter invalid`);
765
- must3(TIERS.includes(f.tier), `findings[${index}].tier invalid`);
766
- must3(typeof f.hops_used === "number", `findings[${index}].hops_used must be a number`);
767
- must3(Array.isArray(f.hop_trail), `findings[${index}].hop_trail must be an array`);
768
- must3(typeof f.dedupe_key === "string" && f.dedupe_key.length > 0, `findings[${index}].dedupe_key required`);
769
- must3(f.proof_refs.every((ref) => typeof ref === "string"), `findings[${index}].proof_refs must contain only strings`);
770
- normalizeOptionalString2(f, "symbol", `findings[${index}].symbol`);
771
- normalizeOptionalString2(f, "root_cause_id", `findings[${index}].root_cause_id`);
866
+ must(typeof f.id === "string" && f.id.length > 0, `findings[${index}].id required`);
867
+ must(typeof f.category === "number" && f.category >= 1 && f.category <= 15, `findings[${index}].category must be 1-15`);
868
+ must(typeof f.path === "string" && f.path.length > 0, `findings[${index}].path required`);
869
+ must(typeof f.line === "number", `findings[${index}].line must be a number`);
870
+ must(SEVERITIES.includes(f.severity), `findings[${index}].severity invalid`);
871
+ must(EVIDENCE_CLASSES.includes(f.evidence_class), `findings[${index}].evidence_class invalid`);
872
+ must(REFUTER_VERDICTS.includes(f.refuter_verdict), `findings[${index}].refuter_verdict invalid`);
873
+ must(CAUSAL_DISPOSITIONS.includes(f.causal_disposition), `findings[${index}].causal_disposition invalid`);
874
+ must(typeof f.claim === "string" && f.claim.length > 0, `findings[${index}].claim required`);
875
+ must(Array.isArray(f.proof_refs), `findings[${index}].proof_refs must be an array`);
876
+ must(typeof f.hunter === "string" && isValidSpecialtySlug(f.hunter), `findings[${index}].hunter invalid`);
877
+ must(TIERS.includes(f.tier), `findings[${index}].tier invalid`);
878
+ must(typeof f.hops_used === "number", `findings[${index}].hops_used must be a number`);
879
+ must(Array.isArray(f.hop_trail), `findings[${index}].hop_trail must be an array`);
880
+ must(typeof f.dedupe_key === "string" && f.dedupe_key.length > 0, `findings[${index}].dedupe_key required`);
881
+ must(f.proof_refs.every((ref) => typeof ref === "string"), `findings[${index}].proof_refs must contain only strings`);
882
+ normalizeOptionalString(f, "symbol", `findings[${index}].symbol`);
883
+ normalizeOptionalString(f, "root_cause_id", `findings[${index}].root_cause_id`);
772
884
  return f;
773
885
  }
774
886
  function validateDocumentSummary(d) {
775
887
  if (d.summary === undefined)
776
888
  return;
777
- must3(typeof d.summary === "object" && d.summary !== null, "summary must be an object when present");
889
+ must(typeof d.summary === "object" && d.summary !== null, "summary must be an object when present");
778
890
  const summary = d.summary;
779
- must3(typeof summary.prose === "string" && summary.prose.length > 0, "summary.prose required");
780
- must3(typeof summary.prose === "string" && summary.prose.length <= 1200, "summary.prose must be at most 1200 characters");
781
- must3(typeof summary.score === "number" && Number.isInteger(summary.score) && summary.score >= 1 && summary.score <= 5, "summary.score must be an integer 1-5");
782
- must3(typeof summary.score_reason === "string" && summary.score_reason.length > 0, "summary.score_reason required");
783
- must3(typeof summary.score_reason === "string" && summary.score_reason.length <= 400, "summary.score_reason must be at most 400 characters");
891
+ must(typeof summary.prose === "string" && summary.prose.length > 0, "summary.prose required");
892
+ must(typeof summary.prose === "string" && summary.prose.length <= 1200, "summary.prose must be at most 1200 characters");
893
+ must(typeof summary.score === "number" && Number.isInteger(summary.score) && summary.score >= 1 && summary.score <= 5, "summary.score must be an integer 1-5");
894
+ must(typeof summary.score_reason === "string" && summary.score_reason.length > 0, "summary.score_reason required");
895
+ must(typeof summary.score_reason === "string" && summary.score_reason.length <= 400, "summary.score_reason must be at most 400 characters");
784
896
  const prose = summary.prose;
785
897
  const scoreReason = summary.score_reason;
786
- must3(!prose.includes("<!--") && !prose.includes("-->") && !scoreReason.includes("<!--") && !scoreReason.includes("-->"), "summary strings must not contain HTML comment markers");
898
+ must(!prose.includes("<!--") && !prose.includes("-->") && !scoreReason.includes("<!--") && !scoreReason.includes("-->"), "summary strings must not contain HTML comment markers");
787
899
  }
788
900
  function validateDocumentEnvelope(d) {
789
- must3(typeof d.pr === "number", "pr must be a number");
790
- must3(typeof d.base_sha === "string" && d.base_sha.length > 0, "base_sha required");
791
- must3(typeof d.head_sha === "string" && d.head_sha.length > 0, "head_sha required");
792
- must3(typeof d.model === "string" && d.model.length > 0, "model required");
793
- must3(typeof d.iteration === "number", "iteration must be a number");
794
- must3(typeof d.parity_hunter_fired === "boolean", "parity_hunter_fired must be a boolean");
795
- must3(d.run_status === "complete" || d.run_status === "partial", "run_status must be complete|partial");
796
- must3(d.sessionFailed === undefined || typeof d.sessionFailed === "boolean", "sessionFailed must be a boolean when present");
901
+ must(typeof d.pr === "number", "pr must be a number");
902
+ must(typeof d.base_sha === "string" && d.base_sha.length > 0, "base_sha required");
903
+ must(typeof d.head_sha === "string" && d.head_sha.length > 0, "head_sha required");
904
+ must(typeof d.model === "string" && d.model.length > 0, "model required");
905
+ must(typeof d.iteration === "number", "iteration must be a number");
906
+ must(typeof d.parity_hunter_fired === "boolean", "parity_hunter_fired must be a boolean");
907
+ must(d.run_status === "complete" || d.run_status === "partial", "run_status must be complete|partial");
908
+ must(d.sessionFailed === undefined || typeof d.sessionFailed === "boolean", "sessionFailed must be a boolean when present");
797
909
  validateDocumentSummary(d);
798
- must3(typeof d.telemetry === "object" && d.telemetry !== null, "telemetry required");
799
- must3(Array.isArray(d.findings), "findings must be an array");
910
+ must(typeof d.telemetry === "object" && d.telemetry !== null, "telemetry required");
911
+ must(Array.isArray(d.findings), "findings must be an array");
800
912
  const debug = d.debug;
801
- must3(!!debug && Array.isArray(debug.refuted), "debug.refuted must be an array");
913
+ must(!!debug && Array.isArray(debug.refuted), "debug.refuted must be an array");
802
914
  }
803
915
  function validateFindingsDocumentV10(d) {
804
916
  d.findings.forEach((f, i) => {
@@ -814,20 +926,28 @@ function validateFindingsDocumentV11(d) {
814
926
  return d;
815
927
  }
816
928
  function validateFindingsDocument(candidate) {
817
- must3(typeof candidate === "object" && candidate !== null, "findings document must be an object");
929
+ must(typeof candidate === "object" && candidate !== null, "findings document must be an object");
818
930
  const d = candidate;
819
931
  const version = d.schema_version;
820
- must3(SUPPORTED_SCHEMA_VERSIONS.includes(version), `schema_version must be ${SCHEMA_VERSION} or ${SCHEMA_VERSION_V1_1}`);
932
+ must(SUPPORTED_SCHEMA_VERSIONS.includes(version), `schema_version must be ${SCHEMA_VERSION} or ${SCHEMA_VERSION_V1_1}`);
821
933
  validateDocumentEnvelope(d);
822
934
  if (version === SCHEMA_VERSION) {
823
935
  return validateFindingsDocumentV10(d);
824
936
  }
825
937
  return validateFindingsDocumentV11(d);
826
938
  }
939
+ function isNotCausedByPr(disposition) {
940
+ return disposition === "pre-existing" || disposition === "base-only";
941
+ }
942
+ function isCausallyExempt(finding) {
943
+ return isNotCausedByPr(finding.causal_disposition) && !isSafetyProtected({ claim: finding.claim, path: finding.path });
944
+ }
827
945
  function deriveTier(finding, options = {}) {
828
946
  const isBlockerClass = finding.severity === "BLOCKER" || finding.severity === "CRITICAL";
829
947
  if (!isBlockerClass)
830
948
  return "advisory";
949
+ if (isCausallyExempt(finding))
950
+ return "advisory";
831
951
  if (finding.evidence_class === "insufficient")
832
952
  return "advisory";
833
953
  if (finding.refuter_verdict === "downgraded-latent")
@@ -864,10 +984,11 @@ async function writeFindings(outPath, doc) {
864
984
  await Bun.write(outPath, `${JSON.stringify(validated, null, 2)}
865
985
  `);
866
986
  }
867
- var SCHEMA_VERSION = "1.0.0", SCHEMA_VERSION_V1_1 = "1.1.0", SEVERITIES2, EVIDENCE_CLASSES2, REFUTER_VERDICTS, CAUSAL_DISPOSITIONS2, TIERS, HUNTERS, SPECIALTY_SLUG_RE, SUPPORTED_SCHEMA_VERSIONS, FindingsValidationError;
987
+ var SCHEMA_VERSION = "1.0.0", SCHEMA_VERSION_V1_1 = "1.1.0", SEVERITIES, EVIDENCE_CLASSES, REFUTER_VERDICTS, CAUSAL_DISPOSITIONS, TIERS, HUNTERS, SPECIALTY_SLUG_RE, SUPPORTED_SCHEMA_VERSIONS, FindingsValidationError;
868
988
  var init_findings = __esm(() => {
869
- SEVERITIES2 = ["BLOCKER", "CRITICAL", "WARNING", "SUGGESTION"];
870
- EVIDENCE_CLASSES2 = [
989
+ init_materiality_gate();
990
+ SEVERITIES = ["BLOCKER", "CRITICAL", "WARNING", "SUGGESTION"];
991
+ EVIDENCE_CLASSES = [
871
992
  "deterministic",
872
993
  "inferential",
873
994
  "insufficient"
@@ -879,7 +1000,7 @@ var init_findings = __esm(() => {
879
1000
  "downgraded-latent",
880
1001
  "not_submitted"
881
1002
  ];
882
- CAUSAL_DISPOSITIONS2 = [
1003
+ CAUSAL_DISPOSITIONS = [
883
1004
  "introduced",
884
1005
  "behavior-activated",
885
1006
  "worsened",
@@ -898,65 +1019,166 @@ var init_findings = __esm(() => {
898
1019
  };
899
1020
  });
900
1021
 
901
- // src/review/findings-conformance.ts
902
- function envelope(schemaVersion, finding, engine) {
903
- const engineField = engine === undefined ? "" : `,"engine":${engine}`;
904
- return `{"schema_version":"${schemaVersion}","pr":1,"base_sha":"abc","head_sha":"def","model":"sonnet","iteration":1,"parity_hunter_fired":false,"run_status":"complete","telemetry":${TELEMETRY}${engineField},"findings":[${finding}],"debug":{"refuted":[]}}`;
1022
+ // src/review/spec.ts
1023
+ function isSafeSlug(value) {
1024
+ return value.length >= 1 && value.length <= 64 && SAFE_SLUG_RE.test(value);
905
1025
  }
906
- var FINDING_V10 = '{"id":"F001","category":1,"path":"src/a.ts","line":1,"severity":"BLOCKER","evidence_class":"deterministic","refuter_verdict":"not_submitted","causal_disposition":"introduced","claim":"x","proof_refs":[],"hunter":"reliability","tier":"blocking","hops_used":0,"hop_trail":[],"dedupe_key":"k"}', FINDING_V11_SECURITY = '{"id":"F001","category":1,"path":"src/a.ts","line":1,"severity":"BLOCKER","evidence_class":"deterministic","refuter_verdict":"not_submitted","causal_disposition":"introduced","claim":"x","proof_refs":[],"hunter":"security","tier":"blocking","hops_used":0,"hop_trail":[],"dedupe_key":"k"}', FINDING_V11_CODE_QUALITY = '{"id":"F001","category":1,"path":"src/a.ts","line":1,"severity":"BLOCKER","evidence_class":"deterministic","refuter_verdict":"not_submitted","causal_disposition":"introduced","claim":"x","proof_refs":[],"hunter":"code-quality","tier":"blocking","hops_used":0,"hop_trail":[],"dedupe_key":"k"}', FINDING_V11_BAD_HUNTER = '{"id":"F001","category":1,"path":"src/a.ts","line":1,"severity":"BLOCKER","evidence_class":"deterministic","refuter_verdict":"not_submitted","causal_disposition":"introduced","claim":"x","proof_refs":[],"hunter":"Security","tier":"blocking","hops_used":0,"hop_trail":[],"dedupe_key":"k"}', TELEMETRY = '{"index_ms":1,"index_mode":"fresh","index_disk_mb":1,"wall_ms":1,"tokens_in":1,"tokens_out":1,"tokens_total":2,"cost_usd_est":0.1}', FINDINGS_CONFORMANCE_CASES;
907
- var init_findings_conformance = __esm(() => {
908
- FINDINGS_CONFORMANCE_CASES = [
909
- {
910
- id: "v10-minimal-closed-hunter",
911
- raw: envelope("1.0.0", FINDING_V10),
912
- expect: "accept"
913
- },
914
- {
915
- id: "v10-optional-engine",
916
- raw: envelope("1.0.0", FINDING_V10, '{"name":"pr-hero","version":"1.0.0"}'),
917
- expect: "accept"
918
- },
919
- {
920
- id: "v10-rejects-open-hunter",
921
- raw: envelope("1.0.0", FINDING_V11_SECURITY),
922
- expect: "reject"
923
- },
924
- {
925
- id: "v11-arbitrary-specialty-slug",
926
- raw: envelope("1.1.0", FINDING_V11_SECURITY, '{"name":"pr-hero","version":"1.0.0"}'),
927
- expect: "accept"
928
- },
929
- {
930
- id: "v11-hyphenated-specialty-slug",
931
- raw: envelope("1.1.0", FINDING_V11_CODE_QUALITY, '{"name":"pr-hero","version":"1.0.0"}'),
932
- expect: "accept"
933
- },
934
- {
935
- id: "v11-optional-revision",
936
- raw: envelope("1.1.0", FINDING_V11_SECURITY, '{"name":"pr-hero","version":"1.0.0","revision":"abc123"}'),
937
- expect: "accept"
938
- },
939
- {
940
- id: "v11-missing-engine",
941
- raw: envelope("1.1.0", FINDING_V11_SECURITY),
942
- expect: "reject"
943
- },
944
- {
945
- id: "v11-invalid-hunter-slug",
946
- raw: envelope("1.1.0", FINDING_V11_BAD_HUNTER, '{"name":"pr-hero","version":"1.0.0"}'),
947
- expect: "reject"
948
- },
949
- {
950
- id: "v11-engine-name-untrimmed",
951
- raw: envelope("1.1.0", FINDING_V11_SECURITY, '{"name":" pr-hero","version":"1.0.0"}'),
952
- expect: "reject"
953
- },
954
- {
955
- id: "v11-engine-revision-control-char",
956
- raw: envelope("1.1.0", FINDING_V11_SECURITY, '{"name":"pr-hero","version":"1.0.0","revision":"bad\\u0007"}'),
957
- expect: "reject"
958
- },
959
- {
1026
+ function resolveSpecialty(agent) {
1027
+ return agent.specialty ?? agent.key;
1028
+ }
1029
+ function must2(condition, message) {
1030
+ if (!condition)
1031
+ throw new ReviewSpecValidationError(message);
1032
+ }
1033
+ function validateReviewSpec(candidate) {
1034
+ must2(typeof candidate === "object" && candidate !== null, "review spec must be an object");
1035
+ const spec = candidate;
1036
+ must2(Array.isArray(spec.agents), "spec.agents must be an array");
1037
+ const diversityEnabled = spec.multiModelDiversity !== undefined && typeof spec.multiModelDiversity === "object" && spec.multiModelDiversity !== null && spec.multiModelDiversity.enabled === true;
1038
+ if (spec.multiModelDiversity !== undefined) {
1039
+ const diversity = spec.multiModelDiversity;
1040
+ must2(diversity.enabled === true, "multiModelDiversity.enabled must be true when present");
1041
+ must2(typeof diversity.armId === "string" && isSafeSlug(diversity.armId), "multiModelDiversity.armId must be a safe slug");
1042
+ must2(typeof diversity.maxLegs === "number" && Number.isInteger(diversity.maxLegs) && diversity.maxLegs >= 1, "multiModelDiversity.maxLegs must be a positive integer");
1043
+ must2(typeof diversity.cashCapUsd === "number" && Number.isFinite(diversity.cashCapUsd) && diversity.cashCapUsd > 0, "multiModelDiversity.cashCapUsd must be a positive number");
1044
+ }
1045
+ const agents = spec.agents;
1046
+ const keys = new Set;
1047
+ const hunterSpecialties = new Set;
1048
+ let hunterCount = 0;
1049
+ let refuterCount = 0;
1050
+ agents.forEach((entry, i) => {
1051
+ must2(typeof entry === "object" && entry !== null, `agents[${i}] must be an object`);
1052
+ const a = entry;
1053
+ must2(typeof a.key === "string" && a.key.length > 0, `agents[${i}].key required`);
1054
+ must2(isSafeSlug(a.key), `agents[${i}].key "${a.key}" is not a safe slug (^[a-z0-9]+(?:-[a-z0-9]+)*$, 1-64 chars)`);
1055
+ must2(!keys.has(a.key), `agents[${i}].key duplicates "${a.key}"`);
1056
+ keys.add(a.key);
1057
+ must2(a.specialty === undefined || typeof a.specialty === "string" && isSafeSlug(a.specialty), `agents[${i}].specialty must be a safe slug when present`);
1058
+ must2(typeof a.file === "string" && a.file.length > 0, `agents[${i}].file required`);
1059
+ must2(a.role === "hunter" || a.role === "refuter", `agents[${i}].role must be hunter|refuter`);
1060
+ must2(a.models === undefined || diversityEnabled && Array.isArray(a.models) && a.models.length >= 1 && a.models.every((model) => typeof model === "string" && model.length > 0), diversityEnabled ? `agents[${i}].models must be a non-empty string array when multiModelDiversity is enabled` : `agents[${i}].models is not supported in D2; fan-out is a D3 capability`);
1061
+ if (diversityEnabled && Array.isArray(a.models)) {
1062
+ for (const model of a.models) {
1063
+ try {
1064
+ parseLogicalIdentity(model);
1065
+ } catch (error) {
1066
+ must2(false, `agents[${i}].models contains invalid model identity "${model}": ${error.message}`);
1067
+ }
1068
+ }
1069
+ }
1070
+ must2(a.model === undefined || typeof a.model === "string" && a.model.length > 0, `agents[${i}].model must be a non-empty string when present`);
1071
+ if (a.model !== undefined) {
1072
+ try {
1073
+ parseLogicalIdentity(a.model);
1074
+ } catch (error) {
1075
+ must2(false, `agents[${i}].model "${a.model}" is not a valid model identity: ${error.message}`);
1076
+ }
1077
+ }
1078
+ if (a.role === "hunter") {
1079
+ hunterCount++;
1080
+ const specialty = a.specialty === undefined ? a.key : a.specialty;
1081
+ if (!diversityEnabled || a.models === undefined) {
1082
+ must2(!hunterSpecialties.has(specialty), `agents[${i}] specialty "${specialty}" duplicates another hunter's effective specialty`);
1083
+ hunterSpecialties.add(specialty);
1084
+ }
1085
+ must2(a.trigger === undefined || a.trigger === "input" || Array.isArray(a.trigger) && a.trigger.every((p) => typeof p === "string" && p.length > 0), `agents[${i}].trigger must be "input" or a string array`);
1086
+ } else {
1087
+ refuterCount++;
1088
+ must2(a.specialty === undefined, `agents[${i}] is a refuter and cannot carry a specialty`);
1089
+ must2(a.trigger === undefined, `agents[${i}] is a refuter and cannot carry a trigger`);
1090
+ }
1091
+ });
1092
+ must2(hunterCount >= 1, "spec needs at least one hunter");
1093
+ must2(refuterCount <= 1, "spec allows at most one refuter");
1094
+ return spec;
1095
+ }
1096
+ function defaultReviewSpec() {
1097
+ return {
1098
+ agents: [
1099
+ {
1100
+ key: "reliability",
1101
+ file: "deep-review-reliability.md",
1102
+ role: "hunter"
1103
+ },
1104
+ { key: "resilience", file: "deep-review-resilience.md", role: "hunter" },
1105
+ {
1106
+ key: "parity",
1107
+ file: "deep-review-parity.md",
1108
+ role: "hunter",
1109
+ trigger: "input"
1110
+ },
1111
+ { key: "refuter", file: "review-refuter.md", role: "refuter" }
1112
+ ]
1113
+ };
1114
+ }
1115
+ var SAFE_SLUG_RE, ReviewSpecValidationError;
1116
+ var init_spec = __esm(() => {
1117
+ init_routing();
1118
+ SAFE_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
1119
+ ReviewSpecValidationError = class ReviewSpecValidationError extends Error {
1120
+ };
1121
+ });
1122
+
1123
+ // src/review/findings-conformance.ts
1124
+ function envelope(schemaVersion, finding, engine) {
1125
+ const engineField = engine === undefined ? "" : `,"engine":${engine}`;
1126
+ return `{"schema_version":"${schemaVersion}","pr":1,"base_sha":"abc","head_sha":"def","model":"sonnet","iteration":1,"parity_hunter_fired":false,"run_status":"complete","telemetry":${TELEMETRY}${engineField},"findings":[${finding}],"debug":{"refuted":[]}}`;
1127
+ }
1128
+ var FINDING_V10 = '{"id":"F001","category":1,"path":"src/a.ts","line":1,"severity":"BLOCKER","evidence_class":"deterministic","refuter_verdict":"not_submitted","causal_disposition":"introduced","claim":"x","proof_refs":[],"hunter":"reliability","tier":"blocking","hops_used":0,"hop_trail":[],"dedupe_key":"k"}', FINDING_V11_SECURITY = '{"id":"F001","category":1,"path":"src/a.ts","line":1,"severity":"BLOCKER","evidence_class":"deterministic","refuter_verdict":"not_submitted","causal_disposition":"introduced","claim":"x","proof_refs":[],"hunter":"security","tier":"blocking","hops_used":0,"hop_trail":[],"dedupe_key":"k"}', FINDING_V11_CODE_QUALITY = '{"id":"F001","category":1,"path":"src/a.ts","line":1,"severity":"BLOCKER","evidence_class":"deterministic","refuter_verdict":"not_submitted","causal_disposition":"introduced","claim":"x","proof_refs":[],"hunter":"code-quality","tier":"blocking","hops_used":0,"hop_trail":[],"dedupe_key":"k"}', FINDING_V11_BAD_HUNTER = '{"id":"F001","category":1,"path":"src/a.ts","line":1,"severity":"BLOCKER","evidence_class":"deterministic","refuter_verdict":"not_submitted","causal_disposition":"introduced","claim":"x","proof_refs":[],"hunter":"Security","tier":"blocking","hops_used":0,"hop_trail":[],"dedupe_key":"k"}', TELEMETRY = '{"index_ms":1,"index_mode":"fresh","index_disk_mb":1,"wall_ms":1,"tokens_in":1,"tokens_out":1,"tokens_total":2,"cost_usd_est":0.1}', FINDINGS_CONFORMANCE_CASES;
1129
+ var init_findings_conformance = __esm(() => {
1130
+ FINDINGS_CONFORMANCE_CASES = [
1131
+ {
1132
+ id: "v10-minimal-closed-hunter",
1133
+ raw: envelope("1.0.0", FINDING_V10),
1134
+ expect: "accept"
1135
+ },
1136
+ {
1137
+ id: "v10-optional-engine",
1138
+ raw: envelope("1.0.0", FINDING_V10, '{"name":"pr-hero","version":"1.0.0"}'),
1139
+ expect: "accept"
1140
+ },
1141
+ {
1142
+ id: "v10-rejects-open-hunter",
1143
+ raw: envelope("1.0.0", FINDING_V11_SECURITY),
1144
+ expect: "reject"
1145
+ },
1146
+ {
1147
+ id: "v11-arbitrary-specialty-slug",
1148
+ raw: envelope("1.1.0", FINDING_V11_SECURITY, '{"name":"pr-hero","version":"1.0.0"}'),
1149
+ expect: "accept"
1150
+ },
1151
+ {
1152
+ id: "v11-hyphenated-specialty-slug",
1153
+ raw: envelope("1.1.0", FINDING_V11_CODE_QUALITY, '{"name":"pr-hero","version":"1.0.0"}'),
1154
+ expect: "accept"
1155
+ },
1156
+ {
1157
+ id: "v11-optional-revision",
1158
+ raw: envelope("1.1.0", FINDING_V11_SECURITY, '{"name":"pr-hero","version":"1.0.0","revision":"abc123"}'),
1159
+ expect: "accept"
1160
+ },
1161
+ {
1162
+ id: "v11-missing-engine",
1163
+ raw: envelope("1.1.0", FINDING_V11_SECURITY),
1164
+ expect: "reject"
1165
+ },
1166
+ {
1167
+ id: "v11-invalid-hunter-slug",
1168
+ raw: envelope("1.1.0", FINDING_V11_BAD_HUNTER, '{"name":"pr-hero","version":"1.0.0"}'),
1169
+ expect: "reject"
1170
+ },
1171
+ {
1172
+ id: "v11-engine-name-untrimmed",
1173
+ raw: envelope("1.1.0", FINDING_V11_SECURITY, '{"name":" pr-hero","version":"1.0.0"}'),
1174
+ expect: "reject"
1175
+ },
1176
+ {
1177
+ id: "v11-engine-revision-control-char",
1178
+ raw: envelope("1.1.0", FINDING_V11_SECURITY, '{"name":"pr-hero","version":"1.0.0","revision":"bad\\u0007"}'),
1179
+ expect: "reject"
1180
+ },
1181
+ {
960
1182
  id: "unknown-schema-version",
961
1183
  raw: envelope("0.9.0", FINDING_V10),
962
1184
  expect: "reject"
@@ -1372,7 +1594,8 @@ var init_outcome = __esm(() => {
1372
1594
  "size",
1373
1595
  "budget",
1374
1596
  "coverage",
1375
- "manual-required"
1597
+ "manual-required",
1598
+ "excluded"
1376
1599
  ];
1377
1600
  CLI_HEAD_PATTERN = /^[0-9a-f]{40}$/;
1378
1601
  CLAUDE_SUBSCRIPTION_FIXES = [
@@ -2016,6 +2239,25 @@ var init_review_policy = __esm(() => {
2016
2239
  ];
2017
2240
  });
2018
2241
 
2242
+ // src/pr/post-floor.ts
2243
+ function isBelowPostFloor(finding, floor) {
2244
+ if (finding.tier === "blocking")
2245
+ return false;
2246
+ if (floor === "blocking")
2247
+ return true;
2248
+ if (floor === "warning")
2249
+ return finding.severity === "SUGGESTION";
2250
+ return false;
2251
+ }
2252
+ var POST_MIN_SEVERITIES;
2253
+ var init_post_floor = __esm(() => {
2254
+ POST_MIN_SEVERITIES = [
2255
+ "suggestion",
2256
+ "warning",
2257
+ "blocking"
2258
+ ];
2259
+ });
2260
+
2019
2261
  // src/triage/triage.ts
2020
2262
  function triageBadge(fields) {
2021
2263
  const badge = TRIAGE_BADGE[fields.tag];
@@ -2168,6 +2410,10 @@ var init_deep_review_resilience = () => {};
2168
2410
  var review_refuter_default = "./review-refuter-j4e9gezy.md";
2169
2411
  var init_review_refuter = () => {};
2170
2412
 
2413
+ // prompts/materiality.md
2414
+ var materiality_default = "./materiality-f1qwnvg1.md";
2415
+ var init_materiality2 = () => {};
2416
+
2171
2417
  // prompts/scout.md
2172
2418
  var scout_default = "./scout-yvp153q7.md";
2173
2419
  var init_scout = () => {};
@@ -2177,7 +2423,7 @@ var summarizer_default = "./summarizer-zca44nxa.md";
2177
2423
  var init_summarizer = () => {};
2178
2424
 
2179
2425
  // skills/crysk/SKILL.md
2180
- var SKILL_default = "./SKILL-9at22381.md";
2426
+ var SKILL_default = "./SKILL-816621e5.md";
2181
2427
  var init_SKILL = () => {};
2182
2428
 
2183
2429
  // skills/crysk-ci-setup/assets/admission-config.example.json
@@ -2189,7 +2435,7 @@ var workflow_default = "./workflow-w1g9szna.yml";
2189
2435
  var init_workflow = () => {};
2190
2436
 
2191
2437
  // skills/crysk-ci-setup/references/ci-admission.md
2192
- var ci_admission_default = "./ci-admission-camfbx2b.md";
2438
+ var ci_admission_default = "./ci-admission-f19qh39t.md";
2193
2439
  var init_ci_admission = () => {};
2194
2440
 
2195
2441
  // skills/crysk-ci-setup/references/opencode-ci.md
@@ -2197,7 +2443,7 @@ var opencode_ci_default = "./opencode-ci-7b0be64p.md";
2197
2443
  var init_opencode_ci = () => {};
2198
2444
 
2199
2445
  // skills/crysk-ci-setup/SKILL.md
2200
- var SKILL_default2 = "./SKILL-ex2hxxh3.md";
2446
+ var SKILL_default2 = "./SKILL-6j27707y.md";
2201
2447
  var init_SKILL2 = () => {};
2202
2448
 
2203
2449
  // skills/crysk-loop/adjudicator.md
@@ -2205,7 +2451,7 @@ var adjudicator_default = "./adjudicator-dtg2axnh.md";
2205
2451
  var init_adjudicator = () => {};
2206
2452
 
2207
2453
  // skills/crysk-loop/SKILL.md
2208
- var SKILL_default3 = "./SKILL-7e3725zn.md";
2454
+ var SKILL_default3 = "./SKILL-yz6wk92g.md";
2209
2455
  var init_SKILL3 = () => {};
2210
2456
 
2211
2457
  // skills/crysk-pr/SKILL.md
@@ -2213,7 +2459,7 @@ var SKILL_default4 = "./SKILL-7q35wcaz.md";
2213
2459
  var init_SKILL4 = () => {};
2214
2460
 
2215
2461
  // src/asset-manifest.ts
2216
- var BUNDLED_AGENT_FILES, CONSOLIDATE_PROMPT_PATH, SCOUT_PROMPT_PATH, SUMMARIZER_PROMPT_PATH, TRIAGE_SKILL_FILES, CI_SETUP_SKILL_FILES, PR_SKILL_FILES, GENERAL_SKILL_FILES;
2462
+ 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;
2217
2463
  var init_asset_manifest = __esm(() => {
2218
2464
  init_consolidate();
2219
2465
  init_deep_review_lifecycle();
@@ -2222,6 +2468,7 @@ var init_asset_manifest = __esm(() => {
2222
2468
  init_deep_review_reliability();
2223
2469
  init_deep_review_resilience();
2224
2470
  init_review_refuter();
2471
+ init_materiality2();
2225
2472
  init_scout();
2226
2473
  init_summarizer();
2227
2474
  init_SKILL();
@@ -2242,6 +2489,7 @@ var init_asset_manifest = __esm(() => {
2242
2489
  "review-refuter.md": review_refuter_default
2243
2490
  };
2244
2491
  CONSOLIDATE_PROMPT_PATH = consolidate_default;
2492
+ MATERIALITY_PROMPT_PATH = materiality_default;
2245
2493
  SCOUT_PROMPT_PATH = scout_default;
2246
2494
  SUMMARIZER_PROMPT_PATH = summarizer_default;
2247
2495
  TRIAGE_SKILL_FILES = {
@@ -2289,7 +2537,7 @@ function resolveVersion() {
2289
2537
  }
2290
2538
  }
2291
2539
  } catch {}
2292
- return "0.3.0";
2540
+ return "0.3.2";
2293
2541
  }
2294
2542
  function resolveEngineAssets() {
2295
2543
  const mode = detectAssetMode();
@@ -2306,6 +2554,7 @@ function resolveEngineAssets() {
2306
2554
  bundledAgentFiles: BUNDLED_AGENT_FILES,
2307
2555
  defaultAgentsDir,
2308
2556
  consolidatePromptPath: CONSOLIDATE_PROMPT_PATH,
2557
+ materialityPromptPath: MATERIALITY_PROMPT_PATH,
2309
2558
  scoutPromptPath: SCOUT_PROMPT_PATH,
2310
2559
  summarizerPromptPath: SUMMARIZER_PROMPT_PATH,
2311
2560
  triageSkillFiles: TRIAGE_SKILL_FILES,
@@ -2503,10 +2752,10 @@ function compileIgnoreRules(rules) {
2503
2752
  globs: rule.globs.map((pattern) => new Bun.Glob(pattern))
2504
2753
  }));
2505
2754
  return {
2506
- match(path5) {
2755
+ match(path) {
2507
2756
  let winner;
2508
2757
  for (const { rule, globs } of compiled) {
2509
- if (globs.some((glob) => glob.match(path5))) {
2758
+ if (globs.some((glob) => glob.match(path))) {
2510
2759
  winner = rule.negated ? undefined : rule;
2511
2760
  }
2512
2761
  }
@@ -2894,8 +3143,8 @@ function row(label, value, opts) {
2894
3143
  const chunks = value.length <= available ? [value] : wrapText(value, available);
2895
3144
  return chunks.map((chunk, i) => i === 0 ? head + chunk : pad + chunk);
2896
3145
  }
2897
- function markerRowLines(marker, value, paint2, styles, width) {
2898
- return row(marker, value, { ...MARKER_ROW, styles: false, width }).map((line) => paint2(line, styles));
3146
+ function markerRowLines(marker, value, paint, styles, width) {
3147
+ return row(marker, value, { ...MARKER_ROW, styles: false, width }).map((line) => paint(line, styles));
2899
3148
  }
2900
3149
  function labelColumnWidth(labels) {
2901
3150
  return Math.max(0, ...labels.map((label) => label.length)) + LABEL_GAP;
@@ -3091,11 +3340,11 @@ function parseNameOnly(stdout) {
3091
3340
  const seen = new Set;
3092
3341
  for (const line of stdout.split(`
3093
3342
  `)) {
3094
- const path8 = line.trim();
3095
- if (path8.length === 0 || seen.has(path8))
3343
+ const path = line.trim();
3344
+ if (path.length === 0 || seen.has(path))
3096
3345
  continue;
3097
- seen.add(path8);
3098
- out.push(path8);
3346
+ seen.add(path);
3347
+ out.push(path);
3099
3348
  }
3100
3349
  out.sort();
3101
3350
  return out;
@@ -3958,30 +4207,30 @@ function outcomeNotificationText(outcome) {
3958
4207
  return `PR #${outcome.pr}: ${outcome.counts.blocking} blocking, ` + `${outcome.counts.advisory} advisory`;
3959
4208
  }
3960
4209
  function renderWatchStatus(facts) {
3961
- const row2 = (label, value) => ` ${label.padEnd(13)}${value}`;
4210
+ const row = (label, value) => ` ${label.padEnd(13)}${value}`;
3962
4211
  const lines = ["crysk watch \u2014 status", ""];
3963
4212
  if (facts.configError !== null) {
3964
- lines.push(row2("config", `INVALID \u2014 ${facts.watchConfigPath}: ${facts.configError}`));
4213
+ lines.push(row("config", `INVALID \u2014 ${facts.watchConfigPath}: ${facts.configError}`));
3965
4214
  } else if (facts.config === null) {
3966
- lines.push(row2("config", `none (${facts.watchConfigPath}) \u2014 run "crysk watch add" inside a ` + "repo to opt it in"));
4215
+ lines.push(row("config", `none (${facts.watchConfigPath}) \u2014 run "crysk watch add" inside a ` + "repo to opt it in"));
3967
4216
  } else {
3968
- lines.push(row2("config", facts.watchConfigPath));
4217
+ lines.push(row("config", facts.watchConfigPath));
3969
4218
  if (facts.config.repos.length === 0) {
3970
- lines.push(row2("", 'no repos watched \u2014 "crysk watch add" opts one in'));
4219
+ lines.push(row("", 'no repos watched \u2014 "crysk watch add" opts one in'));
3971
4220
  }
3972
4221
  for (const repo of facts.config.repos) {
3973
- lines.push(row2("", `${repo.path} post=${repo.post} on_push=${repo.onPush} ` + `max_lines=${repo.maxChangedLines} max_files=${repo.maxChangedFiles}`));
4222
+ lines.push(row("", `${repo.path} post=${repo.post} on_push=${repo.onPush} ` + `max_lines=${repo.maxChangedLines} max_files=${repo.maxChangedFiles}`));
3974
4223
  }
3975
- lines.push(row2("today", `${facts.launchedToday} of ${facts.config.dailyCap} launches used`));
3976
- lines.push(row2("window", facts.config.window === null ? "always" : `${facts.config.window.start}-${facts.config.window.end}`));
4224
+ lines.push(row("today", `${facts.launchedToday} of ${facts.config.dailyCap} launches used`));
4225
+ lines.push(row("window", facts.config.window === null ? "always" : `${facts.config.window.start}-${facts.config.window.end}`));
3977
4226
  }
3978
4227
  if (facts.config === null || facts.configError !== null) {
3979
- lines.push(row2("today", `${facts.launchedToday} launched`));
4228
+ lines.push(row("today", `${facts.launchedToday} launched`));
3980
4229
  }
3981
- lines.push(row2("launchd", facts.installed ? facts.intervalSeconds === null ? `installed (${facts.plistPath}, interval unreadable)` : `installed \u2014 one tick every ${formatIntervalSeconds(facts.intervalSeconds)}` : 'not installed \u2014 run "crysk watch install" to start ticking'));
3982
- lines.push(row2("lock", facts.lockPid === null ? "free" : `held by pid ${facts.lockPid} (a tick is running)`));
3983
- lines.push(row2("last launch", facts.lastLaunched ?? "none recorded"));
3984
- lines.push(row2("last outcome", facts.lastOutcome ?? "none recorded"));
4230
+ lines.push(row("launchd", facts.installed ? facts.intervalSeconds === null ? `installed (${facts.plistPath}, interval unreadable)` : `installed \u2014 one tick every ${formatIntervalSeconds(facts.intervalSeconds)}` : 'not installed \u2014 run "crysk watch install" to start ticking'));
4231
+ lines.push(row("lock", facts.lockPid === null ? "free" : `held by pid ${facts.lockPid} (a tick is running)`));
4232
+ lines.push(row("last launch", facts.lastLaunched ?? "none recorded"));
4233
+ lines.push(row("last outcome", facts.lastOutcome ?? "none recorded"));
3985
4234
  return lines;
3986
4235
  }
3987
4236
  function formatIntervalSeconds(seconds) {
@@ -4004,18 +4253,6 @@ var init_preflight = __esm(() => {
4004
4253
  });
4005
4254
 
4006
4255
  // src/home.ts
4007
- var exports_home = {};
4008
- __export(exports_home, {
4009
- writeRepoRegistry: () => writeRepoRegistry,
4010
- worktreeInFlight: () => worktreeInFlight,
4011
- tryOriginRepoId: () => tryOriginRepoId,
4012
- stampWorktree: () => stampWorktree,
4013
- resolveRepoHome: () => resolveRepoHome,
4014
- releasePidLock: () => releasePidLock,
4015
- ownerPresent: () => ownerPresent,
4016
- gitOriginUrl: () => gitOriginUrl,
4017
- acquirePidLock: () => acquirePidLock
4018
- });
4019
4256
  import { existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
4020
4257
  import { mkdir, open, rename, rm } from "fs/promises";
4021
4258
  import path10 from "path";
@@ -4920,11 +5157,11 @@ async function createRunDir(options, repoRoot, headSha) {
4920
5157
  const explicit = path11.resolve(options.out);
4921
5158
  assertOutsideRepo(explicit, repoRoot);
4922
5159
  await mkdir2(explicit, { recursive: true });
4923
- const { tryOriginRepoId: tryOriginRepoId2 } = await Promise.resolve().then(() => (init_home(), exports_home));
4924
- return { runDir: explicit, repoId: await tryOriginRepoId2(repoRoot) };
5160
+ await Promise.resolve().then(() => init_home());
5161
+ return { runDir: explicit, repoId: await tryOriginRepoId(repoRoot) };
4925
5162
  }
4926
- const { resolveRepoHome: resolveRepoHome2 } = await Promise.resolve().then(() => (init_home(), exports_home));
4927
- const repoHome = await resolveRepoHome2({
5163
+ await Promise.resolve().then(() => init_home());
5164
+ const repoHome = await resolveRepoHome({
4928
5165
  home: os.homedir(),
4929
5166
  operatorRoot: repoRoot,
4930
5167
  persist: true
@@ -5118,7 +5355,9 @@ function parseConfigLayer(raw, file, admitted, parseRouting, isRepoFile) {
5118
5355
  const maxChangedLines = parseNonNegativeInteger(config.max_changed_lines, "max_changed_lines", file);
5119
5356
  const maxChangedFiles = parseNonNegativeInteger(config.max_changed_files, "max_changed_files", file);
5120
5357
  const scout = parseOptionalBoolean(config.scout, "scout", file);
5358
+ const materialityGate = parseOptionalBoolean(config.materiality_gate, "materiality_gate", file);
5121
5359
  const post = parseOptionalBoolean(config.post, "post", file);
5360
+ const postMinSeverity = parsePostMinSeverity(config.post_min_severity, file);
5122
5361
  const ciReviewPolicy = parseCiReviewPolicyMode(config.ci_review_policy, file);
5123
5362
  const ciMaxAttempts = parseCiAdmissionInteger(config.ci_max_attempts, "ci_max_attempts", file, 1);
5124
5363
  const ciMaxReviews = parseCiAdmissionInteger(config.ci_max_reviews, "ci_max_reviews", file, 1);
@@ -5142,7 +5381,9 @@ function parseConfigLayer(raw, file, admitted, parseRouting, isRepoFile) {
5142
5381
  ...maxChangedLines === undefined ? {} : { max_changed_lines: maxChangedLines },
5143
5382
  ...maxChangedFiles === undefined ? {} : { max_changed_files: maxChangedFiles },
5144
5383
  ...scout === undefined ? {} : { scout },
5384
+ ...materialityGate === undefined ? {} : { materiality_gate: materialityGate },
5145
5385
  ...post === undefined ? {} : { post },
5386
+ ...postMinSeverity === undefined ? {} : { post_min_severity: postMinSeverity },
5146
5387
  ...ciReviewPolicy === undefined ? {} : { ci_review_policy: ciReviewPolicy },
5147
5388
  ...ciMaxAttempts === undefined ? {} : { ci_max_attempts: ciMaxAttempts },
5148
5389
  ...ciMaxReviews === undefined ? {} : { ci_max_reviews: ciMaxReviews },
@@ -5153,62 +5394,62 @@ function parseConfigLayer(raw, file, admitted, parseRouting, isRepoFile) {
5153
5394
  ...ciAdmissionObserveOnly === undefined ? {} : { ci_admission_observe_only: ciAdmissionObserveOnly }
5154
5395
  };
5155
5396
  }
5156
- function checkNoCredentials(obj, path12, file) {
5397
+ function checkNoCredentials(obj, path, file) {
5157
5398
  for (const key of Object.keys(obj)) {
5158
5399
  const lower = key.toLowerCase();
5159
5400
  if (CREDENTIAL_KEY_NAMES.has(lower) || lower.includes("secret") || lower.includes("password") || lower.includes("token") || lower.includes("apikey") || lower.includes("api_key")) {
5160
- throw new CliUsageError(`${file} ${path12}: credentials are not permitted in routing config`);
5401
+ throw new CliUsageError(`${file} ${path}: credentials are not permitted in routing config`);
5161
5402
  }
5162
5403
  const val = obj[key];
5163
5404
  if (typeof val === "string") {
5164
5405
  const redacted = redactDiagnostic(val);
5165
5406
  if (redacted !== val) {
5166
- throw new CliUsageError(`${file} ${path12}: credentials are not permitted in routing config`);
5407
+ throw new CliUsageError(`${file} ${path}: credentials are not permitted in routing config`);
5167
5408
  }
5168
5409
  }
5169
5410
  }
5170
5411
  }
5171
- function parseRouteMapping(m, path12, file) {
5412
+ function parseRouteMapping(m, path, file) {
5172
5413
  if (typeof m !== "object" || m === null || Array.isArray(m)) {
5173
- throw new CliUsageError(`${file} ${path12} must be an object`);
5414
+ throw new CliUsageError(`${file} ${path} must be an object`);
5174
5415
  }
5175
5416
  const mapping = m;
5176
- checkNoCredentials(mapping, path12, file);
5417
+ checkNoCredentials(mapping, path, file);
5177
5418
  for (const key of Object.keys(mapping)) {
5178
5419
  if (!KNOWN_ROUTE_MAPPING_KEYS.has(key)) {
5179
- throw new CliUsageError(`${file} ${path12} unknown key: ${redactDiagnostic(key)}`);
5420
+ throw new CliUsageError(`${file} ${path} unknown key: ${redactDiagnostic(key)}`);
5180
5421
  }
5181
5422
  }
5182
5423
  if (mapping.logical !== undefined) {
5183
5424
  if (typeof mapping.logical !== "string" || mapping.logical.trim().length === 0) {
5184
- throw new CliUsageError(`${file} ${path12}.logical must be a non-empty string`);
5425
+ throw new CliUsageError(`${file} ${path}.logical must be a non-empty string`);
5185
5426
  }
5186
5427
  }
5187
5428
  if (typeof mapping.backend !== "string" || mapping.backend !== "claude-code" && mapping.backend !== "opencode") {
5188
- throw new CliUsageError(`${file} ${path12}.backend must be claude-code|opencode`);
5429
+ throw new CliUsageError(`${file} ${path}.backend must be claude-code|opencode`);
5189
5430
  }
5190
5431
  if (typeof mapping.provider !== "string" || mapping.provider.trim().length === 0) {
5191
- throw new CliUsageError(`${file} ${path12}.provider must be a non-empty string`);
5432
+ throw new CliUsageError(`${file} ${path}.provider must be a non-empty string`);
5192
5433
  }
5193
5434
  if (mapping.gateway !== undefined) {
5194
5435
  if (typeof mapping.gateway !== "string" || mapping.gateway !== "configured" && mapping.gateway !== "direct" && mapping.gateway !== "openrouter") {
5195
- throw new CliUsageError(`${file} ${path12}.gateway must be configured|direct|openrouter`);
5436
+ throw new CliUsageError(`${file} ${path}.gateway must be configured|direct|openrouter`);
5196
5437
  }
5197
5438
  }
5198
5439
  if (mapping.modelFamily !== undefined && typeof mapping.modelFamily !== "string") {
5199
- throw new CliUsageError(`${file} ${path12}.modelFamily must be a string`);
5440
+ throw new CliUsageError(`${file} ${path}.modelFamily must be a string`);
5200
5441
  }
5201
5442
  if (mapping.modelSnapshot !== undefined && typeof mapping.modelSnapshot !== "string") {
5202
- throw new CliUsageError(`${file} ${path12}.modelSnapshot must be a string`);
5443
+ throw new CliUsageError(`${file} ${path}.modelSnapshot must be a string`);
5203
5444
  }
5204
5445
  if (mapping.modelVariant !== undefined && typeof mapping.modelVariant !== "string") {
5205
- throw new CliUsageError(`${file} ${path12}.modelVariant must be a string`);
5446
+ throw new CliUsageError(`${file} ${path}.modelVariant must be a string`);
5206
5447
  }
5207
5448
  if (mapping.disabled !== undefined && typeof mapping.disabled !== "boolean") {
5208
- throw new CliUsageError(`${file} ${path12}.disabled must be a boolean`);
5449
+ throw new CliUsageError(`${file} ${path}.disabled must be a boolean`);
5209
5450
  }
5210
5451
  if (mapping.allowSpend !== undefined && typeof mapping.allowSpend !== "boolean") {
5211
- throw new CliUsageError(`${file} ${path12}.allowSpend must be a boolean`);
5452
+ throw new CliUsageError(`${file} ${path}.allowSpend must be a boolean`);
5212
5453
  }
5213
5454
  return {
5214
5455
  ...mapping.logical ? { logical: mapping.logical } : {},
@@ -5316,6 +5557,14 @@ function parseCiAdmissionInteger(value, key, file, min) {
5316
5557
  }
5317
5558
  return parsed;
5318
5559
  }
5560
+ function parsePostMinSeverity(value, file) {
5561
+ if (value === undefined)
5562
+ return;
5563
+ if (typeof value !== "string" || !POST_MIN_SEVERITIES.includes(value)) {
5564
+ throw new CliUsageError(`${file} post_min_severity must be one of: ${POST_MIN_SEVERITIES.join(", ")}`);
5565
+ }
5566
+ return value;
5567
+ }
5319
5568
  function parseCiReviewPolicyMode(value, file) {
5320
5569
  if (value === undefined)
5321
5570
  return;
@@ -5346,6 +5595,9 @@ function resolveSharedPrefix(options) {
5346
5595
  function resolveScout(options, config) {
5347
5596
  return options.scout ?? config.scout ?? false;
5348
5597
  }
5598
+ function resolveMaterialityGate(config) {
5599
+ return config.materiality_gate ?? false;
5600
+ }
5349
5601
  function resolvePost(options, config) {
5350
5602
  return options.post ?? config.post ?? false;
5351
5603
  }
@@ -5392,7 +5644,9 @@ function mergeConfig(global, repo) {
5392
5644
  const maxLines = foldKey(layers, CONFIG_DIRECTION.max_changed_lines, (layer) => layer.max_changed_lines, narrowSizeLimit);
5393
5645
  const maxFiles = foldKey(layers, CONFIG_DIRECTION.max_changed_files, (layer) => layer.max_changed_files, narrowSizeLimit);
5394
5646
  const scout = foldKey(layers, CONFIG_DIRECTION.scout, (layer) => layer.scout, (a, b) => a && b);
5647
+ const materialityGate = foldKey(layers, CONFIG_DIRECTION.materiality_gate, (layer) => layer.materiality_gate, (a, b) => a && b);
5395
5648
  const post = foldKey(layers, CONFIG_DIRECTION.post, (layer) => layer.post, (a, b) => a && b);
5649
+ const postMinSeverity = foldKey(layers, CONFIG_DIRECTION.post_min_severity, (layer) => layer.post_min_severity);
5396
5650
  const routing = foldKey(layers, CONFIG_DIRECTION.routing, (layer) => layer.routing);
5397
5651
  const ciReviewPolicy = foldKey(layers, CONFIG_DIRECTION.ci_review_policy, (layer) => layer.ci_review_policy);
5398
5652
  const ciMaxAttempts = foldKey(layers, CONFIG_DIRECTION.ci_max_attempts, (layer) => layer.ci_max_attempts);
@@ -5418,7 +5672,9 @@ function mergeConfig(global, repo) {
5418
5672
  ...maxLines.value === undefined ? {} : { max_changed_lines: maxLines.value },
5419
5673
  ...maxFiles.value === undefined ? {} : { max_changed_files: maxFiles.value },
5420
5674
  ...scout.value === undefined ? {} : { scout: scout.value },
5675
+ ...materialityGate.value === undefined ? {} : { materiality_gate: materialityGate.value },
5421
5676
  ...post.value === undefined ? {} : { post: post.value },
5677
+ ...postMinSeverity.value === undefined ? {} : { post_min_severity: postMinSeverity.value },
5422
5678
  ...ciReviewPolicy.value === undefined ? {} : { ci_review_policy: ciReviewPolicy.value },
5423
5679
  ...ciMaxAttempts.value === undefined ? {} : { ci_max_attempts: ciMaxAttempts.value },
5424
5680
  ...ciMaxReviews.value === undefined ? {} : { ci_max_reviews: ciMaxReviews.value },
@@ -5440,7 +5696,9 @@ function mergeConfig(global, repo) {
5440
5696
  max_changed_lines: maxLines.source,
5441
5697
  max_changed_files: maxFiles.source,
5442
5698
  scout: scout.source,
5699
+ materiality_gate: materialityGate.source,
5443
5700
  post: post.source,
5701
+ post_min_severity: postMinSeverity.source,
5444
5702
  ci_review_policy: ciReviewPolicy.source,
5445
5703
  ci_max_attempts: ciMaxAttempts.source,
5446
5704
  ci_max_reviews: ciMaxReviews.source,
@@ -5576,6 +5834,7 @@ function gotchasErrorMessage(gotchasPath, reason) {
5576
5834
  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, SETUP_GOTCHAS_FALLBACK, RETIRED_SCAFFOLD_LINES, SCAFFOLD_BODY_LINES;
5577
5835
  var init_preflight2 = __esm(() => {
5578
5836
  init_review_policy();
5837
+ init_post_floor();
5579
5838
  init_spec();
5580
5839
  init_triage();
5581
5840
  init_assets();
@@ -5912,7 +6171,9 @@ about how well a large diff reviews.`;
5912
6171
  max_changed_lines: "capped",
5913
6172
  max_changed_files: "capped",
5914
6173
  scout: "capped",
6174
+ materiality_gate: "capped",
5915
6175
  post: "capped",
6176
+ post_min_severity: "person",
5916
6177
  ci_review_policy: "repo",
5917
6178
  ci_max_attempts: "repo",
5918
6179
  ci_max_reviews: "repo",
@@ -6178,9 +6439,9 @@ function claimFingerprint(claim) {
6178
6439
  return new Bun.CryptoHasher("sha256").update(claim.trim()).digest("hex").slice(0, 12);
6179
6440
  }
6180
6441
  function findingMarker(fields) {
6181
- const path13 = encodeURIComponent(fields.path);
6442
+ const path = encodeURIComponent(fields.path);
6182
6443
  const c = claimFingerprint(fields.claim);
6183
- return `${PR_FINDING_MARKER_PREFIX}path=${path13} line=${fields.line} ` + `head=${fields.headSha} c=${c} -->`;
6444
+ return `${PR_FINDING_MARKER_PREFIX}path=${path} line=${fields.line} ` + `head=${fields.headSha} c=${c} -->`;
6184
6445
  }
6185
6446
  function parseFindingMarker(body) {
6186
6447
  const prefix = matchMarkerPrefix(body, PR_FINDING_MARKER_PREFIX);
@@ -6210,13 +6471,13 @@ function parseFindingMarker(body) {
6210
6471
  const line = Number.parseInt(rawLine, 10);
6211
6472
  if (!Number.isInteger(line))
6212
6473
  return null;
6213
- let path13;
6474
+ let path;
6214
6475
  try {
6215
- path13 = decodeURIComponent(rawPath);
6476
+ path = decodeURIComponent(rawPath);
6216
6477
  } catch {
6217
6478
  return null;
6218
6479
  }
6219
- return { path: path13, line, headSha, c };
6480
+ return { path, line, headSha, c };
6220
6481
  }
6221
6482
  function inFlightContextsFor(statusContext) {
6222
6483
  return statusContext === COMMIT_STATUS_CONTEXT ? [COMMIT_STATUS_CONTEXT] : RUN_STATUS_CONTEXTS;
@@ -6396,12 +6657,6 @@ var init_errors2 = __esm(() => {
6396
6657
  });
6397
6658
 
6398
6659
  // src/diversity/admission.ts
6399
- var exports_admission = {};
6400
- __export(exports_admission, {
6401
- requireInternalFindingsCapability: () => requireInternalFindingsCapability,
6402
- checkInternalFindingsCapability: () => checkInternalFindingsCapability,
6403
- assertDiversityCapabilityOrThrow: () => assertDiversityCapabilityOrThrow
6404
- });
6405
6660
  function checkInternalFindingsCapability() {
6406
6661
  try {
6407
6662
  for (const conformanceCase of FINDINGS_CONFORMANCE_CASES) {
@@ -6513,6 +6768,8 @@ REMINDER: your final message must be exactly one JSON object ` + "matching the m
6513
6768
  init_routing();
6514
6769
 
6515
6770
  // src/review/dedupe.ts
6771
+ init_findings();
6772
+ init_materiality_gate();
6516
6773
  var SEVERITY_RANK = {
6517
6774
  BLOCKER: 0,
6518
6775
  CRITICAL: 1,
@@ -6675,15 +6932,42 @@ function mergeAndDedupe(drafts) {
6675
6932
  const survivorsRaw = [];
6676
6933
  const emittedWinners = new Set;
6677
6934
  const originalOf = new Map;
6935
+ const mergedInto = new Map;
6936
+ for (const draft of drafts) {
6937
+ let root = draft;
6938
+ for (let next = winnerOf.get(root);next !== undefined && next !== root; ) {
6939
+ root = next;
6940
+ next = winnerOf.get(root);
6941
+ }
6942
+ if (root === draft)
6943
+ continue;
6944
+ const members = mergedInto.get(root);
6945
+ if (members)
6946
+ members.push(draft);
6947
+ else
6948
+ mergedInto.set(root, [draft]);
6949
+ }
6950
+ const blamingDisposition = (winner) => {
6951
+ if (!isNotCausedByPr(winner.causal_disposition))
6952
+ return;
6953
+ const members = mergedInto.get(winner) ?? [];
6954
+ const blamer = members.find((member) => !isNotCausedByPr(member.causal_disposition));
6955
+ if (blamer !== undefined)
6956
+ return blamer.causal_disposition;
6957
+ const lostSafety = !isSafetyProtected(winner) && members.some((member) => isSafetyProtected(member));
6958
+ return lostSafety ? "unknown" : undefined;
6959
+ };
6678
6960
  for (const draft of pass1) {
6679
6961
  const winner = clusterWinnerOf.get(draft);
6680
6962
  if (emittedWinners.has(winner))
6681
6963
  continue;
6682
6964
  emittedWinners.add(winner);
6683
6965
  const losers = foldedInto.get(winner);
6966
+ const blame = blamingDisposition(winner);
6684
6967
  if (losers.length === 0) {
6685
- survivorsRaw.push(winner);
6686
- originalOf.set(winner, winner);
6968
+ const survivor = blame === undefined ? winner : { ...winner, causal_disposition: blame };
6969
+ survivorsRaw.push(survivor);
6970
+ originalOf.set(survivor, winner);
6687
6971
  continue;
6688
6972
  }
6689
6973
  const foldedRefs = [...winner.proof_refs];
@@ -6693,7 +6977,11 @@ function mergeAndDedupe(drafts) {
6693
6977
  foldedRefs.push(ref);
6694
6978
  }
6695
6979
  }
6696
- const folded = { ...winner, proof_refs: foldedRefs };
6980
+ const folded = {
6981
+ ...winner,
6982
+ proof_refs: foldedRefs,
6983
+ ...blame === undefined ? {} : { causal_disposition: blame }
6984
+ };
6697
6985
  survivorsRaw.push(folded);
6698
6986
  originalOf.set(folded, winner);
6699
6987
  }
@@ -6827,18 +7115,18 @@ function mustResolveProofRefs(refs, options, label) {
6827
7115
  if (resolve === undefined)
6828
7116
  return;
6829
7117
  const unresolved = unresolvedProofRefs(refs, resolve);
6830
- must2(unresolved.length === 0, `${label} cite paths absent from the reviewed tree: ${unresolved.join(", ")}`);
7118
+ must3(unresolved.length === 0, `${label} cite paths absent from the reviewed tree: ${unresolved.join(", ")}`);
6831
7119
  }
6832
- function must2(condition, message) {
7120
+ function must3(condition, message) {
6833
7121
  if (!condition)
6834
7122
  throw new DraftValidationError(message);
6835
7123
  }
6836
- function normalizeOptionalString(f, key, label) {
7124
+ function normalizeOptionalString2(f, key, label) {
6837
7125
  if (f[key] === null) {
6838
7126
  delete f[key];
6839
7127
  return;
6840
7128
  }
6841
- must2(f[key] === undefined || typeof f[key] === "string", `${label} must be a string when present`);
7129
+ must3(f[key] === undefined || typeof f[key] === "string", `${label} must be a string when present`);
6842
7130
  }
6843
7131
  function extractJsonObject(finalText) {
6844
7132
  const direct = tryParse(finalText.trim());
@@ -6893,13 +7181,13 @@ function tryParse(text) {
6893
7181
  return;
6894
7182
  }
6895
7183
  }
6896
- var SEVERITIES = ["BLOCKER", "CRITICAL", "WARNING", "SUGGESTION"];
6897
- var EVIDENCE_CLASSES = [
7184
+ var SEVERITIES2 = ["BLOCKER", "CRITICAL", "WARNING", "SUGGESTION"];
7185
+ var EVIDENCE_CLASSES2 = [
6898
7186
  "deterministic",
6899
7187
  "inferential",
6900
7188
  "insufficient"
6901
7189
  ];
6902
- var CAUSAL_DISPOSITIONS = [
7190
+ var CAUSAL_DISPOSITIONS2 = [
6903
7191
  "introduced",
6904
7192
  "behavior-activated",
6905
7193
  "worsened",
@@ -6914,69 +7202,69 @@ var REFUTER_OUTCOMES = [
6914
7202
  "downgraded-latent"
6915
7203
  ];
6916
7204
  function validateSummary(candidate) {
6917
- must2(typeof candidate === "object" && candidate !== null, "summary must be an object");
7205
+ must3(typeof candidate === "object" && candidate !== null, "summary must be an object");
6918
7206
  const summary = candidate;
6919
- must2(typeof summary.prose === "string" && summary.prose.length > 0, "summary.prose required");
6920
- must2(typeof summary.prose === "string" && summary.prose.length <= 1200, "summary.prose must be at most 1200 characters");
6921
- must2(typeof summary.score === "number" && Number.isInteger(summary.score) && summary.score >= 1 && summary.score <= 5, "summary.score must be an integer 1-5");
6922
- must2(typeof summary.score_reason === "string" && summary.score_reason.length > 0, "summary.score_reason required");
6923
- must2(typeof summary.score_reason === "string" && summary.score_reason.length <= 400, "summary.score_reason must be at most 400 characters");
7207
+ must3(typeof summary.prose === "string" && summary.prose.length > 0, "summary.prose required");
7208
+ must3(typeof summary.prose === "string" && summary.prose.length <= 1200, "summary.prose must be at most 1200 characters");
7209
+ must3(typeof summary.score === "number" && Number.isInteger(summary.score) && summary.score >= 1 && summary.score <= 5, "summary.score must be an integer 1-5");
7210
+ must3(typeof summary.score_reason === "string" && summary.score_reason.length > 0, "summary.score_reason required");
7211
+ must3(typeof summary.score_reason === "string" && summary.score_reason.length <= 400, "summary.score_reason must be at most 400 characters");
6924
7212
  const prose = summary.prose;
6925
7213
  const scoreReason = summary.score_reason;
6926
- must2(!prose.includes("<!--") && !prose.includes("-->") && !scoreReason.includes("<!--") && !scoreReason.includes("-->"), "summary strings must not contain HTML comment markers");
7214
+ must3(!prose.includes("<!--") && !prose.includes("-->") && !scoreReason.includes("<!--") && !scoreReason.includes("-->"), "summary strings must not contain HTML comment markers");
6927
7215
  return summary;
6928
7216
  }
6929
7217
  function validateDraftFinding(candidate, index, options) {
6930
- must2(typeof candidate === "object" && candidate !== null, `draft findings[${index}] must be an object`);
7218
+ must3(typeof candidate === "object" && candidate !== null, `draft findings[${index}] must be an object`);
6931
7219
  const f = candidate;
6932
- must2(typeof f.id === "string" && f.id.length > 0, `draft findings[${index}].id required`);
6933
- must2(typeof f.category === "number" && f.category >= 1 && f.category <= 15, `draft findings[${index}].category must be 1-15`);
6934
- must2(typeof f.path === "string" && f.path.length > 0, `draft findings[${index}].path required`);
6935
- must2(typeof f.line === "number", `draft findings[${index}].line must be a number`);
6936
- must2(SEVERITIES.includes(f.severity), `draft findings[${index}].severity invalid`);
6937
- must2(EVIDENCE_CLASSES.includes(f.evidence_class), `draft findings[${index}].evidence_class invalid`);
6938
- must2(CAUSAL_DISPOSITIONS.includes(f.causal_disposition), `draft findings[${index}].causal_disposition invalid`);
6939
- must2(typeof f.claim === "string" && f.claim.length > 0, `draft findings[${index}].claim required`);
6940
- must2(Array.isArray(f.proof_refs), `draft findings[${index}].proof_refs must be an array`);
6941
- must2(typeof f.hunter === "string" && isSafeSlug(f.hunter), `draft findings[${index}].hunter invalid`);
6942
- must2(typeof f.hops_used === "number", `draft findings[${index}].hops_used must be a number`);
6943
- must2(Array.isArray(f.hop_trail), `draft findings[${index}].hop_trail must be an array`);
6944
- must2(typeof f.dedupe_key === "string" && f.dedupe_key.length > 0, `draft findings[${index}].dedupe_key required`);
6945
- must2(f.proof_refs.every((ref) => typeof ref === "string"), `draft findings[${index}].proof_refs must contain only strings`);
7220
+ must3(typeof f.id === "string" && f.id.length > 0, `draft findings[${index}].id required`);
7221
+ must3(typeof f.category === "number" && f.category >= 1 && f.category <= 15, `draft findings[${index}].category must be 1-15`);
7222
+ must3(typeof f.path === "string" && f.path.length > 0, `draft findings[${index}].path required`);
7223
+ must3(typeof f.line === "number", `draft findings[${index}].line must be a number`);
7224
+ must3(SEVERITIES2.includes(f.severity), `draft findings[${index}].severity invalid`);
7225
+ must3(EVIDENCE_CLASSES2.includes(f.evidence_class), `draft findings[${index}].evidence_class invalid`);
7226
+ must3(CAUSAL_DISPOSITIONS2.includes(f.causal_disposition), `draft findings[${index}].causal_disposition invalid`);
7227
+ must3(typeof f.claim === "string" && f.claim.length > 0, `draft findings[${index}].claim required`);
7228
+ must3(Array.isArray(f.proof_refs), `draft findings[${index}].proof_refs must be an array`);
7229
+ must3(typeof f.hunter === "string" && isSafeSlug(f.hunter), `draft findings[${index}].hunter invalid`);
7230
+ must3(typeof f.hops_used === "number", `draft findings[${index}].hops_used must be a number`);
7231
+ must3(Array.isArray(f.hop_trail), `draft findings[${index}].hop_trail must be an array`);
7232
+ must3(typeof f.dedupe_key === "string" && f.dedupe_key.length > 0, `draft findings[${index}].dedupe_key required`);
7233
+ must3(f.proof_refs.every((ref) => typeof ref === "string"), `draft findings[${index}].proof_refs must contain only strings`);
6946
7234
  mustResolveProofRefs(f.proof_refs, options, `draft findings[${index}].proof_refs`);
6947
- normalizeOptionalString(f, "symbol", `draft findings[${index}].symbol`);
6948
- normalizeOptionalString(f, "root_cause_id", `draft findings[${index}].root_cause_id`);
7235
+ normalizeOptionalString2(f, "symbol", `draft findings[${index}].symbol`);
7236
+ normalizeOptionalString2(f, "root_cause_id", `draft findings[${index}].root_cause_id`);
6949
7237
  return f;
6950
7238
  }
6951
7239
  function validateHunterDraft(candidate, options) {
6952
- must2(typeof candidate === "object" && candidate !== null, "hunter draft must be an object");
7240
+ must3(typeof candidate === "object" && candidate !== null, "hunter draft must be an object");
6953
7241
  const d = candidate;
6954
- must2(Array.isArray(d.findings), "hunter draft .findings must be an array");
7242
+ must3(Array.isArray(d.findings), "hunter draft .findings must be an array");
6955
7243
  d.findings.forEach((f, i) => {
6956
7244
  validateDraftFinding(f, i, options);
6957
7245
  });
6958
7246
  return d;
6959
7247
  }
6960
7248
  function validateRefuterResult(candidate, submittedIds, options) {
6961
- must2(typeof candidate === "object" && candidate !== null, "refuter result must be an object");
7249
+ must3(typeof candidate === "object" && candidate !== null, "refuter result must be an object");
6962
7250
  const d = candidate;
6963
- must2(Array.isArray(d.results), "refuter result .results must be an array");
7251
+ must3(Array.isArray(d.results), "refuter result .results must be an array");
6964
7252
  const seen = new Set;
6965
7253
  for (const [i, entry] of d.results.entries()) {
6966
- must2(typeof entry === "object" && entry !== null, `refuter results[${i}] must be an object`);
7254
+ must3(typeof entry === "object" && entry !== null, `refuter results[${i}] must be an object`);
6967
7255
  const r = entry;
6968
- must2(typeof r.finding_id === "string" && r.finding_id.length > 0, `refuter results[${i}].finding_id required`);
6969
- must2(REFUTER_OUTCOMES.includes(r.outcome), `refuter results[${i}].outcome invalid`);
6970
- must2(Array.isArray(r.proof_refs), `refuter results[${i}].proof_refs must be an array`);
6971
- must2(r.proof_refs.every((ref) => typeof ref === "string"), `refuter results[${i}].proof_refs must contain only strings`);
7256
+ must3(typeof r.finding_id === "string" && r.finding_id.length > 0, `refuter results[${i}].finding_id required`);
7257
+ must3(REFUTER_OUTCOMES.includes(r.outcome), `refuter results[${i}].outcome invalid`);
7258
+ must3(Array.isArray(r.proof_refs), `refuter results[${i}].proof_refs must be an array`);
7259
+ must3(r.proof_refs.every((ref) => typeof ref === "string"), `refuter results[${i}].proof_refs must contain only strings`);
6972
7260
  mustResolveProofRefs(r.proof_refs, options, `refuter results[${i}].proof_refs`);
6973
7261
  const id = r.finding_id;
6974
- must2(!seen.has(id), `refuter results duplicate verdict for ${id}`);
6975
- must2(submittedIds.includes(id), `refuter results verdict for never-submitted ${id}`);
7262
+ must3(!seen.has(id), `refuter results duplicate verdict for ${id}`);
7263
+ must3(submittedIds.includes(id), `refuter results verdict for never-submitted ${id}`);
6976
7264
  seen.add(id);
6977
7265
  }
6978
7266
  for (const id of submittedIds) {
6979
- must2(seen.has(id), `refuter results missing verdict for ${id}`);
7267
+ must3(seen.has(id), `refuter results missing verdict for ${id}`);
6980
7268
  }
6981
7269
  return d;
6982
7270
  }
@@ -6986,46 +7274,15 @@ init_findings();
6986
7274
  init_findings_conformance();
6987
7275
 
6988
7276
  // src/review/pipeline.ts
7277
+ init_materiality();
6989
7278
  init_catalog();
6990
7279
  init_routing();
6991
7280
  import { existsSync as existsSync12 } from "fs";
6992
- import { chmod, mkdir as mkdir7 } from "fs/promises";
7281
+ import { chmod, mkdir as mkdir7, realpath as realpath4 } from "fs/promises";
6993
7282
  import path23 from "path";
6994
7283
 
6995
- // src/review/boundary.ts
6996
- var BOUNDARY_NONCE_CHARS = 8;
6997
- var MAX_NONCE_ATTEMPTS = 16;
6998
-
6999
- class BoundaryNonceError extends Error {
7000
- }
7001
- function generateBoundaryNonce() {
7002
- const bytes = new Uint8Array(BOUNDARY_NONCE_CHARS / 2);
7003
- crypto.getRandomValues(bytes);
7004
- return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
7005
- }
7006
- function blockForgesNonce(content, nonce) {
7007
- return content.includes(nonce);
7008
- }
7009
- function selectBoundaryNonce(blocks, generate = generateBoundaryNonce) {
7010
- for (let attempt = 0;attempt < MAX_NONCE_ATTEMPTS; attempt++) {
7011
- const nonce = generate();
7012
- if (!blocks.some((block) => blockForgesNonce(block, nonce)))
7013
- return nonce;
7014
- }
7015
- throw new BoundaryNonceError(`no boundary nonce survived ${MAX_NONCE_ATTEMPTS} attempts against ${blocks.length} blocks`);
7016
- }
7017
- function wrapBlock(tag, nonce, content) {
7018
- if (content.length === 0)
7019
- return "";
7020
- if (blockForgesNonce(content, nonce)) {
7021
- throw new BoundaryNonceError(`<${tag}> content carries the run's boundary nonce and could forge its own closing tag`);
7022
- }
7023
- return `<${tag} ${nonce}>
7024
- ${content}
7025
- </${tag} ${nonce}>`;
7026
- }
7027
-
7028
7284
  // src/rereview/adjudicate.ts
7285
+ init_boundary();
7029
7286
  var ADJUDICATION_INSTRUCTION = `Rule on the author's argument that this finding should be dismissed. Read the repository at the current head yourself. Answer with exactly one JSON object and nothing else: {"verdict": "upheld" | "rejected" | "inconclusive", "evidence": ["path:line", ...]}. "upheld" only if you verified in the repository, yourself, that the finding is not a defect.`;
7030
7287
  var ADJUDICATION_VERDICT_WORDS = new Set([
7031
7288
  "upheld",
@@ -7073,8 +7330,8 @@ function parseAdjudicationResult(finalText) {
7073
7330
  }
7074
7331
 
7075
7332
  // src/compare/compare.ts
7076
- function normalizePath(path2) {
7077
- return path2.trim().replace(/^\.\//, "");
7333
+ function normalizePath(path) {
7334
+ return path.trim().replace(/^\.\//, "");
7078
7335
  }
7079
7336
 
7080
7337
  // src/review/root-cause.ts
@@ -7135,8 +7392,8 @@ function parseProofRefLocs(ref) {
7135
7392
  if (anchor === null)
7136
7393
  return [];
7137
7394
  const colon = anchor.lastIndexOf(":");
7138
- const path2 = normalizePath(anchor.slice(0, colon));
7139
- if (path2.length === 0)
7395
+ const path = normalizePath(anchor.slice(0, colon));
7396
+ if (path.length === 0)
7140
7397
  return [];
7141
7398
  const specs = anchor.slice(colon + 1).split(",");
7142
7399
  const locs = [];
@@ -7149,7 +7406,7 @@ function parseProofRefLocs(ref) {
7149
7406
  if (!Number.isInteger(start) || !Number.isInteger(end) || end < start) {
7150
7407
  continue;
7151
7408
  }
7152
- locs.push({ path: path2, span: { start, end } });
7409
+ locs.push({ path, span: { start, end } });
7153
7410
  }
7154
7411
  return locs;
7155
7412
  }
@@ -7172,8 +7429,8 @@ function identityFromLocs(locs) {
7172
7429
  }
7173
7430
  function mapIdentityPaths(identity, rewrite) {
7174
7431
  const locs = [];
7175
- for (const [path2, spans] of identity) {
7176
- const next = rewrite(path2);
7432
+ for (const [path, spans] of identity) {
7433
+ const next = rewrite(path);
7177
7434
  for (const span of spans)
7178
7435
  locs.push({ path: next, span });
7179
7436
  }
@@ -7182,12 +7439,12 @@ function mapIdentityPaths(identity, rewrite) {
7182
7439
  function formatLocs(identity) {
7183
7440
  const out = [];
7184
7441
  const paths = [...identity.keys()].sort();
7185
- for (const path2 of paths) {
7186
- const spans = identity.get(path2);
7442
+ for (const path of paths) {
7443
+ const spans = identity.get(path);
7187
7444
  if (spans === undefined)
7188
7445
  continue;
7189
7446
  for (const span of spans) {
7190
- out.push(span.start === span.end ? `${path2}:${span.start}` : `${path2}:${span.start}-${span.end}`);
7447
+ out.push(span.start === span.end ? `${path}:${span.start}` : `${path}:${span.start}-${span.end}`);
7191
7448
  }
7192
7449
  }
7193
7450
  return out;
@@ -7200,9 +7457,9 @@ function identitiesMatch(a, b, window = IDENTITY_LINE_WINDOW) {
7200
7457
  if (!equal && !containment)
7201
7458
  return false;
7202
7459
  const shared = equal ? pa : intersect(pa, pb);
7203
- for (const path2 of shared) {
7204
- const as = a.get(path2);
7205
- const bs = b.get(path2);
7460
+ for (const path of shared) {
7461
+ const as = a.get(path);
7462
+ const bs = b.get(path);
7206
7463
  if (as === undefined || bs === undefined)
7207
7464
  return false;
7208
7465
  if (!spansOverlapOrNear(as, bs, window))
@@ -7279,7 +7536,7 @@ function isRecoveredTier(value) {
7279
7536
  }
7280
7537
  function classifyPrior(prior, ctx) {
7281
7538
  const original = identityFromLocs(prior.locs);
7282
- const rewritten = mapIdentityPaths(original, (path2) => ctx.renameMap.get(path2) ?? path2);
7539
+ const rewritten = mapIdentityPaths(original, (path) => ctx.renameMap.get(path) ?? path);
7283
7540
  const locs = formatLocs(rewritten);
7284
7541
  const renamed = formatLocs(original).join("\x00") !== locs.join("\x00");
7285
7542
  if (everyFileDeleted(rewritten, ctx.deletedFiles)) {
@@ -7367,8 +7624,8 @@ function triageHeldStatus(triage) {
7367
7624
  function everyFileDeleted(identity, deletedFiles) {
7368
7625
  if (identity.size === 0)
7369
7626
  return false;
7370
- for (const path2 of identity.keys()) {
7371
- if (!deletedFiles.has(path2))
7627
+ for (const path of identity.keys()) {
7628
+ if (!deletedFiles.has(path))
7372
7629
  return false;
7373
7630
  }
7374
7631
  return true;
@@ -7431,6 +7688,8 @@ function applyWorsening(input) {
7431
7688
 
7432
7689
  // src/rereview/state.ts
7433
7690
  init_preflight3();
7691
+ init_findings();
7692
+ init_materiality_gate();
7434
7693
  init_brand();
7435
7694
  var PR_STATE_MARKER_PREFIX = `${MARKER_OPEN}state `;
7436
7695
  var GITHUB_ISSUE_COMMENT_MAX = 65536;
@@ -7577,8 +7836,8 @@ function asStateFindings(parsed) {
7577
7836
  if (!Array.isArray(findings))
7578
7837
  return null;
7579
7838
  const out = [];
7580
- for (const row2 of findings) {
7581
- const finding = asStateFinding(row2);
7839
+ for (const row of findings) {
7840
+ const finding = asStateFinding(row);
7582
7841
  if (finding === null)
7583
7842
  return null;
7584
7843
  out.push(finding);
@@ -7604,10 +7863,10 @@ function asStateReviews(parsed) {
7604
7863
  }
7605
7864
  return reviews;
7606
7865
  }
7607
- function asStateFinding(row2) {
7608
- if (typeof row2 !== "object" || row2 === null)
7866
+ function asStateFinding(row) {
7867
+ if (typeof row !== "object" || row === null)
7609
7868
  return null;
7610
- const r = row2;
7869
+ const r = row;
7611
7870
  if (typeof r.id !== "string" || !R_ID.test(r.id))
7612
7871
  return null;
7613
7872
  if (!isRecoveredSeverity(r.sev) || !isRecoveredTier(r.tier))
@@ -7644,24 +7903,25 @@ function assembleLive(input) {
7644
7903
  const verifiedGoneIds = [];
7645
7904
  let returned = 0;
7646
7905
  let reTiered = 0;
7647
- for (const row2 of input.settled) {
7648
- let status = row2.status;
7649
- if (status === "queued" && row2.held !== undefined) {
7650
- status = input.verifyVerdicts.get(row2.id) === "verified-gone" ? "verified-gone" : row2.held;
7906
+ for (const row of input.settled) {
7907
+ let status = row.status;
7908
+ if (status === "queued" && row.held !== undefined) {
7909
+ status = input.verifyVerdicts.get(row.id) === "verified-gone" ? "verified-gone" : row.held;
7651
7910
  } else if (status === "queued") {
7652
- status = input.verifyVerdicts.get(row2.id) ?? "unconfirmed";
7911
+ status = input.verifyVerdicts.get(row.id) ?? "unconfirmed";
7653
7912
  }
7654
7913
  if (status === "verified-gone") {
7655
- verifiedGoneIds.push(row2.id);
7914
+ verifiedGoneIds.push(row.id);
7656
7915
  continue;
7657
7916
  }
7658
- const gatePrior = priorById.get(row2.id);
7917
+ const gatePrior = priorById.get(row.id);
7659
7918
  if (gatePrior !== undefined) {
7660
7919
  gateRows.push({
7661
7920
  id: gatePrior.id,
7662
7921
  tier: gatePrior.tier,
7663
- locs: row2.locs,
7664
- status
7922
+ locs: row.locs,
7923
+ status,
7924
+ claim: gatePrior.claim
7665
7925
  });
7666
7926
  }
7667
7927
  let persisted;
@@ -7680,7 +7940,7 @@ function assembleLive(input) {
7680
7940
  sev: gatePrior.sev,
7681
7941
  tier: gatePrior.tier,
7682
7942
  channel: gatePrior.channel,
7683
- locs: row2.locs,
7943
+ locs: row.locs,
7684
7944
  c: liveFingerprint(gatePrior.id, gatePrior.claim),
7685
7945
  claim: gatePrior.claim,
7686
7946
  status: persisted
@@ -7700,25 +7960,52 @@ function assembleLive(input) {
7700
7960
  reTiered
7701
7961
  };
7702
7962
  }
7963
+ function isDemotedFromBlocking(survivor) {
7964
+ if (survivor.tier !== "advisory")
7965
+ return false;
7966
+ if (survivor.materiality?.label === "immaterial")
7967
+ return true;
7968
+ const {
7969
+ severity,
7970
+ evidence_class,
7971
+ refuter_verdict,
7972
+ causal_disposition,
7973
+ claim
7974
+ } = survivor;
7975
+ if (severity === undefined || evidence_class === undefined || refuter_verdict === undefined || refuter_verdict === "not_submitted" || causal_disposition === undefined || claim === undefined)
7976
+ return false;
7977
+ const finding = {
7978
+ severity,
7979
+ evidence_class,
7980
+ refuter_verdict,
7981
+ causal_disposition,
7982
+ claim,
7983
+ path: survivor.path
7984
+ };
7985
+ return isCausallyExempt(finding) && deriveTier({ ...finding, causal_disposition: "introduced" }) === "blocking";
7986
+ }
7703
7987
  var PAIR_PREFERENCE = [
7704
7988
  "blocking",
7705
7989
  TIER_UNRECOVERABLE,
7706
7990
  "advisory"
7707
7991
  ];
7708
7992
  function pairBlockingSurvivors(survivors, rows) {
7709
- const identities = rows.map((row2) => identityFromLocs(row2.locs));
7710
- const paired = new Set;
7993
+ return pairInto(survivors, rows, new Set, (survivor) => survivor.tier === "blocking" ? PAIR_PREFERENCE : null);
7994
+ }
7995
+ function pairInto(survivors, rows, paired, preferenceOf, rowAllowed = () => true) {
7996
+ const identities = rows.map((row) => identityFromLocs(row.locs));
7711
7997
  const pairs = [];
7712
7998
  survivors.forEach((survivor, s) => {
7713
- if (survivor.tier !== "blocking")
7999
+ const preference = preferenceOf(survivor);
8000
+ if (preference === null)
7714
8001
  return;
7715
8002
  const survivorIdentity = identityFromFinding({
7716
8003
  path: survivor.path,
7717
8004
  line: survivor.line,
7718
8005
  proof_refs: survivor.proof_refs
7719
8006
  });
7720
- for (const tier of PAIR_PREFERENCE) {
7721
- const pick = rows.findIndex((row2, i) => !paired.has(i) && row2.tier === tier && identitiesMatch(identities[i] ?? new Map, survivorIdentity));
8007
+ for (const tier of preference) {
8008
+ const pick = rows.findIndex((row, i) => !paired.has(i) && row.tier === tier && rowAllowed(i) && identitiesMatch(identities[i] ?? new Map, survivorIdentity));
7722
8009
  if (pick !== -1) {
7723
8010
  paired.add(pick);
7724
8011
  pairs.push({ survivor: s, row: pick });
@@ -7728,30 +8015,53 @@ function pairBlockingSurvivors(survivors, rows) {
7728
8015
  });
7729
8016
  return pairs;
7730
8017
  }
7731
- function unresolvedBlockingCount(survivors, rows) {
7732
- const blockingSurvivors = survivors.filter((survivor) => survivor.tier === "blocking").length;
8018
+ function gatePairing(survivors, rows) {
7733
8019
  const seen = new Set;
7734
- const open2 = [];
7735
- for (const row2 of rows) {
7736
- if (row2.status === "verified-gone" || row2.status === "ci-dismissed") {
8020
+ const open = [];
8021
+ for (const row of rows) {
8022
+ if (row.status === "verified-gone" || row.status === "ci-dismissed") {
7737
8023
  continue;
7738
8024
  }
7739
- if (seen.has(row2.id))
8025
+ if (seen.has(row.id))
7740
8026
  continue;
7741
- seen.add(row2.id);
7742
- open2.push(row2);
8027
+ seen.add(row.id);
8028
+ open.push(row);
8029
+ }
8030
+ const taken = new Set;
8031
+ const carried = new Set(pairInto(survivors, open, taken, (survivor) => survivor.tier === "blocking" ? PAIR_PREFERENCE : null).map((p) => p.row));
8032
+ const released = new Set(pairInto(survivors, open, taken, (survivor) => isDemotedFromBlocking(survivor) ? ["blocking"] : null, (i) => isReleasable(open[i])).map((p) => p.row));
8033
+ return { open, carried, released };
8034
+ }
8035
+ function isReleasable(row) {
8036
+ const claim = row?.claim;
8037
+ if (row === undefined || claim === undefined || claim.trim().length === 0) {
8038
+ return false;
7743
8039
  }
7744
- const paired = new Set(pairBlockingSurvivors(survivors, open2).map((p) => p.row));
8040
+ const paths = [...identityFromLocs(row.locs).keys()];
8041
+ if (paths.length === 0)
8042
+ return !isSafetyProtected({ claim, path: "" });
8043
+ return paths.every((path) => !isSafetyProtected({ claim, path }));
8044
+ }
8045
+ function unresolvedBlockingCount(survivors, rows) {
8046
+ const blockingSurvivors = survivors.filter((survivor) => survivor.tier === "blocking").length;
8047
+ const { open, carried, released } = gatePairing(survivors, rows);
7745
8048
  let unpairedBlocking = 0;
7746
- for (let i = 0;i < open2.length; i++) {
7747
- if (paired.has(i))
8049
+ for (let i = 0;i < open.length; i++) {
8050
+ if (carried.has(i) || released.has(i))
7748
8051
  continue;
7749
- const tier = open2[i]?.tier;
8052
+ const tier = open[i]?.tier;
7750
8053
  if (tier === "blocking" || tier === TIER_UNRECOVERABLE)
7751
8054
  unpairedBlocking++;
7752
8055
  }
7753
8056
  return blockingSurvivors + unpairedBlocking;
7754
8057
  }
8058
+ function materialityReleasedIds(survivors, rows) {
8059
+ const { open, released } = gatePairing(survivors, rows);
8060
+ return [...released].flatMap((i) => {
8061
+ const row = open[i];
8062
+ return row === undefined ? [] : [row.id];
8063
+ });
8064
+ }
7755
8065
  var VISIBLE_BODY_RESERVE = 4096;
7756
8066
  function stateBlockBudget(referenceBodyLength) {
7757
8067
  return Math.max(0, GITHUB_ISSUE_COMMENT_MAX - referenceBodyLength - VISIBLE_BODY_RESERVE);
@@ -7759,32 +8069,38 @@ function stateBlockBudget(referenceBodyLength) {
7759
8069
  function mergeStateFindings(input) {
7760
8070
  const priorIds = [
7761
8071
  ...(input.previous?.findings ?? []).map((f) => f.id),
7762
- ...input.live.map((row2) => row2.id),
8072
+ ...input.live.map((row) => row.id),
7763
8073
  ...input.retiredIds ?? []
7764
8074
  ];
7765
8075
  let hw = Math.max(input.previous?.hw ?? 0, highestStableNumber(priorIds));
7766
- const rows = input.live.map((row2) => ({ ...row2 }));
8076
+ const rows = input.live.map((row) => ({ ...row }));
7767
8077
  if (input.previousHead != null && input.previousHead === input.headSha) {
7768
8078
  const held = new Set([
7769
- ...input.live.map((row2) => row2.id),
8079
+ ...input.live.map((row) => row.id),
7770
8080
  ...input.retiredIds ?? []
7771
8081
  ]);
7772
- for (const row2 of input.previous?.findings ?? []) {
7773
- if (held.has(row2.id))
8082
+ for (const row of input.previous?.findings ?? []) {
8083
+ if (held.has(row.id))
7774
8084
  continue;
7775
- rows.push({ ...row2, status: "unconfirmed" });
8085
+ rows.push({ ...row, status: "unconfirmed" });
8086
+ }
8087
+ }
8088
+ const released = new Set(input.releasedIds ?? []);
8089
+ for (const [i, row] of rows.entries()) {
8090
+ if (row.tier === "blocking" && released.has(row.id)) {
8091
+ rows[i] = { ...row, tier: "advisory" };
7776
8092
  }
7777
8093
  }
7778
8094
  const touched = new Set;
7779
- const pairs = pairBlockingSurvivors(input.fresh, rows.map((row2) => ({ tier: row2.tier, locs: row2.locs })));
8095
+ const pairs = pairBlockingSurvivors(input.fresh, rows.map((row) => ({ tier: row.tier, locs: row.locs })));
7780
8096
  const rowOfSurvivor = new Map(pairs.map((p) => [p.survivor, p.row]));
7781
8097
  const takenRows = new Set(pairs.map((p) => p.row));
7782
- const rowIdentities = rows.map((row2) => identityFromLocs(row2.locs));
8098
+ const rowIdentities = rows.map((row) => identityFromLocs(row.locs));
7783
8099
  for (const [s, finding] of input.fresh.entries()) {
7784
8100
  if (finding.tier !== "advisory" || rowOfSurvivor.has(s))
7785
8101
  continue;
7786
8102
  const identity = identityFromFinding(finding);
7787
- const pick = rows.findIndex((row2, i) => !takenRows.has(i) && row2.tier === "advisory" && identitiesMatch(rowIdentities[i] ?? new Map, identity));
8103
+ const pick = rows.findIndex((row, i) => !takenRows.has(i) && row.tier === "advisory" && identitiesMatch(rowIdentities[i] ?? new Map, identity));
7788
8104
  if (pick === -1)
7789
8105
  continue;
7790
8106
  takenRows.add(pick);
@@ -7846,6 +8162,7 @@ function droppedStateNote(count) {
7846
8162
  }
7847
8163
 
7848
8164
  // src/rereview/verify.ts
8165
+ init_boundary();
7849
8166
  import path13 from "path";
7850
8167
  var VERIFY_BATCH_FILE = "verify-batch.json";
7851
8168
  var VERIFY_STEPS_DIR = "verify";
@@ -7898,7 +8215,7 @@ function capVerificationQueue(queued, max) {
7898
8215
  const ranked = unique.map((entry, index) => ({ entry, index })).sort((a, b) => {
7899
8216
  const rank = verifyQueueRank(a.entry.sev) - verifyQueueRank(b.entry.sev);
7900
8217
  return rank !== 0 ? rank : a.index - b.index;
7901
- }).map((row2) => row2.entry);
8218
+ }).map((row) => row.entry);
7902
8219
  return {
7903
8220
  verify: ranked.slice(0, max),
7904
8221
  capped: ranked.slice(max)
@@ -7979,7 +8296,11 @@ function composeVerifyPrompt(subject, nonce) {
7979
8296
  `);
7980
8297
  }
7981
8298
 
8299
+ // src/review/pipeline.ts
8300
+ init_boundary();
8301
+
7982
8302
  // src/review/consolidate.ts
8303
+ init_boundary();
7983
8304
  function validatePlan(raw, ids, draftIds) {
7984
8305
  const plan = raw?.findings;
7985
8306
  if (!Array.isArray(plan) || plan.length === 0) {
@@ -8127,9 +8448,11 @@ function enforcePlanInvariants(plan, findings, stats) {
8127
8448
 
8128
8449
  // src/review/pipeline.ts
8129
8450
  init_findings();
8451
+ init_materiality_gate();
8130
8452
 
8131
8453
  // src/review/prompt-set.ts
8132
8454
  init_catalog();
8455
+ init_boundary();
8133
8456
  var AGENT_NAMES = [
8134
8457
  "deep-review-reliability",
8135
8458
  "deep-review-resilience",
@@ -8449,8 +8772,8 @@ init_admission();
8449
8772
 
8450
8773
  // src/diversity/clustering.ts
8451
8774
  import { createHash as createHash4 } from "crypto";
8452
- function canonicalProofAnchor(path14, symbol, span) {
8453
- const normalizedPath = path14.replace(/\\/g, "/");
8775
+ function canonicalProofAnchor(path, symbol, span) {
8776
+ const normalizedPath = path.replace(/\\/g, "/");
8454
8777
  const anchorHash = createHash4("sha256").update(`${normalizedPath}|${symbol ?? ""}|${span}`).digest("hex");
8455
8778
  return { path: normalizedPath, symbol, anchorHash };
8456
8779
  }
@@ -8489,9 +8812,9 @@ function maxSeverity(observations) {
8489
8812
  }
8490
8813
  function sortObservations(observations) {
8491
8814
  return [...observations].sort((a, b) => {
8492
- const path14 = a.path.localeCompare(b.path);
8493
- if (path14 !== 0)
8494
- return path14;
8815
+ const path = a.path.localeCompare(b.path);
8816
+ if (path !== 0)
8817
+ return path;
8495
8818
  const symbol = (a.symbol ?? "").localeCompare(b.symbol ?? "");
8496
8819
  if (symbol !== 0)
8497
8820
  return symbol;
@@ -8792,7 +9115,10 @@ function projectAdjudicationToFindings(adjudication, specialty, startingId = 1)
8792
9115
  tier: deriveTier({
8793
9116
  severity: canonical.severity,
8794
9117
  evidence_class: canonical.evidenceClass,
8795
- refuter_verdict: refuterVerdict
9118
+ refuter_verdict: refuterVerdict,
9119
+ causal_disposition: canonical.causalDisposition,
9120
+ claim: canonical.claim,
9121
+ path: canonical.path
8796
9122
  }),
8797
9123
  hops_used: canonical.hopsUsed,
8798
9124
  hop_trail: canonical.hopTrail,
@@ -10083,58 +10409,12 @@ class OpenCodeFreeBroker {
10083
10409
  }
10084
10410
  }
10085
10411
 
10086
- // src/security/evidence-redaction.ts
10087
- var MAX_BYTES = 4 * 1024 * 1024;
10088
- var SECRET = /authorization|cookie|password|secret|api.?key|access.?token|refresh.?token|^token$|^key$/i;
10089
- function redactEvidenceText(value) {
10090
- return value.replace(/\b(?:authorization|proxy-authorization|cookie|set-cookie)\s*:[^\r\n]*/gi, "[REDACTED HEADER]").replace(/https?:\/\/[^\s<>"']+/gi, (text) => {
10091
- try {
10092
- const url = new URL(text);
10093
- url.username = "";
10094
- url.password = "";
10095
- for (const key of [...url.searchParams.keys()])
10096
- if (SECRET.test(key))
10097
- url.searchParams.set(key, "[REDACTED]");
10098
- return url.toString();
10099
- } catch {
10100
- return "[REDACTED URL]";
10101
- }
10102
- }).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]");
10103
- }
10104
- function redactEvidence(value, depth = 0, budget = { nodes: 0 }) {
10105
- if (++budget.nodes > 20000 || depth > 12)
10106
- throw new Error("capture shape limit");
10107
- if (typeof value === "string") {
10108
- if (value.length > MAX_BYTES)
10109
- throw new Error("capture string limit");
10110
- return redactEvidenceText(value);
10111
- }
10112
- if (value === null || typeof value === "boolean" || typeof value === "number")
10113
- return value;
10114
- if (value === undefined)
10115
- return null;
10116
- if (typeof value !== "object")
10117
- throw new Error("non-JSON capture value");
10118
- const proto = Object.getPrototypeOf(value);
10119
- if (proto !== Object.prototype && proto !== Array.prototype && proto !== null)
10120
- throw new Error("non-JSON capture object");
10121
- const result = {};
10122
- for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
10123
- if (key === "length" && Array.isArray(value))
10124
- continue;
10125
- if (!("value" in descriptor))
10126
- throw new Error("capture accessor rejected");
10127
- if (!descriptor.enumerable)
10128
- continue;
10129
- result[key] = SECRET.test(key) ? "[REDACTED]" : redactEvidence(descriptor.value, depth + 1, budget);
10130
- }
10131
- return Array.isArray(value) ? Object.values(result) : result;
10132
- }
10133
-
10134
10412
  // src/execution/harness.ts
10413
+ init_evidence_redaction();
10135
10414
  init_redact();
10136
10415
 
10137
10416
  // src/security/workspace-read-broker.ts
10417
+ init_boundary();
10138
10418
  import {
10139
10419
  existsSync as existsSync9,
10140
10420
  lstatSync as lstatSync2,
@@ -10738,13 +11018,13 @@ function loadOrCreateBucketKey(home, deps = {}) {
10738
11018
  const exists = deps.existsFn ?? existsSync11;
10739
11019
  const readBytes = deps.readFileFn ?? ((p) => readFileSync5(p));
10740
11020
  const writeBytes = deps.writeFileFn ?? ((p, data) => writeFileSync3(p, data, { mode: 384, flag: "wx" }));
10741
- const mkdir5 = deps.mkdirFn ?? ((p) => mkdirSync4(p, { recursive: true }));
11021
+ const mkdir = deps.mkdirFn ?? ((p) => mkdirSync4(p, { recursive: true }));
10742
11022
  const makeRandomBytes = deps.randomBytesFn ?? ((n) => nodeRandomBytes(n));
10743
11023
  const layout = prheroLayout(home);
10744
11024
  if (exists(layout.bucketKeyPath)) {
10745
11025
  return readBytes(layout.bucketKeyPath);
10746
11026
  }
10747
- mkdir5(layout.dir);
11027
+ mkdir(layout.dir);
10748
11028
  const key = makeRandomBytes(BUCKET_KEY_BYTES);
10749
11029
  try {
10750
11030
  writeBytes(layout.bucketKeyPath, key);
@@ -11247,11 +11527,11 @@ var CREDIT_OR_SPEND_LIMIT = /credit balance|spend limit|usage limit/i;
11247
11527
  var SUBSCRIPTION_OR_SPEND_CAP = /hit your .*limit|usage limit|spend cap|spend limit/i;
11248
11528
  var USAGE_LIMIT_NO_STATUS = /hit your .*limit|usage limit|credit balance|spend cap|spend limit/i;
11249
11529
  var NOT_LOGGED_IN = /Not logged in\s*[\u00B7.]\s*Please run \/login/i;
11250
- function claudeCliErrorCause(envelope2) {
11251
- const status = typeof envelope2.api_error_status === "number" && Number.isInteger(envelope2.api_error_status) ? envelope2.api_error_status : undefined;
11252
- const reason = typeof envelope2.terminal_reason === "string" ? envelope2.terminal_reason : undefined;
11253
- const subtype = typeof envelope2.subtype === "string" ? envelope2.subtype : undefined;
11254
- const message = typeof envelope2.result === "string" ? envelope2.result : "";
11530
+ function claudeCliErrorCause(envelope) {
11531
+ const status = typeof envelope.api_error_status === "number" && Number.isInteger(envelope.api_error_status) ? envelope.api_error_status : undefined;
11532
+ const reason = typeof envelope.terminal_reason === "string" ? envelope.terminal_reason : undefined;
11533
+ const subtype = typeof envelope.subtype === "string" ? envelope.subtype : undefined;
11534
+ const message = typeof envelope.result === "string" ? envelope.result : "";
11255
11535
  if (reason === "prompt_too_long" || status === 413) {
11256
11536
  return "context_window_exceeded";
11257
11537
  }
@@ -11297,22 +11577,22 @@ function claudeCliErrorCause(envelope2) {
11297
11577
  }
11298
11578
  return;
11299
11579
  }
11300
- function providerApiErrorOf(envelope2) {
11301
- if (envelope2.is_error !== true)
11580
+ function providerApiErrorOf(envelope) {
11581
+ if (envelope.is_error !== true)
11302
11582
  return;
11303
- const cause = claudeCliErrorCause(envelope2);
11304
- const status = typeof envelope2.api_error_status === "number" ? envelope2.api_error_status : undefined;
11305
- const reason = typeof envelope2.terminal_reason === "string" ? envelope2.terminal_reason : undefined;
11306
- const subtype = typeof envelope2.subtype === "string" ? envelope2.subtype : undefined;
11307
- const message = typeof envelope2.result === "string" ? envelope2.result : "";
11583
+ const cause = claudeCliErrorCause(envelope);
11584
+ const status = typeof envelope.api_error_status === "number" ? envelope.api_error_status : undefined;
11585
+ const reason = typeof envelope.terminal_reason === "string" ? envelope.terminal_reason : undefined;
11586
+ const subtype = typeof envelope.subtype === "string" ? envelope.subtype : undefined;
11587
+ const message = typeof envelope.result === "string" ? envelope.result : "";
11308
11588
  if (cause === undefined) {
11309
11589
  const tag = oneLine(reason ?? (subtype !== undefined && subtype !== "success" ? subtype : ""), UNNAMED_TAG_MAX) || "unknown";
11310
- const suffix2 = ` (${tag}${status === undefined ? "" : `, HTTP ${status}`})`;
11311
- const prefix2 = "Claude CLI: ";
11312
- const words2 = oneLine(message.trim() === "" ? "no message" : message, API_ERROR_DETAIL_MAX - prefix2.length - suffix2.length);
11590
+ const suffix = ` (${tag}${status === undefined ? "" : `, HTTP ${status}`})`;
11591
+ const prefix = "Claude CLI: ";
11592
+ const words = oneLine(message.trim() === "" ? "no message" : message, API_ERROR_DETAIL_MAX - prefix.length - suffix.length);
11313
11593
  return {
11314
11594
  cause: "provider_configuration_invalid",
11315
- detail: `${prefix2}${words2}${suffix2}`
11595
+ detail: `${prefix}${words}${suffix}`
11316
11596
  };
11317
11597
  }
11318
11598
  const named = subtype !== undefined && subtype !== "success" ? subtype : reason;
@@ -11432,11 +11712,11 @@ function consumedOpenCodeContractDigest(document) {
11432
11712
  const sourceSchemas = record(record(root.components).schemas);
11433
11713
  const paths = {};
11434
11714
  const schemas = {};
11435
- for (const [path20, methods] of Object.entries(operations)) {
11436
- paths[path20] = Object.fromEntries(methods.map((method) => {
11437
- const operation = record(allPaths[path20])[method];
11715
+ for (const [path, methods] of Object.entries(operations)) {
11716
+ paths[path] = Object.fromEntries(methods.map((method) => {
11717
+ const operation = record(allPaths[path])[method];
11438
11718
  if (operation === undefined)
11439
- throw new Error(`OpenCode contract lacks ${method} ${path20}`);
11719
+ throw new Error(`OpenCode contract lacks ${method} ${path}`);
11440
11720
  return [method, operation];
11441
11721
  }));
11442
11722
  }
@@ -11594,7 +11874,7 @@ class OpenCodeQualificationTransportError extends Error {
11594
11874
  async function qualifyOpenCodeServer(url, expected, signal, fetcher = fetch, options = {}) {
11595
11875
  signal?.throwIfAborted();
11596
11876
  const backoffMs = options.backoffMs ?? QUALIFY_BACKOFF_MS;
11597
- const attempt = async (path20, deadlineMs) => {
11877
+ const attempt = async (path, deadlineMs) => {
11598
11878
  const controller = new AbortController;
11599
11879
  const abort = () => controller.abort(signal?.reason);
11600
11880
  signal?.addEventListener("abort", abort, { once: true });
@@ -11615,12 +11895,12 @@ async function qualifyOpenCodeServer(url, expected, signal, fetcher = fetch, opt
11615
11895
  try {
11616
11896
  let response;
11617
11897
  try {
11618
- response = await withAbort(fetcher(new URL(path20, url), { signal: controller.signal }), controller.signal);
11898
+ response = await withAbort(fetcher(new URL(path, url), { signal: controller.signal }), controller.signal);
11619
11899
  } catch (error) {
11620
11900
  throw transport(error);
11621
11901
  }
11622
11902
  if (!response.ok || response.body === null) {
11623
- const message = `OpenCode qualification unavailable: ${path20}`;
11903
+ const message = `OpenCode qualification unavailable: ${path}`;
11624
11904
  throw response.status >= 500 ? new OpenCodeQualificationTransportError(message) : new Error(message);
11625
11905
  }
11626
11906
  let text;
@@ -11636,10 +11916,10 @@ async function qualifyOpenCodeServer(url, expected, signal, fetcher = fetch, opt
11636
11916
  controller.abort();
11637
11917
  }
11638
11918
  };
11639
- const get = async (path20, deadlineMs) => {
11919
+ const get = async (path, deadlineMs) => {
11640
11920
  for (let n = 1;; n++) {
11641
11921
  try {
11642
- return await attempt(path20, deadlineMs);
11922
+ return await attempt(path, deadlineMs);
11643
11923
  } catch (error) {
11644
11924
  if (signal?.aborted || !(error instanceof OpenCodeQualificationTransportError) || n >= QUALIFY_ATTEMPTS)
11645
11925
  throw error;
@@ -11671,6 +11951,8 @@ async function qualifyOpenCodeServer(url, expected, signal, fetcher = fetch, opt
11671
11951
  }
11672
11952
 
11673
11953
  // src/transports/opencode-evidence.ts
11954
+ init_evidence_redaction();
11955
+ init_evidence_redaction();
11674
11956
  var MAX_BYTES2 = 4 * 1024 * 1024;
11675
11957
  var MAX_RECORDS = 1e4;
11676
11958
  var HEAD_MAX_RECORDS = 1000;
@@ -11952,18 +12234,18 @@ function mcpToolIdsFor(config) {
11952
12234
  return ids;
11953
12235
  }
11954
12236
  function assertMcpConnected(status, expected) {
11955
- const record2 = asRecord(status);
11956
- if (record2 === undefined) {
12237
+ const record = asRecord(status);
12238
+ if (record === undefined) {
11957
12239
  throw new Error("opencode reported an unreadable MCP status, so the connected server " + "set cannot be verified; refusing to prompt a session whose tool " + "channels are unknown");
11958
12240
  }
11959
12241
  const declared = new Set(expected);
11960
- const connected = Object.keys(record2).sort();
12242
+ const connected = Object.keys(record).sort();
11961
12243
  const extra = connected.filter((name) => !declared.has(name));
11962
12244
  if (extra.length > 0) {
11963
12245
  throw new Error(`opencode connected MCP servers Crysk did not declare: ${extra.join(", ")}` + ` (declared: ${expected.length === 0 ? "none" : [...declared].sort().join(", ")})`);
11964
12246
  }
11965
12247
  for (const name of [...declared].sort()) {
11966
- const entry = asRecord(record2[name]);
12248
+ const entry = asRecord(record[name]);
11967
12249
  if (entry === undefined) {
11968
12250
  throw new Error(`opencode did not connect the declared MCP server "${name}"`);
11969
12251
  }
@@ -13063,15 +13345,15 @@ var ACCOUNT_LIMIT_REASONS = new Set([
13063
13345
  "account_rate_limit"
13064
13346
  ]);
13065
13347
  function providerLimitFromStatus(status) {
13066
- const record2 = asRecord2(status);
13067
- if (record2?.type !== "retry")
13348
+ const record = asRecord2(status);
13349
+ if (record?.type !== "retry")
13068
13350
  return;
13069
- const action = asRecord2(record2.action);
13351
+ const action = asRecord2(record.action);
13070
13352
  const reason = action?.reason;
13071
13353
  if (typeof reason !== "string" || !ACCOUNT_LIMIT_REASONS.has(reason)) {
13072
13354
  return;
13073
13355
  }
13074
- const message = typeof record2.message === "string" ? record2.message : "";
13356
+ const message = typeof record.message === "string" ? record.message : "";
13075
13357
  return { reason, message };
13076
13358
  }
13077
13359
  function providerRefusalFromProperties(properties) {
@@ -13138,11 +13420,11 @@ function failIntegrity(state, detail) {
13138
13420
  state.integrityFailure = `[pr-hero] opencode client: ${detail}`;
13139
13421
  throw new Error(state.integrityFailure);
13140
13422
  }
13141
- function canonicalDirectory(path20) {
13423
+ function canonicalDirectory(path) {
13142
13424
  try {
13143
- return realpathSync2(path20);
13425
+ return realpathSync2(path);
13144
13426
  } catch {
13145
- return resolve(path20);
13427
+ return resolve(path);
13146
13428
  }
13147
13429
  }
13148
13430
  function trackPayload(state, key, value) {
@@ -13183,8 +13465,8 @@ function trackMessage(state, info) {
13183
13465
  if (!state.payloadBytes.has(`message:${id}`) && [...state.payloadBytes.keys()].filter((key) => key.startsWith("message:")).length >= MAX_TRACKED_MESSAGES) {
13184
13466
  failIntegrity(state, "message cap exceeded (cap exhaustion)");
13185
13467
  }
13186
- const path20 = asRecord2(info.path);
13187
- if (info.role === "assistant" && state.expectedCwd !== undefined && (typeof path20?.cwd !== "string" || canonicalDirectory(path20.cwd) !== canonicalDirectory(state.expectedCwd))) {
13468
+ const path = asRecord2(info.path);
13469
+ if (info.role === "assistant" && state.expectedCwd !== undefined && (typeof path?.cwd !== "string" || canonicalDirectory(path.cwd) !== canonicalDirectory(state.expectedCwd))) {
13188
13470
  failIntegrity(state, "message cwd mismatch or unavailable");
13189
13471
  }
13190
13472
  trackPayload(state, `message:${id}`, info);
@@ -13394,19 +13676,19 @@ function handlePartUpdated(p, state) {
13394
13676
  }
13395
13677
  if (msgDetail)
13396
13678
  msgDetail.hasToolCalls = true;
13397
- const events2 = [];
13679
+ const events = [];
13398
13680
  if (transitioned) {
13399
- events2.push({ kind: "activity" });
13681
+ events.push({ kind: "activity" });
13400
13682
  }
13401
13683
  if (status === "completed") {
13402
13684
  state.completedToolCallIds.add(callId);
13403
13685
  if (!state.streamCompletedToolCallIds.has(callId)) {
13404
13686
  const tool = typeof part.tool === "string" && part.tool.length > 0 ? part.tool : "unknown";
13405
13687
  state.streamCompletedToolCallIds.add(callId);
13406
- events2.push({ kind: "tool", tool, callId });
13688
+ events.push({ kind: "tool", tool, callId });
13407
13689
  }
13408
13690
  }
13409
- return events2;
13691
+ return events;
13410
13692
  }
13411
13693
  if (partType === "reasoning") {
13412
13694
  if (!isMessageOwned(messageId, state))
@@ -13542,14 +13824,14 @@ function handlePartDelta(p, state, eventId) {
13542
13824
  return [];
13543
13825
  }
13544
13826
  function reconcileUnknownOwnerBuffer(messageId, state) {
13545
- const events2 = [];
13827
+ const events = [];
13546
13828
  const remaining = [];
13547
13829
  for (const obs of state.unknownOwnerBuffer) {
13548
13830
  if (obs.messageId === messageId) {
13549
13831
  if (obs.type === "part.updated") {
13550
- events2.push(...handlePartUpdated(obs.raw, state));
13832
+ events.push(...handlePartUpdated(obs.raw, state));
13551
13833
  } else if (obs.type === "part.delta") {
13552
- events2.push(...handlePartDelta(obs.raw, state, obs.eventId));
13834
+ events.push(...handlePartDelta(obs.raw, state, obs.eventId));
13553
13835
  }
13554
13836
  } else {
13555
13837
  remaining.push(obs);
@@ -13557,7 +13839,7 @@ function reconcileUnknownOwnerBuffer(messageId, state) {
13557
13839
  }
13558
13840
  state.unknownOwnerBuffer.length = 0;
13559
13841
  state.unknownOwnerBuffer.push(...remaining);
13560
- return events2;
13842
+ return events;
13561
13843
  }
13562
13844
  function reconcileMessages(list, state, options) {
13563
13845
  const emit = options?.emit ?? true;
@@ -13759,9 +14041,9 @@ function reconcileMessages(list, state, options) {
13759
14041
  if (!msgDetail)
13760
14042
  continue;
13761
14043
  if (msgDetail.error !== undefined) {
13762
- const proof2 = terminalProofFromAssistant(msgDetail, state);
13763
- if (proof2)
13764
- return { events: [], terminalProof: proof2, finalText: "" };
14044
+ const proof = terminalProofFromAssistant(msgDetail, state);
14045
+ if (proof)
14046
+ return { events: [], terminalProof: proof, finalText: "" };
13765
14047
  }
13766
14048
  const evalRes = evaluateFinalAssistant(msgDetail, state);
13767
14049
  if (!evalRes.valid)
@@ -13769,7 +14051,7 @@ function reconcileMessages(list, state, options) {
13769
14051
  const proof = terminalProofFromAssistant(msgDetail, state);
13770
14052
  if (proof === undefined)
13771
14053
  continue;
13772
- const events2 = [];
14054
+ const events = [];
13773
14055
  let canonicalFinalText = "";
13774
14056
  for (const partId of msgDetail.partIds) {
13775
14057
  const detail = state.partDetails.get(partId);
@@ -13787,11 +14069,11 @@ function reconcileMessages(list, state, options) {
13787
14069
  }
13788
14070
  if (alreadyEmitted.length === 0) {
13789
14071
  detail.emittedText = snapshotText;
13790
- events2.push({ kind: "delta", text: snapshotText });
14072
+ events.push({ kind: "delta", text: snapshotText });
13791
14073
  } else if (snapshotText.startsWith(alreadyEmitted)) {
13792
14074
  const suffix = snapshotText.slice(alreadyEmitted.length);
13793
14075
  detail.emittedText = snapshotText;
13794
- events2.push({ kind: "delta", text: suffix });
14076
+ events.push({ kind: "delta", text: suffix });
13795
14077
  } else {
13796
14078
  state.integrityFailure = `[pr-hero] opencode client: conflicting snapshot in readback for part ${partId}`;
13797
14079
  return {
@@ -13804,7 +14086,7 @@ function reconcileMessages(list, state, options) {
13804
14086
  const totalUsage = turnUsage(state);
13805
14087
  const isIncomplete = state.usageIncomplete === true || state.usageConflict === true || state.usageCapped === true;
13806
14088
  return {
13807
- events: events2,
14089
+ events,
13808
14090
  terminalProof: proof,
13809
14091
  finalText: canonicalFinalText,
13810
14092
  usage: totalUsage,
@@ -14166,10 +14448,10 @@ function createOpenCodeClient(options) {
14166
14448
  try {
14167
14449
  await Promise.race([
14168
14450
  work(controller.signal),
14169
- new Promise((resolve2) => {
14451
+ new Promise((resolve) => {
14170
14452
  timer = setTimeout(() => {
14171
14453
  controller.abort();
14172
- resolve2();
14454
+ resolve();
14173
14455
  }, remaining);
14174
14456
  })
14175
14457
  ]);
@@ -14419,8 +14701,8 @@ function createOpenCodeClient(options) {
14419
14701
  throw new Error(state.failure);
14420
14702
  if (state.ended)
14421
14703
  return;
14422
- await new Promise((resolve2) => {
14423
- state.wake = resolve2;
14704
+ await new Promise((resolve) => {
14705
+ state.wake = resolve;
14424
14706
  });
14425
14707
  }
14426
14708
  },
@@ -14606,7 +14888,7 @@ async function launchOpenCodeServer(options) {
14606
14888
  } catch {}
14607
14889
  const escalated = await Promise.race([
14608
14890
  proc.exited.then(() => "exited"),
14609
- new Promise((resolve2) => setTimeout(() => resolve2("grace"), termGraceMs))
14891
+ new Promise((resolve) => setTimeout(() => resolve("grace"), termGraceMs))
14610
14892
  ]);
14611
14893
  if (escalated === "grace") {
14612
14894
  try {
@@ -14614,12 +14896,12 @@ async function launchOpenCodeServer(options) {
14614
14896
  } catch {}
14615
14897
  await Promise.race([
14616
14898
  proc.exited,
14617
- new Promise((resolve2) => setTimeout(resolve2, killReapMs))
14899
+ new Promise((resolve) => setTimeout(resolve, killReapMs))
14618
14900
  ]);
14619
14901
  }
14620
14902
  };
14621
14903
  onSpawned?.(close);
14622
- const url = await new Promise((resolve2, reject) => {
14904
+ const url = await new Promise((resolve, reject) => {
14623
14905
  let settled = false;
14624
14906
  const finish = (fn) => {
14625
14907
  if (settled)
@@ -14668,7 +14950,7 @@ async function launchOpenCodeServer(options) {
14668
14950
  announced = true;
14669
14951
  break;
14670
14952
  }
14671
- finish(() => resolve2(match[1]));
14953
+ finish(() => resolve(match[1]));
14672
14954
  announced = true;
14673
14955
  break;
14674
14956
  }
@@ -14786,14 +15068,14 @@ function planOpenCodeSdkImport(input) {
14786
15068
  function asPackageJson(module) {
14787
15069
  if (typeof module !== "object" || module === null)
14788
15070
  return {};
14789
- const record2 = module;
14790
- if (typeof record2.version === "string" || record2.exports !== undefined) {
14791
- return record2;
15071
+ const record = module;
15072
+ if (typeof record.version === "string" || record.exports !== undefined) {
15073
+ return record;
14792
15074
  }
14793
- if (typeof record2.default === "object" && record2.default !== null) {
14794
- return record2.default;
15075
+ if (typeof record.default === "object" && record.default !== null) {
15076
+ return record.default;
14795
15077
  }
14796
- return record2;
15078
+ return record;
14797
15079
  }
14798
15080
  function normalizeSdkVersion(version) {
14799
15081
  if (typeof version !== "string")
@@ -15284,8 +15566,8 @@ async function admitRoutePlan(plan, registryOrCapabilities, optionsOrRegistry, m
15284
15566
  };
15285
15567
  }
15286
15568
  async function admitDiversityRoutePlan(plan, registryOrCapabilities, optionsOrRegistry, maybeOptions) {
15287
- const { requireInternalFindingsCapability: requireInternalFindingsCapability2 } = await Promise.resolve().then(() => (init_admission(), exports_admission));
15288
- requireInternalFindingsCapability2();
15569
+ await Promise.resolve().then(() => init_admission());
15570
+ requireInternalFindingsCapability();
15289
15571
  return admitRoutePlan(plan, registryOrCapabilities, optionsOrRegistry, maybeOptions);
15290
15572
  }
15291
15573
  function defaultOpenCodeLaunchServer(options) {
@@ -15352,6 +15634,7 @@ function sumUsage(a, b) {
15352
15634
 
15353
15635
  // src/execution/attempt-evidence.ts
15354
15636
  import { createHash as createHash8 } from "crypto";
15637
+ init_evidence_redaction();
15355
15638
  import { mkdir as mkdir5, readFile as readFile5, realpath as realpath3 } from "fs/promises";
15356
15639
  import path21 from "path";
15357
15640
  var evidenceSha256 = (value) => createHash8("sha256").update(value).digest("hex");
@@ -15531,8 +15814,8 @@ async function freezeAttemptEvidenceIdentity(request, step) {
15531
15814
  try {
15532
15815
  await Promise.race([
15533
15816
  planWrite,
15534
- new Promise((resolve2) => {
15535
- timer = setTimeout(resolve2, Math.min(100, Math.max(1, step.timeoutMs)));
15817
+ new Promise((resolve) => {
15818
+ timer = setTimeout(resolve, Math.min(100, Math.max(1, step.timeoutMs)));
15536
15819
  })
15537
15820
  ]);
15538
15821
  } catch {} finally {
@@ -15585,7 +15868,7 @@ class ConcurrencyLimiter {
15585
15868
  if (signal?.aborted) {
15586
15869
  return Promise.reject(new ConcurrencyAdmissionAbortedError(bucketId));
15587
15870
  }
15588
- return new Promise((resolve2, reject) => {
15871
+ return new Promise((resolve, reject) => {
15589
15872
  const onAbort = () => {
15590
15873
  this.removeQueued(bucketId, entry);
15591
15874
  reject(new ConcurrencyAdmissionAbortedError(bucketId));
@@ -15593,7 +15876,7 @@ class ConcurrencyLimiter {
15593
15876
  const detachAbortListener = () => {
15594
15877
  signal?.removeEventListener("abort", onAbort);
15595
15878
  };
15596
- const entry = { resolve: resolve2, reject, detachAbortListener };
15879
+ const entry = { resolve, reject, detachAbortListener };
15597
15880
  signal?.addEventListener("abort", onAbort, { once: true });
15598
15881
  const queue = this.bucketQueues.get(bucketId) ?? [];
15599
15882
  queue.push(entry);
@@ -16020,7 +16303,7 @@ class InMemorySpendLedger {
16020
16303
  }
16021
16304
 
16022
16305
  // src/execution/harness.ts
16023
- var DEFAULT_SLEEP = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
16306
+ var DEFAULT_SLEEP = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
16024
16307
  var DEFAULT_ATTEMPT_ADMISSION_TIMEOUT_MS = 30 * 60 * 1000;
16025
16308
  var DEFAULT_CREDENTIAL_PROJECTION_TIMEOUT_MS = 60000;
16026
16309
  async function projectCredentialWithBudget(broker, input, options) {
@@ -16074,11 +16357,11 @@ function cancellableSleep(ms, signal) {
16074
16357
  return Promise.resolve();
16075
16358
  if (signal?.aborted)
16076
16359
  return Promise.resolve();
16077
- return new Promise((resolve2) => {
16360
+ return new Promise((resolve) => {
16078
16361
  const onDone = () => {
16079
16362
  signal?.removeEventListener("abort", onAbort);
16080
16363
  clearTimeout(timer);
16081
- resolve2();
16364
+ resolve();
16082
16365
  };
16083
16366
  const timer = setTimeout(onDone, ms);
16084
16367
  const onAbort = () => onDone();
@@ -16549,8 +16832,8 @@ ${line}`;
16549
16832
  const lease = settlement.writeLease;
16550
16833
  const controller = new AbortController;
16551
16834
  let resolveSettled;
16552
- const settled = new Promise((resolve2) => {
16553
- resolveSettled = resolve2;
16835
+ const settled = new Promise((resolve) => {
16836
+ resolveSettled = resolve;
16554
16837
  });
16555
16838
  let fenceClosed = false;
16556
16839
  let outcome;
@@ -16630,20 +16913,20 @@ ${line}`;
16630
16913
  settled
16631
16914
  };
16632
16915
  let onCancel;
16633
- const cancelPromise = new Promise((resolve2) => {
16916
+ const cancelPromise = new Promise((resolve) => {
16634
16917
  const sig = this.cancelSignal;
16635
16918
  if (!sig)
16636
16919
  return;
16637
16920
  if (sig.aborted) {
16638
- resolve2("cancel");
16921
+ resolve("cancel");
16639
16922
  return;
16640
16923
  }
16641
- onCancel = () => resolve2("cancel");
16924
+ onCancel = () => resolve("cancel");
16642
16925
  sig.addEventListener("abort", onCancel, { once: true });
16643
16926
  });
16644
16927
  let watchdogTimer;
16645
- const watchdogPromise = harnessWatchdogMs !== undefined && harnessWatchdogMs > 0 ? new Promise((resolve2) => {
16646
- watchdogTimer = setTimeout(() => resolve2("watchdog"), harnessWatchdogMs);
16928
+ const watchdogPromise = harnessWatchdogMs !== undefined && harnessWatchdogMs > 0 ? new Promise((resolve) => {
16929
+ watchdogTimer = setTimeout(() => resolve("watchdog"), harnessWatchdogMs);
16647
16930
  }) : undefined;
16648
16931
  try {
16649
16932
  const racers = [
@@ -16663,31 +16946,31 @@ ${line}`;
16663
16946
  fenceClosed = true;
16664
16947
  sink.close();
16665
16948
  controller.abort();
16666
- const graceMs2 = deadlineMs + this.graceMarginMs;
16949
+ const graceMs = deadlineMs + this.graceMarginMs;
16667
16950
  await Promise.race([
16668
16951
  execGuarded,
16669
- new Promise((resolve2) => setTimeout(resolve2, graceMs2))
16952
+ new Promise((resolve) => setTimeout(resolve, graceMs))
16670
16953
  ]);
16671
- const transportTerminal2 = settlement.terminal;
16672
- let receipt2;
16673
- const cancellationSemantics2 = transport.cancellationSemantics ?? (transport.backend === "claude-code" ? "process-exit" : this.isTestFake ? transport.backend === "opencode" ? "provider-proof" : "process-exit" : undefined);
16674
- const isProviderProof2 = cancellationSemantics2 === "provider-proof";
16675
- if (transportTerminal2 !== undefined && transportTerminal2.origin !== "harness" && (!isProviderProof2 || transportTerminal2.proof !== undefined)) {
16676
- receipt2 = finalize(() => settlement.receipt("failed", {
16677
- confirmation: cancellationSemantics2 === "process-exit" ? "process_group_exited" : "sdk_abort_confirmed",
16678
- processGroupAlive: isProviderProof2 ? "not_applicable" : "unknown",
16954
+ const transportTerminal = settlement.terminal;
16955
+ let receipt;
16956
+ const cancellationSemantics = transport.cancellationSemantics ?? (transport.backend === "claude-code" ? "process-exit" : this.isTestFake ? transport.backend === "opencode" ? "provider-proof" : "process-exit" : undefined);
16957
+ const isProviderProof = cancellationSemantics === "provider-proof";
16958
+ if (transportTerminal !== undefined && transportTerminal.origin !== "harness" && (!isProviderProof || transportTerminal.proof !== undefined)) {
16959
+ receipt = finalize(() => settlement.receipt("failed", {
16960
+ confirmation: cancellationSemantics === "process-exit" ? "process_group_exited" : "sdk_abort_confirmed",
16961
+ processGroupAlive: isProviderProof ? "not_applicable" : "unknown",
16679
16962
  remoteStatus: "failed"
16680
16963
  }));
16681
16964
  } else {
16682
16965
  settlement.acceptTerminal("harness", "failed");
16683
- receipt2 = finalize(() => synthesizeUnconfirmed(settlement, {
16684
- processGroupAlive: isProviderProof2 ? "not_applicable" : "unknown",
16685
- outcome: isProviderProof2 ? "local_fenced_remote_unconfirmed" : undefined,
16966
+ receipt = finalize(() => synthesizeUnconfirmed(settlement, {
16967
+ processGroupAlive: isProviderProof ? "not_applicable" : "unknown",
16968
+ outcome: isProviderProof ? "local_fenced_remote_unconfirmed" : undefined,
16686
16969
  warning: `Step timed out after ${harnessWatchdogMs}ms (harness-owned watchdog)`
16687
16970
  }));
16688
16971
  }
16689
- await this.persistSettlement(step, session, receipt2);
16690
- this.onSessionSettled?.({ session, settlement, receipt: receipt2 });
16972
+ await this.persistSettlement(step, session, receipt);
16973
+ this.onSessionSettled?.({ session, settlement, receipt });
16691
16974
  return {
16692
16975
  session,
16693
16976
  settlement,
@@ -16703,19 +16986,19 @@ ${line}`;
16703
16986
  timedOut: true
16704
16987
  },
16705
16988
  cancelled: false,
16706
- receipt: receipt2
16989
+ receipt
16707
16990
  };
16708
16991
  }
16709
16992
  if (raced === "outcome") {
16710
16993
  const resolved = outcome;
16711
16994
  if (resolved === undefined) {
16712
16995
  sink.close();
16713
- const receipt3 = finalize(() => synthesizeUnconfirmed(settlement, {
16996
+ const receipt = finalize(() => synthesizeUnconfirmed(settlement, {
16714
16997
  warning: "transport promise settled without producing an outcome (\xA75.1 invariant conversion)"
16715
16998
  }));
16716
- await this.persistSettlement(step, session, receipt3);
16717
- this.onSessionSettled?.({ session, settlement, receipt: receipt3 });
16718
- return { session, settlement, cancelled: true, receipt: receipt3 };
16999
+ await this.persistSettlement(step, session, receipt);
17000
+ this.onSessionSettled?.({ session, settlement, receipt });
17001
+ return { session, settlement, cancelled: true, receipt };
16719
17002
  }
16720
17003
  settlement.acceptTerminal("transport", completionToStatus(resolved), resolved.terminalProof);
16721
17004
  if (resolved.terminalProof !== undefined) {
@@ -16731,32 +17014,32 @@ ${line}`;
16731
17014
  fenceClosed = true;
16732
17015
  sink.close();
16733
17016
  settlement.acceptTerminal("harness", "failed");
16734
- const receipt3 = finalize(() => synthesizeInternalFailure(settlement, error));
16735
- await this.persistSettlement(step, session, receipt3);
16736
- this.onSessionSettled?.({ session, settlement, receipt: receipt3 });
17017
+ const receipt = finalize(() => synthesizeInternalFailure(settlement, error));
17018
+ await this.persistSettlement(step, session, receipt);
17019
+ this.onSessionSettled?.({ session, settlement, receipt });
16737
17020
  return {
16738
17021
  session,
16739
17022
  settlement,
16740
17023
  outcome: resolved,
16741
17024
  cancelled: false,
16742
- receipt: receipt3
17025
+ receipt
16743
17026
  };
16744
17027
  }
16745
17028
  sink.close();
16746
- const receipt2 = finalize(() => settlement.receipt(resolved.completion === "success" ? "completed" : "failed", {
17029
+ const receipt = finalize(() => settlement.receipt(resolved.completion === "success" ? "completed" : "failed", {
16747
17030
  confirmation: resolved.terminalProof ? "process_group_exited" : "not_required",
16748
17031
  processGroupAlive: "unknown",
16749
17032
  remoteStatus: resolved.completion === "success" ? "completed" : "failed"
16750
17033
  }));
16751
- await this.persistSettlement(step, session, receipt2);
16752
- this.onSessionSettled?.({ session, settlement, receipt: receipt2 });
17034
+ await this.persistSettlement(step, session, receipt);
17035
+ this.onSessionSettled?.({ session, settlement, receipt });
16753
17036
  return {
16754
17037
  session,
16755
17038
  settlement,
16756
17039
  outcome: resolved,
16757
17040
  delivery,
16758
17041
  cancelled: false,
16759
- receipt: receipt2
17042
+ receipt
16760
17043
  };
16761
17044
  }
16762
17045
  settlement.markAbortRequested();
@@ -16770,7 +17053,7 @@ ${line}`;
16770
17053
  const graceMs = deadlineMs + this.graceMarginMs;
16771
17054
  await Promise.race([
16772
17055
  execGuarded,
16773
- new Promise((resolve2) => setTimeout(resolve2, graceMs))
17056
+ new Promise((resolve) => setTimeout(resolve, graceMs))
16774
17057
  ]);
16775
17058
  const transportTerminal = settlement.terminal;
16776
17059
  let receipt;
@@ -17129,10 +17412,10 @@ ${line}`;
17129
17412
  async finalizeReservation(reservation, result, transport) {
17130
17413
  const ledger = this.spendLedger;
17131
17414
  if (ledger === undefined) {
17132
- const usage2 = result.kind === "cancelled" ? undefined : result.outcome.usage;
17415
+ const usage = result.kind === "cancelled" ? undefined : result.outcome.usage;
17133
17416
  return {
17134
17417
  reservation,
17135
- decision: usage2 === undefined ? { kind: "unresolved", knownUsd: undefined } : settlementFromUsage(usage2)
17418
+ decision: usage === undefined ? { kind: "unresolved", knownUsd: undefined } : settlementFromUsage(usage)
17136
17419
  };
17137
17420
  }
17138
17421
  const idempotencyKey = `${reservation.reservationId}:finalize`;
@@ -17195,62 +17478,62 @@ ${line}`;
17195
17478
  transport,
17196
17479
  deadlineMs,
17197
17480
  harnessWatchdogMs,
17198
- onData: async (outcome2, settlement) => {
17199
- if (outcome2.completion === "failed" && outcome2.failureCause !== undefined) {
17200
- const resolution2 = resolveFailureCause({
17201
- outcome: outcome2,
17481
+ onData: async (outcome, settlement) => {
17482
+ if (outcome.completion === "failed" && outcome.failureCause !== undefined) {
17483
+ const resolution = resolveFailureCause({
17484
+ outcome,
17202
17485
  classifyFailure: transport.classifyFailure,
17203
17486
  parseThrew: false
17204
17487
  });
17205
- const classification = legacyClassificationFromCause(resolution2);
17206
- await this.guardedDataPlaneWrite(settlement, () => writeAttemptLog(step, attempt, kind, outcome2, classification, resolution2.kind === "cause" ? resolution2.cause : "legacy_terminal")).catch(() => {});
17488
+ const classification = legacyClassificationFromCause(resolution);
17489
+ await this.guardedDataPlaneWrite(settlement, () => writeAttemptLog(step, attempt, kind, outcome, classification, resolution.kind === "cause" ? resolution.cause : "legacy_terminal")).catch(() => {});
17207
17490
  if (classification === "transient") {
17208
17491
  await this.guardedDataPlaneWrite(settlement, () => Bun.file(step.outPath).unlink().then(() => {}).catch(() => {}));
17209
17492
  }
17210
- return { delivered: false, resolution: resolution2 };
17493
+ return { delivered: false, resolution };
17211
17494
  }
17212
- let parseError2;
17495
+ let parseError;
17213
17496
  try {
17214
17497
  let parsed;
17215
17498
  try {
17216
- parsed = step.parse(outcome2.finalText);
17499
+ parsed = step.parse(outcome.finalText);
17217
17500
  } catch (parseFailure) {
17218
- parseError2 = parseFailure instanceof Error ? parseFailure.message : String(parseFailure);
17501
+ parseError = parseFailure instanceof Error ? parseFailure.message : String(parseFailure);
17219
17502
  throw parseFailure;
17220
17503
  }
17221
17504
  if (isVacuousHunt({
17222
17505
  tools: step.tools,
17223
- toolInvocations: outcome2.toolInvocations,
17506
+ toolInvocations: outcome.toolInvocations,
17224
17507
  parsed
17225
17508
  })) {
17226
- await this.guardedDataPlaneWrite(settlement, () => writeAttemptLog(step, attempt, kind, outcome2, "terminal", "legacy_terminal")).catch(() => {});
17509
+ await this.guardedDataPlaneWrite(settlement, () => writeAttemptLog(step, attempt, kind, outcome, "terminal", "legacy_terminal")).catch(() => {});
17227
17510
  return {
17228
17511
  delivered: false,
17229
17512
  resolution: { kind: "legacy_terminal" }
17230
17513
  };
17231
17514
  }
17232
17515
  await this.guardedDataPlaneWrite(settlement, () => writeJsonAtomically(step.outPath, parsed));
17233
- await this.guardedDataPlaneWrite(settlement, () => writeAttemptLog(step, attempt, kind, outcome2, "ok"));
17516
+ await this.guardedDataPlaneWrite(settlement, () => writeAttemptLog(step, attempt, kind, outcome, "ok"));
17234
17517
  return { delivered: true, parsed };
17235
17518
  } catch (failure) {
17236
- const resolution2 = parseError2 !== undefined ? resolveFailureCause({
17237
- outcome: outcome2,
17519
+ const resolution = parseError !== undefined ? resolveFailureCause({
17520
+ outcome,
17238
17521
  classifyFailure: transport.classifyFailure,
17239
17522
  parseThrew: true
17240
17523
  }) : { kind: "legacy_terminal" };
17241
- const rejection = parseError2 !== undefined ? { label: "parse_error", message: parseError2 } : {
17524
+ const rejection = parseError !== undefined ? { label: "parse_error", message: parseError } : {
17242
17525
  label: "persist_error",
17243
17526
  message: failure instanceof Error ? failure.message : String(failure)
17244
17527
  };
17245
- const classification = legacyClassificationFromCause(resolution2);
17246
- await this.guardedDataPlaneWrite(settlement, () => writeAttemptLog(step, attempt, kind, outcome2, classification, resolution2.kind === "cause" ? resolution2.cause : "legacy_terminal", rejection)).catch(() => {});
17528
+ const classification = legacyClassificationFromCause(resolution);
17529
+ await this.guardedDataPlaneWrite(settlement, () => writeAttemptLog(step, attempt, kind, outcome, classification, resolution.kind === "cause" ? resolution.cause : "legacy_terminal", rejection)).catch(() => {});
17247
17530
  if (classification === "transient") {
17248
17531
  await this.guardedDataPlaneWrite(settlement, () => Bun.file(step.outPath).unlink().then(() => {}).catch(() => {}));
17249
17532
  }
17250
17533
  return {
17251
17534
  delivered: false,
17252
- resolution: resolution2,
17253
- ...parseError2 === undefined ? {} : { parseError: parseError2 }
17535
+ resolution,
17536
+ ...parseError === undefined ? {} : { parseError }
17254
17537
  };
17255
17538
  }
17256
17539
  }
@@ -17262,8 +17545,8 @@ ${line}`;
17262
17545
  ...execution,
17263
17546
  frozenIdentity
17264
17547
  }).catch(() => {}),
17265
- new Promise((resolve2) => {
17266
- evidenceTimer = setTimeout(resolve2, Math.min(100, Math.max(1, step.timeoutMs)));
17548
+ new Promise((resolve) => {
17549
+ evidenceTimer = setTimeout(resolve, Math.min(100, Math.max(1, step.timeoutMs)));
17267
17550
  })
17268
17551
  ]);
17269
17552
  } finally {
@@ -17302,10 +17585,12 @@ function completionToStatus(outcome) {
17302
17585
  }
17303
17586
 
17304
17587
  // src/review/pipeline.ts
17588
+ init_evidence_redaction();
17305
17589
  init_redact();
17306
17590
  init_preflight2();
17307
17591
 
17308
17592
  // src/review/scout.ts
17593
+ init_boundary();
17309
17594
  var SCOUT_OUTPUT_CONTRACT = [
17310
17595
  "Your final message must be exactly one JSON object \u2014 no prose, no code",
17311
17596
  "fences \u2014 of the shape",
@@ -17709,12 +17994,12 @@ async function runPipeline(input, deps) {
17709
17994
  const execSettled = execute(input, legDeps, state).then((value) => ({ ok: true, value }), (error) => ({ ok: false, error }));
17710
17995
  let timer;
17711
17996
  let graceTimer;
17712
- const ceiling = new Promise((resolve2) => {
17997
+ const ceiling = new Promise((resolve) => {
17713
17998
  timer = setTimeout(() => {
17714
17999
  state.partial = true;
17715
18000
  state.ceilingFired = true;
17716
18001
  controller.abort();
17717
- resolve2(CEILING_FIRED);
18002
+ resolve(CEILING_FIRED);
17718
18003
  }, input.pipelineTimeoutMs ?? DEFAULT_PIPELINE_TIMEOUT_MS);
17719
18004
  });
17720
18005
  try {
@@ -17726,8 +18011,8 @@ async function runPipeline(input, deps) {
17726
18011
  }
17727
18012
  await Promise.race([
17728
18013
  execSettled,
17729
- new Promise((resolve2) => {
17730
- graceTimer = setTimeout(resolve2, graceMs);
18014
+ new Promise((resolve) => {
18015
+ graceTimer = setTimeout(resolve, graceMs);
17731
18016
  })
17732
18017
  ]);
17733
18018
  return await finish(input, state);
@@ -17839,7 +18124,8 @@ async function execute(input, deps, state) {
17839
18124
  frontmatterModel: consolidateFrontmatter,
17840
18125
  defaultModel: DEFAULT_CONSOLIDATE_MODEL
17841
18126
  }
17842
- }
18127
+ },
18128
+ ...input.materiality === undefined ? {} : { materiality: true }
17843
18129
  });
17844
18130
  } catch (error) {
17845
18131
  if (effectiveRoutingConfig !== undefined)
@@ -18291,6 +18577,10 @@ ${SHARED_PREFIX_CLOSING}` : sharedBlock,
18291
18577
  await runConsolidation(input, deps, state, stepsDir, boundaryNonce);
18292
18578
  }
18293
18579
  state.consolidation ??= skippedConsolidation(input);
18580
+ if (input.materiality !== undefined && !ceilingAborted(deps, state)) {
18581
+ await runMaterialityJudge(input, deps, state, stepsDir, boundaryNonce);
18582
+ }
18583
+ state.materiality ??= skippedMateriality(input, state);
18294
18584
  return finish(input, state);
18295
18585
  }
18296
18586
  async function runRefuter(input, deps, state, batch, options) {
@@ -18658,7 +18948,7 @@ async function runScout(input, deps, state, patch, stepsDir, nonce) {
18658
18948
  outPath,
18659
18949
  status: "unsettled"
18660
18950
  };
18661
- const record2 = {
18951
+ const record = {
18662
18952
  enabled: true,
18663
18953
  model: meta.model,
18664
18954
  status: "failed",
@@ -18667,7 +18957,7 @@ async function runScout(input, deps, state, patch, stepsDir, nonce) {
18667
18957
  why_truncated: 0,
18668
18958
  duration_ms: 0
18669
18959
  };
18670
- state.scout = record2;
18960
+ state.scout = record;
18671
18961
  const startedAt = Date.now();
18672
18962
  const abandon = (error) => {
18673
18963
  if ((meta.attempts === undefined || meta.attempts < 1) && meta.failure === undefined) {
@@ -18676,11 +18966,11 @@ async function runScout(input, deps, state, patch, stepsDir, nonce) {
18676
18966
  meta.status = "failed";
18677
18967
  }
18678
18968
  state.perAgent.scout ??= failedAgentEntry();
18679
- record2.duration_ms = Date.now() - startedAt;
18969
+ record.duration_ms = Date.now() - startedAt;
18680
18970
  emit(deps, {
18681
18971
  kind: "scout-finished",
18682
18972
  ok: false,
18683
- durationMs: record2.duration_ms
18973
+ durationMs: record.duration_ms
18684
18974
  });
18685
18975
  return "";
18686
18976
  };
@@ -18690,9 +18980,9 @@ async function runScout(input, deps, state, patch, stepsDir, nonce) {
18690
18980
  const agent = parseAgentSource(raw);
18691
18981
  await writeSystemPrompt(systemPromptPath, agent.body);
18692
18982
  meta.model = resolveModel(input, input.scout.model, agent.model ?? DEFAULT_SCOUT_MODEL, input.scout.promptPath);
18693
- record2.model = meta.model;
18983
+ record.model = meta.model;
18694
18984
  meta.effort = resolveEffort(agent.effort, "scout");
18695
- record2.prompt_sha256 = new Bun.CryptoHasher("sha256").update(raw).digest("hex");
18985
+ record.prompt_sha256 = new Bun.CryptoHasher("sha256").update(raw).digest("hex");
18696
18986
  spec = {
18697
18987
  name,
18698
18988
  systemPromptPath,
@@ -18724,7 +19014,7 @@ async function runScout(input, deps, state, patch, stepsDir, nonce) {
18724
19014
  meta.effort_applied = spec.route.backend === "claude-code";
18725
19015
  const routedModel = effectiveExecutionModel(spec);
18726
19016
  meta.model = routedModel;
18727
- record2.model = routedModel;
19017
+ record.model = routedModel;
18728
19018
  }
18729
19019
  state.steps.push(meta);
18730
19020
  emit(deps, { kind: "scout-started", model: meta.model });
@@ -18745,15 +19035,15 @@ async function runScout(input, deps, state, patch, stepsDir, nonce) {
18745
19035
  if (blockForgesNonce(block, nonce))
18746
19036
  return abandon();
18747
19037
  meta.status = "ok";
18748
- record2.status = "ok";
18749
- record2.leads_count = capped.leads.length;
18750
- record2.leads_truncated = capped.dropped;
18751
- record2.why_truncated = capped.whyTruncated;
18752
- record2.duration_ms = Date.now() - startedAt;
19038
+ record.status = "ok";
19039
+ record.leads_count = capped.leads.length;
19040
+ record.leads_truncated = capped.dropped;
19041
+ record.why_truncated = capped.whyTruncated;
19042
+ record.duration_ms = Date.now() - startedAt;
18753
19043
  emit(deps, {
18754
19044
  kind: "scout-finished",
18755
19045
  ok: true,
18756
- durationMs: record2.duration_ms,
19046
+ durationMs: record.duration_ms,
18757
19047
  leads: capped.leads.length
18758
19048
  });
18759
19049
  return renderLeadsBlock(capped.leads);
@@ -18804,14 +19094,14 @@ async function runConsolidation(input, deps, state, stepsDir, nonce) {
18804
19094
  };
18805
19095
  return;
18806
19096
  }
18807
- const record2 = {
19097
+ const record = {
18808
19098
  enabled: true,
18809
19099
  status: "passthrough",
18810
19100
  findings_in: posted.length,
18811
19101
  findings_out: posted.length,
18812
19102
  duration_ms: 0
18813
19103
  };
18814
- state.consolidation = record2;
19104
+ state.consolidation = record;
18815
19105
  if (posted.length === 0)
18816
19106
  return;
18817
19107
  let prompt;
@@ -18819,11 +19109,11 @@ async function runConsolidation(input, deps, state, stepsDir, nonce) {
18819
19109
  prompt = consolidationPrompt(posted, nonce);
18820
19110
  } catch (error) {
18821
19111
  if (error instanceof BoundaryNonceError) {
18822
- record2.reason = "nonce";
19112
+ record.reason = "nonce";
18823
19113
  return;
18824
19114
  }
18825
- record2.status = "failed";
18826
- record2.reason = "prompt could not be composed";
19115
+ record.status = "failed";
19116
+ record.reason = "prompt could not be composed";
18827
19117
  return;
18828
19118
  }
18829
19119
  const name = "consolidate";
@@ -18838,7 +19128,7 @@ async function runConsolidation(input, deps, state, stepsDir, nonce) {
18838
19128
  outPath,
18839
19129
  status: "unsettled"
18840
19130
  };
18841
- record2.status = "failed";
19131
+ record.status = "failed";
18842
19132
  const startedAt = Date.now();
18843
19133
  const abandon = (reason, error) => {
18844
19134
  if ((meta.attempts === undefined || meta.attempts < 1) && meta.failure === undefined) {
@@ -18847,10 +19137,10 @@ async function runConsolidation(input, deps, state, stepsDir, nonce) {
18847
19137
  meta.status = "failed";
18848
19138
  }
18849
19139
  state.perAgent.consolidate ??= failedAgentEntry();
18850
- record2.status = "failed";
18851
- record2.reason = reason;
18852
- record2.findings_out = posted.length;
18853
- record2.duration_ms = Date.now() - startedAt;
19140
+ record.status = "failed";
19141
+ record.reason = reason;
19142
+ record.findings_out = posted.length;
19143
+ record.duration_ms = Date.now() - startedAt;
18854
19144
  };
18855
19145
  let spec;
18856
19146
  try {
@@ -18858,9 +19148,9 @@ async function runConsolidation(input, deps, state, stepsDir, nonce) {
18858
19148
  const agent = parseAgentSource(raw);
18859
19149
  await writeSystemPrompt(systemPromptPath, agent.body);
18860
19150
  meta.model = resolveModel(input, input.consolidate.model, agent.model ?? DEFAULT_CONSOLIDATE_MODEL, input.consolidate.promptPath);
18861
- record2.model = meta.model;
19151
+ record.model = meta.model;
18862
19152
  meta.effort = agent.effort ?? DEFAULT_CONSOLIDATE_EFFORT;
18863
- record2.prompt_sha256 = new Bun.CryptoHasher("sha256").update(raw).digest("hex");
19153
+ record.prompt_sha256 = new Bun.CryptoHasher("sha256").update(raw).digest("hex");
18864
19154
  spec = {
18865
19155
  name,
18866
19156
  systemPromptPath,
@@ -18893,7 +19183,7 @@ async function runConsolidation(input, deps, state, stepsDir, nonce) {
18893
19183
  meta.effort_applied = spec.route.backend === "claude-code";
18894
19184
  const routedModel = effectiveExecutionModel(spec);
18895
19185
  meta.model = routedModel;
18896
- record2.model = routedModel;
19186
+ record.model = routedModel;
18897
19187
  }
18898
19188
  state.steps.push(meta);
18899
19189
  let result;
@@ -18914,19 +19204,197 @@ async function runConsolidation(input, deps, state, stepsDir, nonce) {
18914
19204
  const plan = result.output;
18915
19205
  state.consolidationPlan = plan;
18916
19206
  meta.status = "ok";
18917
- record2.status = "ok";
18918
- record2.findings_out = plan.length;
18919
- record2.duration_ms = Date.now() - startedAt;
19207
+ record.status = "ok";
19208
+ record.findings_out = plan.length;
19209
+ record.duration_ms = Date.now() - startedAt;
19210
+ }
19211
+ var MATERIALITY_TIMEOUT_MS = 3 * 60 * 1000;
19212
+ var MATERIALITY_MAX_ATTEMPTS = 2;
19213
+ var MATERIALITY_AGENT = "materiality";
19214
+ var MATERIALITY_TITLE_FALLBACK = "(title unavailable)";
19215
+ var MATERIALITY_MAX_FILE_BYTES = 1024 * 1024;
19216
+ function skippedMateriality(input, state) {
19217
+ const enabled = input.materiality !== undefined;
19218
+ return {
19219
+ enabled,
19220
+ status: enabled && state.ceilingFired ? "ceiling" : "skipped",
19221
+ judged: 0,
19222
+ demoted: 0,
19223
+ protected: 0,
19224
+ failed: 0,
19225
+ skipped_unsafe: 0,
19226
+ duration_ms: 0
19227
+ };
18920
19228
  }
18921
- async function finish(input, state) {
19229
+ async function materialityWindow(worktree, relPath, line) {
19230
+ if (path23.isAbsolute(relPath))
19231
+ return null;
19232
+ try {
19233
+ const root = await realpath4(worktree);
19234
+ const target = await realpath4(path23.join(root, relPath));
19235
+ const rel = path23.relative(root, target);
19236
+ if (rel === "" || rel === ".." || rel.startsWith(`..${path23.sep}`) || path23.isAbsolute(rel)) {
19237
+ return null;
19238
+ }
19239
+ const file = Bun.file(target);
19240
+ if (file.size > MATERIALITY_MAX_FILE_BYTES)
19241
+ return null;
19242
+ return codeWindow(await file.text(), line);
19243
+ } catch {
19244
+ return null;
19245
+ }
19246
+ }
19247
+ async function runMaterialityJudge(input, deps, state, stepsDir, nonce) {
19248
+ if (!input.materiality) {
19249
+ state.materiality = skippedMateriality(input, state);
19250
+ return;
19251
+ }
19252
+ const startedAt = Date.now();
19253
+ const record = {
19254
+ enabled: true,
19255
+ status: "ran",
19256
+ judged: 0,
19257
+ demoted: 0,
19258
+ protected: 0,
19259
+ failed: 0,
19260
+ skipped_unsafe: 0,
19261
+ model: MATERIALITY_JUDGE_MODEL,
19262
+ duration_ms: 0
19263
+ };
19264
+ state.materiality = record;
18922
19265
  if (!state.survivors) {
18923
- const { survivors, deduped: deduped2 } = mergeAndDedupe(state.drafts);
19266
+ const { survivors, deduped } = mergeAndDedupe(state.drafts);
18924
19267
  state.survivors = survivors;
18925
- state.deduped = deduped2;
19268
+ state.deduped = deduped;
19269
+ }
19270
+ const tiered = tierFindings(state, state.survivors);
19271
+ const { judge, protectedCount } = materialityCandidates(tiered.findings, tiered.protectedIds);
19272
+ record.protected = protectedCount;
19273
+ let route;
19274
+ if (state.routePlan !== undefined) {
19275
+ route = routeForStepKey(state.routePlan, MATERIALITY_STEP_KEY);
19276
+ if (route === undefined || !isMeasuredJudgeRoute(route)) {
19277
+ record.status = "unsupported_route";
19278
+ 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";
19279
+ return;
19280
+ }
19281
+ }
19282
+ if (judge.length === 0)
19283
+ return;
19284
+ const deadline = state.ceilingDeadlineMs;
19285
+ if (deadline !== undefined) {
19286
+ const perWaveMs = MATERIALITY_TIMEOUT_MS * (MATERIALITY_MAX_ATTEMPTS + 1);
19287
+ const budgetMs = deadline - Date.now() - (state.ceilingGraceMs ?? ceilingGraceMs(input));
19288
+ const waves = Math.floor(budgetMs / perWaveMs);
19289
+ if (waves < 1) {
19290
+ record.status = "ceiling";
19291
+ record.reason = "ceiling budget";
19292
+ return;
19293
+ }
19294
+ const cap = input.config?.effective.max_concurrent_steps;
19295
+ if (cap !== undefined && judge.length > waves * cap) {
19296
+ record.reason = `ceiling budget: judged ${waves * cap} of ${judge.length}`;
19297
+ judge.splice(waves * cap);
19298
+ }
19299
+ }
19300
+ const systemPromptPath = path23.join(stepsDir, "materiality.system.md");
19301
+ const mcpConfigPath = path23.join(stepsDir, "materiality.mcp.json");
19302
+ try {
19303
+ const raw = await Bun.file(input.materiality.promptPath).text();
19304
+ const agent = parseAgentSource(raw);
19305
+ record.prompt_sha256 = new Bun.CryptoHasher("sha256").update(raw).digest("hex");
19306
+ await writeSystemPrompt(systemPromptPath, agent.body);
19307
+ await Bun.write(mcpConfigPath, JSON.stringify({ mcpServers: {} }));
19308
+ await chmod(mcpConfigPath, 384);
19309
+ } catch {
19310
+ record.failed = judge.length;
19311
+ record.reason = "prompt file unreadable";
19312
+ record.duration_ms = Date.now() - startedAt;
19313
+ return;
19314
+ }
19315
+ const prTitle = input.prTitle !== undefined && input.prTitle.trim() !== "" ? input.prTitle : MATERIALITY_TITLE_FALLBACK;
19316
+ const effort = defaultEffortForRole("other");
19317
+ const specs = [];
19318
+ for (const finding of judge) {
19319
+ const prompt = renderMaterialityPrompt({
19320
+ prTitle,
19321
+ claim: finding.claim,
19322
+ path: finding.path,
19323
+ window: await materialityWindow(input.worktree, finding.path, finding.line)
19324
+ }, nonce);
19325
+ if (prompt === null) {
19326
+ record.skipped_unsafe++;
19327
+ continue;
19328
+ }
19329
+ const dir = path23.join(stepsDir, "materiality", finding.id);
19330
+ await mkdir7(dir, { recursive: true });
19331
+ const spec = {
19332
+ name: `materiality-${finding.id}`,
19333
+ systemPromptPath,
19334
+ prompt,
19335
+ tools: [],
19336
+ mcpConfigPath,
19337
+ model: MATERIALITY_JUDGE_MODEL,
19338
+ effort,
19339
+ cwd: input.worktree,
19340
+ outPath: path23.join(dir, "result.json"),
19341
+ timeoutMs: MATERIALITY_TIMEOUT_MS,
19342
+ maxAttempts: MATERIALITY_MAX_ATTEMPTS,
19343
+ ...route === undefined ? {} : { route },
19344
+ parse: parseJudgeVerdict,
19345
+ onRetry: (info) => emit(deps, { kind: "step-retry", ...info })
19346
+ };
19347
+ specs.push({ id: finding.id, spec, meta: stepMeta(spec) });
19348
+ }
19349
+ record.judged = specs.length;
19350
+ if (specs.length === 0) {
19351
+ record.duration_ms = Date.now() - startedAt;
19352
+ return;
19353
+ }
19354
+ for (const { meta } of specs)
19355
+ state.steps.push(meta);
19356
+ const settled = await Promise.allSettled(specs.map(({ spec }) => deps.runner.run(spec)));
19357
+ const verdicts = new Map;
19358
+ let usage;
19359
+ let attempts = 0;
19360
+ for (const [i, entry] of specs.entries()) {
19361
+ const outcome = settled[i];
19362
+ const result = outcome?.status === "fulfilled" ? outcome.value : undefined;
19363
+ if (result) {
19364
+ usage = usage ? sumUsage(usage, result.usage) : result.usage;
19365
+ attempts += result.attempts;
19366
+ recordSettlement(entry.meta, result, input.runDir);
19367
+ state.usageTotal = sumUsage(state.usageTotal, result.usage);
19368
+ accumulateUsageV2(state, result);
19369
+ } else {
19370
+ recordStepFailure(entry.meta, outcome?.status === "rejected" ? outcome.reason : "materiality step produced no result");
19371
+ }
19372
+ if (result?.status === "ok") {
19373
+ const verdict = result.output;
19374
+ verdicts.set(entry.id, verdict);
19375
+ if (verdict.label === "immaterial")
19376
+ record.demoted++;
19377
+ continue;
19378
+ }
19379
+ record.failed++;
18926
19380
  }
18927
- let findings = [];
19381
+ state.perAgent[MATERIALITY_AGENT] = usage ? {
19382
+ tokens_total: usage.tokens_total,
19383
+ duration_ms: Date.now() - startedAt,
19384
+ tokens_in: usage.tokens_in,
19385
+ tokens_out: usage.tokens_out,
19386
+ cost_usd_est: usage.cost_usd_est,
19387
+ attempts,
19388
+ status: record.failed > 0 ? "failed" : "ok",
19389
+ ...record.failed > 0 ? firstFailureDetail(settled) : {}
19390
+ } : failedAgentEntry();
19391
+ state.materialityVerdicts = verdicts;
19392
+ record.duration_ms = Date.now() - startedAt;
19393
+ }
19394
+ function tierFindings(state, survivors) {
19395
+ const findings = [];
18928
19396
  const refuted = [];
18929
- for (const survivor of state.survivors) {
19397
+ for (const survivor of survivors) {
18930
19398
  const verdict = state.verdicts.get(survivor.id) ?? "not_submitted";
18931
19399
  if (verdict === "refuted") {
18932
19400
  refuted.push({ ...survivor, refuter_verdict: "refuted" });
@@ -18938,37 +19406,81 @@ async function finish(input, state) {
18938
19406
  tier: deriveTier({
18939
19407
  severity: survivor.severity,
18940
19408
  evidence_class: survivor.evidence_class,
18941
- refuter_verdict: verdict
19409
+ refuter_verdict: verdict,
19410
+ causal_disposition: survivor.causal_disposition,
19411
+ claim: survivor.claim,
19412
+ path: survivor.path
18942
19413
  }, { refuterCutShort: state.ceilingFired && state.refuterConfigured })
18943
19414
  });
18944
19415
  }
19416
+ const tieredCount = findings.length;
19417
+ const protectedIds = new Set(findings.filter((f) => isSafetyProtected(f)).map((f) => f.id));
19418
+ if (state.consolidationPlan === undefined) {
19419
+ return {
19420
+ findings,
19421
+ tieredCount,
19422
+ refuted,
19423
+ protectedIds,
19424
+ consolidation: { kind: "none" }
19425
+ };
19426
+ }
19427
+ let plan;
19428
+ try {
19429
+ plan = validatePlan({ findings: state.consolidationPlan }, findings.map((f) => f.id), new Set);
19430
+ } catch {
19431
+ plan = undefined;
19432
+ }
19433
+ if (plan === undefined) {
19434
+ return {
19435
+ findings,
19436
+ tieredCount,
19437
+ refuted,
19438
+ protectedIds,
19439
+ consolidation: { kind: "mismatch" }
19440
+ };
19441
+ }
19442
+ const stats = { repairs: 0 };
19443
+ plan = enforcePlanInvariants(plan, findings, stats);
19444
+ for (const entry of plan) {
19445
+ if (entry.sources.some((id) => protectedIds.has(id))) {
19446
+ protectedIds.add(entry.primary);
19447
+ }
19448
+ }
19449
+ return {
19450
+ findings: applyPlan(findings, plan, []),
19451
+ tieredCount,
19452
+ refuted,
19453
+ protectedIds,
19454
+ consolidation: {
19455
+ kind: "applied",
19456
+ repairs: stats.repairs,
19457
+ findingsOut: plan.length
19458
+ }
19459
+ };
19460
+ }
19461
+ async function finish(input, state) {
19462
+ if (!state.survivors) {
19463
+ const { survivors, deduped } = mergeAndDedupe(state.drafts);
19464
+ state.survivors = survivors;
19465
+ state.deduped = deduped;
19466
+ }
19467
+ const tiered = tierFindings(state, state.survivors);
19468
+ const refuted = tiered.refuted;
18945
19469
  const deduped = (state.deduped ?? []).map((loser) => ({
18946
19470
  ...loser,
18947
19471
  refuter_verdict: "not_submitted"
18948
19472
  }));
18949
- if (state.consolidationPlan !== undefined) {
18950
- let plan;
18951
- try {
18952
- plan = validatePlan({ findings: state.consolidationPlan }, findings.map((f) => f.id), new Set);
18953
- } catch {
18954
- plan = undefined;
18955
- }
18956
- if (plan === undefined) {
18957
- if (state.consolidation !== undefined) {
18958
- state.consolidation.status = "failed";
18959
- state.consolidation.reason = "plan no longer matches findings";
18960
- state.consolidation.findings_out = findings.length;
18961
- }
18962
- } else {
18963
- const stats = { repairs: 0 };
18964
- plan = enforcePlanInvariants(plan, findings, stats);
18965
- if (state.consolidation !== undefined) {
18966
- state.consolidation.plan_repairs = stats.repairs;
18967
- state.consolidation.findings_out = plan.length;
18968
- }
18969
- findings = applyPlan(findings, plan, []);
19473
+ if (state.consolidation !== undefined) {
19474
+ if (tiered.consolidation.kind === "mismatch") {
19475
+ state.consolidation.status = "failed";
19476
+ state.consolidation.reason = "plan no longer matches findings";
19477
+ state.consolidation.findings_out = tiered.tieredCount;
19478
+ } else if (tiered.consolidation.kind === "applied") {
19479
+ state.consolidation.plan_repairs = tiered.consolidation.repairs;
19480
+ state.consolidation.findings_out = tiered.consolidation.findingsOut;
18970
19481
  }
18971
19482
  }
19483
+ const findings = state.materialityVerdicts === undefined ? tiered.findings : applyMaterialityVerdicts(tiered.findings, state.materialityVerdicts, tiered.protectedIds);
18972
19484
  state.consolidation ??= skippedConsolidation(input);
18973
19485
  const rootCauses = clusterByRootCause(findings);
18974
19486
  const rootCauseId = rootCauseIdByFinding(rootCauses);
@@ -18989,6 +19501,7 @@ async function finish(input, state) {
18989
19501
  run_status: state.partial ? "partial" : "complete",
18990
19502
  ...state.summary === undefined ? {} : { summary: state.summary }
18991
19503
  };
19504
+ state.finalFindings = clustered;
18992
19505
  await writePipelinePlan(input, state);
18993
19506
  return {
18994
19507
  skillOutput,
@@ -19075,6 +19588,7 @@ async function writePipelinePlan(input, state) {
19075
19588
  ...state.boundaryNonce === undefined ? {} : { boundary_nonce: state.boundaryNonce },
19076
19589
  ...state.scout === undefined ? {} : { scout: state.scout },
19077
19590
  ...state.consolidation === undefined ? {} : { consolidation: state.consolidation },
19591
+ materiality: state.materiality ?? skippedMateriality(input, state),
19078
19592
  ...input.sharedPrefix === true ? { shared_prefix: true } : {},
19079
19593
  ...state.diversity === undefined ? {} : {
19080
19594
  multiModelDiversity: buildDiversityPipelineRecord(state.diversity, state.partial)
@@ -19097,11 +19611,12 @@ function fillRereviewProvenance(input, state) {
19097
19611
  }
19098
19612
  const assembled = input.phaseB === undefined ? {
19099
19613
  live: base.live,
19100
- gateRows: base.live.map((row2) => ({
19101
- id: row2.id,
19102
- tier: row2.tier,
19103
- locs: row2.locs,
19104
- status: row2.status
19614
+ gateRows: base.live.map((row) => ({
19615
+ id: row.id,
19616
+ tier: row.tier,
19617
+ locs: row.locs,
19618
+ status: row.status,
19619
+ claim: row.claim
19105
19620
  })),
19106
19621
  verifiedGone: base.resolved_verified ?? 0,
19107
19622
  verifiedGoneIds: base.resolved_ids ?? [],
@@ -19113,6 +19628,7 @@ function fillRereviewProvenance(input, state) {
19113
19628
  verifyVerdicts: state.verifyVerdicts
19114
19629
  });
19115
19630
  state.gatePriors = assembled.gateRows;
19631
+ const released = materialityReleasedIds(state.finalFindings ?? [], assembled.gateRows);
19116
19632
  const filled = {
19117
19633
  ...base,
19118
19634
  verified: state.verificationSpawned,
@@ -19123,7 +19639,8 @@ function fillRereviewProvenance(input, state) {
19123
19639
  resolved_ids: assembled.verifiedGoneIds,
19124
19640
  returned: assembled.returned,
19125
19641
  re_tiered: assembled.reTiered,
19126
- ...state.worsenedHits.length > 0 ? { worsened: state.worsenedHits } : {}
19642
+ ...state.worsenedHits.length > 0 ? { worsened: state.worsenedHits } : {},
19643
+ ...released.length > 0 ? { materiality_released_ids: released } : {}
19127
19644
  };
19128
19645
  Object.assign(base, filled);
19129
19646
  return filled;
@@ -19248,6 +19765,7 @@ init_preflight2();
19248
19765
 
19249
19766
  // src/review/report.ts
19250
19767
  init_preflight3();
19768
+ init_findings();
19251
19769
  init_brand();
19252
19770
  var USD_PER_AGENT_BASE = 1.2;
19253
19771
  var USD_PER_CHANGED_LINE = 0.00021;
@@ -19353,7 +19871,7 @@ function asRecoveredSeverity(sev) {
19353
19871
  }
19354
19872
  }
19355
19873
  function rereviewDeltaFromProvenance(rereview, newFindings) {
19356
- const count = (status) => rereview.live.filter((row2) => row2.status === status).length;
19874
+ const count = (status) => rereview.live.filter((row) => row.status === status).length;
19357
19875
  return {
19358
19876
  verifiedGone: rereview.resolved_verified ?? 0,
19359
19877
  unconfirmed: count("unconfirmed"),
@@ -19363,12 +19881,12 @@ function rereviewDeltaFromProvenance(rereview, newFindings) {
19363
19881
  suppressed: count("suppressed"),
19364
19882
  returned: rereview.returned ?? 0,
19365
19883
  reTiered: rereview.re_tiered ?? 0,
19366
- live: rereview.live.map((row2) => ({
19367
- id: row2.id ?? "",
19368
- sev: asRecoveredSeverity(row2.sev),
19369
- status: row2.status,
19370
- locs: row2.locs ?? [],
19371
- claim: row2.claim ?? ""
19884
+ live: rereview.live.map((row) => ({
19885
+ id: row.id ?? "",
19886
+ sev: asRecoveredSeverity(row.sev),
19887
+ status: row.status,
19888
+ locs: row.locs ?? [],
19889
+ claim: row.claim ?? ""
19372
19890
  })),
19373
19891
  capped: rereview.verification_capped ?? 0,
19374
19892
  ...rereview.case === undefined ? {} : { case: rereview.case },
@@ -19439,13 +19957,13 @@ function findingIndexLines(findings, commentUrlByFindingId) {
19439
19957
  return `${scanAidEmoji(f)} ${locRef} \u2014 ${leadIn(f.claim)}`;
19440
19958
  });
19441
19959
  }
19442
- function renderPrComment(doc, repoWebUrl, delta, outsideDiffFindings, movedHeadSha, commentUrlByFindingId, ciMode = "advisory", compactFrom) {
19960
+ function renderPrComment(doc, repoWebUrl, delta, outsideDiffFindings, movedHeadSha, commentUrlByFindingId, ciMode = "advisory", compactFrom, notPosted) {
19443
19961
  const webUrl = repoWebUrl?.endsWith("/") ? repoWebUrl.slice(0, -1) : repoWebUrl;
19444
19962
  const liveRows = delta?.rereview?.live ?? [];
19445
- const liveForHeadline = liveRows.filter((row2) => row2.status !== "suppressed");
19963
+ const liveForHeadline = liveRows.filter((row) => row.status !== "suppressed");
19446
19964
  const headlineSev = [
19447
19965
  ...doc.findings.map((f) => f.severity),
19448
- ...liveForHeadline.map((row2) => row2.sev)
19966
+ ...liveForHeadline.map((row) => row.sev)
19449
19967
  ];
19450
19968
  const critical = headlineSev.filter((sev) => sev === "BLOCKER" || sev === "CRITICAL").length;
19451
19969
  const warning = headlineSev.filter((sev) => sev === "WARNING").length;
@@ -19484,12 +20002,17 @@ function renderPrComment(doc, repoWebUrl, delta, outsideDiffFindings, movedHeadS
19484
20002
  out.push("");
19485
20003
  }
19486
20004
  if (doc.findings.length === 0) {
19487
- out.push(cleanBillLine(doc.run_status, delta?.rereview));
20005
+ const cleanBill = cleanBillLine(doc.run_status, delta?.rereview);
20006
+ out.push(notPosted !== undefined && cleanBill === CLEAN_BILL ? `No findings at or above ${code(notPosted.floor)} severity.` : cleanBill);
19488
20007
  out.push("");
19489
20008
  } else {
19490
20009
  out.push(...findingIndexLines(doc.findings, commentUrlByFindingId));
19491
20010
  out.push("");
19492
20011
  }
20012
+ if (notPosted !== undefined) {
20013
+ out.push(notPostedLine(notPosted));
20014
+ out.push("");
20015
+ }
19493
20016
  out.push(...liveFindingLines(delta?.rereview));
19494
20017
  if (outsideDiffFindings.length > 0) {
19495
20018
  out.push(...outsideDiffSection(outsideDiffFindings, doc.head_sha, webUrl, compactFrom));
@@ -19517,13 +20040,13 @@ function liveFindingLines(rereview) {
19517
20040
  }
19518
20041
  out.push("");
19519
20042
  }
19520
- const listed = (rereview.live ?? []).filter((row2) => row2.status !== "suppressed");
20043
+ const listed = (rereview.live ?? []).filter((row) => row.status !== "suppressed");
19521
20044
  if (listed.length > 0) {
19522
20045
  out.push("Still live:");
19523
- for (const row2 of listed) {
19524
- const loc = row2.locs[0] ?? row2.id;
19525
- const badge = row2.sev === SEVERITY_UNRECOVERABLE ? "\u26A0\uFE0F severity unavailable" : severityEmoji(row2.sev);
19526
- out.push(`- \`${row2.status}\` ${badge} \`${loc}\` \u2014 ${liveClaimText(row2.claim)} (${row2.id})`);
20046
+ for (const row of listed) {
20047
+ const loc = row.locs[0] ?? row.id;
20048
+ const badge = row.sev === SEVERITY_UNRECOVERABLE ? "\u26A0\uFE0F severity unavailable" : severityEmoji(row.sev);
20049
+ out.push(`- \`${row.status}\` ${badge} \`${loc}\` \u2014 ${liveClaimText(row.claim)} (${row.id})`);
19527
20050
  }
19528
20051
  out.push("");
19529
20052
  }
@@ -19589,7 +20112,13 @@ function cleanBillLine(runStatus, rereview) {
19589
20112
  if (!rereviewIsClean(rereview) && rereview !== undefined) {
19590
20113
  return `No new findings this delta. Live: ${liveBits(rereview).join(" \xB7 ")}.`;
19591
20114
  }
19592
- return "\u2705 Crysk reviewed this PR and found nothing to report.";
20115
+ return CLEAN_BILL;
20116
+ }
20117
+ var CLEAN_BILL = "\u2705 Crysk reviewed this PR and found nothing to report.";
20118
+ function notPostedLine(notPosted) {
20119
+ const noun = notPosted.count === 1 ? "finding" : "findings";
20120
+ const what = notPosted.floor === "blocking" ? "advisory" : "lower-severity";
20121
+ return `${notPosted.count} ${what} ${noun} not posted ` + `(${code(`post_min_severity: ${notPosted.floor}`)}).`;
19593
20122
  }
19594
20123
  function deltaLine(delta) {
19595
20124
  const since = delta.previousHeadSha === undefined ? "\u0394" : `\u0394 since ${code(delta.previousHeadSha.slice(0, 8))}`;
@@ -19661,6 +20190,16 @@ function tierExplanationLines(finding) {
19661
20190
  const isBlockerClass = finding.severity === "BLOCKER" || finding.severity === "CRITICAL";
19662
20191
  if (!isBlockerClass || finding.tier !== "advisory")
19663
20192
  return [];
20193
+ if (finding.materiality?.label === "immaterial") {
20194
+ return [
20195
+ "\u2696\uFE0F Demoted to advisory \u2014 not material under normal use: " + materialityReason(finding.materiality.reason)
20196
+ ];
20197
+ }
20198
+ if (isCausallyExempt(finding)) {
20199
+ return [
20200
+ "\u2696\uFE0F Advisory \u2014 this PR did not introduce it, so it does not block the gate"
20201
+ ];
20202
+ }
19664
20203
  const lines = [
19665
20204
  finding.refuter_verdict === "not_submitted" ? "\u2696\uFE0F Downgraded to advisory \u2014 the refuter never checked it" : "\u2696\uFE0F Downgraded to advisory \u2014 the refuter returned " + `\`${finding.refuter_verdict}\``
19666
20205
  ];
@@ -19669,6 +20208,11 @@ function tierExplanationLines(finding) {
19669
20208
  }
19670
20209
  return lines;
19671
20210
  }
20211
+ var MATERIALITY_REASON_MAX = 280;
20212
+ function materialityReason(reason) {
20213
+ const flat = oneLine2(reason).replaceAll("<!--", "<!\u2010\u2010").replaceAll("-->", "\u2010\u2010>").replaceAll("@", "@\u200B");
20214
+ return flat.length <= MATERIALITY_REASON_MAX ? flat : `${flat.slice(0, MATERIALITY_REASON_MAX - 1).trimEnd()}\u2026`;
20215
+ }
19672
20216
  function promptToFixBlock(finding) {
19673
20217
  return [
19674
20218
  "",
@@ -19796,21 +20340,21 @@ function parseRefAnchor(ref) {
19796
20340
  if (anchor === null)
19797
20341
  return null;
19798
20342
  const colon = anchor.lastIndexOf(":");
19799
- const path24 = anchor.slice(0, colon);
20343
+ const path = anchor.slice(0, colon);
19800
20344
  const lines = anchor.slice(colon + 1);
19801
20345
  const match = /^(\d+)(?:-(\d+))?$/.exec(lines);
19802
- if (path24.length === 0 || match?.[1] === undefined)
20346
+ if (path.length === 0 || match?.[1] === undefined)
19803
20347
  return null;
19804
20348
  return {
19805
- path: path24,
20349
+ path,
19806
20350
  lines,
19807
20351
  start: Number(match[1]),
19808
20352
  end: match[2] === undefined ? undefined : Number(match[2]),
19809
20353
  prose: ref.trim().slice(anchor.length).trim()
19810
20354
  };
19811
20355
  }
19812
- function blobUrl(webUrl, sha, path24, fragment) {
19813
- return `${webUrl}/blob/${sha}/${path24}#${fragment}`;
20356
+ function blobUrl(webUrl, sha, path, fragment) {
20357
+ return `${webUrl}/blob/${sha}/${path}#${fragment}`;
19814
20358
  }
19815
20359
  function runLines(doc, meta) {
19816
20360
  const { files, insertions, deletions } = meta.diffStat;
@@ -20000,191 +20544,200 @@ function envelopeModel(options, agentFiles) {
20000
20544
  // src/index.ts
20001
20545
  init_spec();
20002
20546
  var ENGINE_NAME = "pr-hero";
20003
- var ENGINE_VERSION = "0.3.0";
20547
+ var ENGINE_VERSION = "0.3.2";
20004
20548
  export {
20005
- zeroUsage,
20006
- writeFindings,
20007
- withUsageClass,
20008
- withRecordClass,
20009
- validateSummary,
20010
- validateReviewSpec,
20011
- validateRefuterResult,
20012
- validateHunterDraft,
20013
- validateFindingsDocument,
20014
- validateFinding,
20015
- validateDraftFinding,
20016
- sumUsage,
20017
- stepFailureReason,
20018
- spawnModelForClaudeCli,
20019
- severityEmoji,
20020
- settlementReceiptPath,
20021
- serversShuttingDown,
20022
- scanAidEmoji,
20023
- runPipeline,
20024
- runDirCandidate,
20025
- routingNeedsOpenCodeSdk,
20026
- routeSharesPrefix,
20027
- rootCauseIdByFinding,
20028
- resolveSummary,
20029
- resolveStepRoute,
20030
- resolveSpecialty,
20031
- resolveSharedPrefix,
20032
- resolveScout,
20033
- resolvePost,
20034
- resolveOpenCodeSdkV2Entry,
20035
- resolveModelRoute,
20036
- resolveMaxVerificationSteps,
20037
- resolveMaxConcurrentSteps,
20038
- resolveLogicalModel,
20039
- resolveBaseRef,
20040
- resolveAgentsDirSetting,
20041
- resolveAgentsDir,
20042
- resetServerShutdownForTests,
20043
- rereviewDeltaFromProvenance,
20044
- repoWebUrlFromRemote,
20045
- renderRereviewClosedComment,
20046
- renderReport,
20047
- renderPriorsBlock,
20048
- renderPrComment,
20049
- renderIssueFindingComment,
20050
- renderInlineComment,
20051
- renderAgentBody,
20052
- refuterPrompt,
20053
- recordClassOf,
20054
- readInstalledOpenCodeSdkVersion,
20055
- promptSetIdentity,
20056
- promptSetFingerprint,
20057
- preflightAgentsDir,
20058
- planOpenCodeSdkImport,
20059
- parseUsage,
20060
- parseRoutingConfig,
20061
- parseRemoteHead,
20062
- parseNumstatFiles,
20063
- parseNumstat,
20064
- parseLogicalIdentity,
20065
- parseLocalConfig,
20066
- parseGlobalConfig,
20067
- parseFindingCommentBadge,
20068
- parseArgs,
20069
- parseAgentSource,
20070
- parseAgentFile,
20071
- parityTriggered,
20072
- openCodeLaunchServerFor,
20073
- movedHeadSentence,
20074
- mergeRunEnvelope,
20075
- mergeConfig,
20076
- mergeAndDedupe,
20077
- makeProofRefResolver,
20078
- lookupAlias,
20079
- localReviewSpec,
20080
- loadOpenCodeSdk,
20081
- listPaths,
20082
- killAllChildProcesses,
20083
- isVacuousHunt,
20084
- isTransientSessionFailure,
20085
- isTerminalSessionFailure,
20086
- isSafeSlug,
20087
- isModelAlias,
20088
- isFullCommitId,
20089
- isCiEnvironment,
20090
- initTemplateOmissions,
20091
- initGotchasInstructions,
20092
- initGitReminder,
20093
- initConfigTemplate,
20094
- incompleteReviewAnnotation,
20095
- headContainedInBaseMessage,
20096
- gotchasUnusableReason,
20097
- gotchasErrorMessage,
20098
- freezeRoutePlan,
20099
- formatStepRoute,
20100
- formatModelRoute,
20101
- formatElapsed,
20102
- extractJsonObject,
20103
- extractAnchor,
20104
- estimateCost,
20105
- envelopeModel,
20106
- emptyDiffMessage,
20107
- deriveTier,
20108
- defaultReviewSpec,
20109
- defaultOpenCodeLaunchServer,
20110
- createRunDir,
20111
- createResolvedRoutePlan,
20112
- createDefaultTransportRegistry,
20113
- coverageSentence,
20114
- computeRouteFingerprint,
20115
- clusterByRootCause,
20116
- closeAllServers,
20117
- classifyFailure,
20118
- claimSimilarity,
20119
- checkD1_11Readiness,
20120
- changedPathsFromDiff,
20121
- buildStepArgv,
20122
- buildResolvedRoutePlan,
20123
- blobUrl,
20124
- attemptLogPath,
20125
- attemptEvidencePath,
20126
- assertOutsideRepo,
20127
- assertBasenameOnly,
20128
- allExcludedMessage,
20129
- aliasCanonical,
20130
- agentsDirSeat,
20131
- agentsDirProblems,
20132
- agentStepKey,
20133
- agentFilePath,
20134
- admitRoutePlan,
20135
- admitOpenCodeVersionPair,
20136
- admitDiversityRoutePlan,
20137
- UnmappedRouteError,
20138
- UnauthorizedRouteError,
20139
- SUPPORTED_OPENCODE_SERVER_VERSION,
20140
- SUPPORTED_OPENCODE_SDK_VERSION,
20141
- SUMMARY_DIRECTION,
20142
- SETUP_GOTCHAS_FALLBACK,
20143
- SCHEMA_VERSION_V1_1,
20144
- SCHEMA_VERSION,
20145
- RouteAdmissionError,
20146
- ReviewSpecValidationError,
20147
- RUNTIME_PREAMBLE,
20148
- PIPELINE_SCHEMA_VERSION,
20149
- OpenCodeVersionAdmissionError,
20150
- OpenCodeProductionGatedError,
20151
- ModelRoutingError,
20152
- MODEL_CATALOG,
20153
- HELP_TEXT,
20154
- GOTCHAS_TEMPLATE,
20155
- GOTCHAS_PLACEHOLDER_MARKER,
20156
- FindingsValidationError,
20157
- FORMAT_RETRY_REMINDER,
20158
- FINDINGS_CONFORMANCE_CASES,
20159
- ENGINE_VERSION,
20160
- ENGINE_NAME,
20161
- EMPTY_LOCAL_CONFIG,
20162
- DraftValidationError,
20163
- DefaultTransportRegistry,
20164
- DEFAULT_WATCH_INTERVAL_MIN,
20165
- DEFAULT_SUMMARY_MODEL,
20166
- DEFAULT_STEP_TIMEOUT_MS,
20167
- DEFAULT_STEP_MAX_ATTEMPTS,
20168
- DEFAULT_SCOUT_MODEL,
20169
- DEFAULT_PIPELINE_TIMEOUT_MS,
20170
- DEFAULT_MAX_VERIFICATION_STEPS,
20171
- DEFAULT_HOP_BUDGET,
20172
- DEFAULT_HEAD_REF,
20173
- DEFAULT_GC_INTERVAL_MIN,
20174
- DEFAULT_CONSOLIDATE_MODEL,
20175
- DEFAULT_BASE_REF,
20176
- DEDUPE_SYMBOL_LINE_WINDOW,
20177
- DEDUPE_CLAIM_OVERLAP_THRESHOLD,
20178
- DEDUPE_CLAIM_MIN_TOKENS,
20179
- CliUsageError,
20180
- CliError,
20181
- ClaudeCodeRunner,
20182
- CONFIG_DIRECTION,
20183
- CODEGRAPH_MANDATE,
20184
- BUNDLED_AGENTS_DIR_LABEL,
20185
- AmbiguousMappingError,
20186
- AGENT_NAMES,
20187
- AGENT_FILE_PATTERNS,
20549
+ ACTIVE_CHILD_PROCS,
20188
20550
  ACTIVE_SERVER_CLOSERS,
20189
- ACTIVE_CHILD_PROCS
20551
+ AGENT_FILE_PATTERNS,
20552
+ AGENT_NAMES,
20553
+ AmbiguousMappingError,
20554
+ BUNDLED_AGENTS_DIR_LABEL,
20555
+ CODEGRAPH_MANDATE,
20556
+ CONFIG_DIRECTION,
20557
+ ClaudeCodeRunner,
20558
+ CliError,
20559
+ CliUsageError,
20560
+ DEDUPE_CLAIM_MIN_TOKENS,
20561
+ DEDUPE_CLAIM_OVERLAP_THRESHOLD,
20562
+ DEDUPE_SYMBOL_LINE_WINDOW,
20563
+ DEFAULT_BASE_REF,
20564
+ DEFAULT_CONSOLIDATE_MODEL,
20565
+ DEFAULT_GC_INTERVAL_MIN,
20566
+ DEFAULT_HEAD_REF,
20567
+ DEFAULT_HOP_BUDGET,
20568
+ DEFAULT_MAX_VERIFICATION_STEPS,
20569
+ DEFAULT_PIPELINE_TIMEOUT_MS,
20570
+ DEFAULT_SCOUT_MODEL,
20571
+ DEFAULT_STEP_MAX_ATTEMPTS,
20572
+ DEFAULT_STEP_TIMEOUT_MS,
20573
+ DEFAULT_SUMMARY_MODEL,
20574
+ DEFAULT_WATCH_INTERVAL_MIN,
20575
+ DefaultTransportRegistry,
20576
+ DraftValidationError,
20577
+ EMPTY_LOCAL_CONFIG,
20578
+ ENGINE_NAME,
20579
+ ENGINE_VERSION,
20580
+ FINDINGS_CONFORMANCE_CASES,
20581
+ FORMAT_RETRY_REMINDER,
20582
+ FindingsValidationError,
20583
+ GOTCHAS_PLACEHOLDER_MARKER,
20584
+ GOTCHAS_TEMPLATE,
20585
+ HELP_TEXT,
20586
+ MATERIALITY_JUDGE_MODEL,
20587
+ MATERIALITY_STEP_KEY,
20588
+ MATERIALITY_TITLE_FALLBACK,
20589
+ MODEL_CATALOG,
20590
+ ModelRoutingError,
20591
+ OpenCodeProductionGatedError,
20592
+ OpenCodeVersionAdmissionError,
20593
+ PIPELINE_SCHEMA_VERSION,
20594
+ RUNTIME_PREAMBLE,
20595
+ ReviewSpecValidationError,
20596
+ RouteAdmissionError,
20597
+ SCHEMA_VERSION,
20598
+ SCHEMA_VERSION_V1_1,
20599
+ SETUP_GOTCHAS_FALLBACK,
20600
+ SUMMARY_DIRECTION,
20601
+ SUPPORTED_OPENCODE_SDK_VERSION,
20602
+ SUPPORTED_OPENCODE_SERVER_VERSION,
20603
+ UnauthorizedRouteError,
20604
+ UnmappedRouteError,
20605
+ admitDiversityRoutePlan,
20606
+ admitOpenCodeVersionPair,
20607
+ admitRoutePlan,
20608
+ agentFilePath,
20609
+ agentStepKey,
20610
+ agentsDirProblems,
20611
+ agentsDirSeat,
20612
+ aliasCanonical,
20613
+ allExcludedMessage,
20614
+ assertBasenameOnly,
20615
+ assertOutsideRepo,
20616
+ attemptEvidencePath,
20617
+ attemptLogPath,
20618
+ blobUrl,
20619
+ buildResolvedRoutePlan,
20620
+ buildStepArgv,
20621
+ changedPathsFromDiff,
20622
+ checkD1_11Readiness,
20623
+ claimSimilarity,
20624
+ classifyFailure,
20625
+ closeAllServers,
20626
+ clusterByRootCause,
20627
+ code,
20628
+ computeRouteFingerprint,
20629
+ coverageSentence,
20630
+ createDefaultTransportRegistry,
20631
+ createResolvedRoutePlan,
20632
+ createRunDir,
20633
+ defaultOpenCodeLaunchServer,
20634
+ defaultReviewSpec,
20635
+ deriveTier,
20636
+ emptyDiffMessage,
20637
+ envelopeModel,
20638
+ estimateCost,
20639
+ extractAnchor,
20640
+ extractJsonObject,
20641
+ formatElapsed,
20642
+ formatModelRoute,
20643
+ formatStepRoute,
20644
+ freezeRoutePlan,
20645
+ gotchasErrorMessage,
20646
+ gotchasUnusableReason,
20647
+ headContainedInBaseMessage,
20648
+ incompleteReviewAnnotation,
20649
+ initConfigTemplate,
20650
+ initGitReminder,
20651
+ initGotchasInstructions,
20652
+ initTemplateOmissions,
20653
+ isCausallyExempt,
20654
+ isCiEnvironment,
20655
+ isFullCommitId,
20656
+ isMeasuredJudgeRoute,
20657
+ isModelAlias,
20658
+ isNotCausedByPr,
20659
+ isSafeSlug,
20660
+ isTerminalSessionFailure,
20661
+ isTransientSessionFailure,
20662
+ isVacuousHunt,
20663
+ killAllChildProcesses,
20664
+ listPaths,
20665
+ loadOpenCodeSdk,
20666
+ localReviewSpec,
20667
+ lookupAlias,
20668
+ makeProofRefResolver,
20669
+ mergeAndDedupe,
20670
+ mergeConfig,
20671
+ mergeRunEnvelope,
20672
+ movedHeadSentence,
20673
+ openCodeLaunchServerFor,
20674
+ parityTriggered,
20675
+ parseAgentFile,
20676
+ parseAgentSource,
20677
+ parseArgs,
20678
+ parseFindingCommentBadge,
20679
+ parseGlobalConfig,
20680
+ parseLocalConfig,
20681
+ parseLogicalIdentity,
20682
+ parseNumstat,
20683
+ parseNumstatFiles,
20684
+ parseRemoteHead,
20685
+ parseRoutingConfig,
20686
+ parseUsage,
20687
+ planOpenCodeSdkImport,
20688
+ preflightAgentsDir,
20689
+ promptSetFingerprint,
20690
+ promptSetIdentity,
20691
+ readInstalledOpenCodeSdkVersion,
20692
+ recordClassOf,
20693
+ refuterPrompt,
20694
+ renderAgentBody,
20695
+ renderInlineComment,
20696
+ renderIssueFindingComment,
20697
+ renderPrComment,
20698
+ renderPriorsBlock,
20699
+ renderReport,
20700
+ renderRereviewClosedComment,
20701
+ repoWebUrlFromRemote,
20702
+ rereviewDeltaFromProvenance,
20703
+ resetServerShutdownForTests,
20704
+ resolveAgentsDir,
20705
+ resolveAgentsDirSetting,
20706
+ resolveBaseRef,
20707
+ resolveLogicalModel,
20708
+ resolveMaterialityGate,
20709
+ resolveMaterialityJudgeRoute,
20710
+ resolveMaxConcurrentSteps,
20711
+ resolveMaxVerificationSteps,
20712
+ resolveModelRoute,
20713
+ resolveOpenCodeSdkV2Entry,
20714
+ resolvePost,
20715
+ resolveScout,
20716
+ resolveSharedPrefix,
20717
+ resolveSpecialty,
20718
+ resolveStepRoute,
20719
+ resolveSummary,
20720
+ rootCauseIdByFinding,
20721
+ routeSharesPrefix,
20722
+ routingNeedsOpenCodeSdk,
20723
+ runDirCandidate,
20724
+ runPipeline,
20725
+ scanAidEmoji,
20726
+ serversShuttingDown,
20727
+ settlementReceiptPath,
20728
+ severityEmoji,
20729
+ spawnModelForClaudeCli,
20730
+ stepFailureReason,
20731
+ sumUsage,
20732
+ validateDraftFinding,
20733
+ validateFinding,
20734
+ validateFindingsDocument,
20735
+ validateHunterDraft,
20736
+ validateRefuterResult,
20737
+ validateReviewSpec,
20738
+ validateSummary,
20739
+ withRecordClass,
20740
+ withUsageClass,
20741
+ writeFindings,
20742
+ zeroUsage
20190
20743
  };