@attalabs/vinaya 0.39.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/README.md +9 -9
  2. package/aeg-root/contracts/planner-developer.md +1 -1
  3. package/aeg-root/enforcement.md +22 -22
  4. package/aeg-root/process.md +1 -1
  5. package/aeg-root/roles/archivist.md +1 -1
  6. package/aeg-root/roles/developer/reference.md +4 -1
  7. package/aeg-root/roles/developer.md +1 -1
  8. package/aeg-root/roles/planner/reference.md +18 -5
  9. package/aeg-root/roles/principal.md +1 -1
  10. package/aeg-root/roles/reviewer.md +3 -3
  11. package/aeg-root/roles/security.md +4 -4
  12. package/aeg-root/roles/tranche-archivist.md +2 -2
  13. package/aeg-root/skills/aeg/SKILL.md +1 -1
  14. package/aeg-root/state-machine.md +8 -13
  15. package/aeg-root/templates/brief-template.md +4 -1
  16. package/aeg-root/templates/decision-record-template.md +38 -0
  17. package/aeg-root/templates/issue-rationale-template.md +1 -1
  18. package/aeg-root/tranche-model.md +1 -1
  19. package/dist/checks/bin/check-body-bare-digits.js +1867 -347
  20. package/dist/checks/bin/check-branch-topology.js +1181 -237
  21. package/dist/checks/bin/check-brief-shape.js +1911 -433
  22. package/dist/checks/bin/check-changeset-coverage.js +2144 -517
  23. package/dist/checks/bin/check-ci-shard-coverage.js +12133 -11
  24. package/dist/checks/bin/check-closes-n.js +1181 -237
  25. package/dist/checks/bin/check-coherence.js +1785 -1126
  26. package/dist/checks/bin/check-dead-branch-push.js +1154 -225
  27. package/dist/checks/bin/check-dispatch-readiness.js +2068 -436
  28. package/dist/checks/bin/check-doc-claims.js +2104 -231
  29. package/dist/checks/bin/check-doc-coverage-push.js +2181 -515
  30. package/dist/checks/bin/check-doc-coverage.js +2181 -519
  31. package/dist/checks/bin/check-doctrine-no-procedures.js +1668 -345
  32. package/dist/checks/bin/check-doctrine-portability.js +2143 -516
  33. package/dist/checks/bin/check-evidence-fresh.js +2080 -465
  34. package/dist/checks/bin/check-exec-bits.js +2130 -503
  35. package/dist/checks/bin/check-first-push-dispatch.js +1845 -371
  36. package/dist/checks/bin/check-issue-assignment.js +712 -170
  37. package/dist/checks/bin/check-issue-milestone-attach.js +1145 -225
  38. package/dist/checks/bin/check-issue-objectives-numbering.js +1661 -338
  39. package/dist/checks/bin/check-issue-parts-coverage.js +1145 -225
  40. package/dist/checks/bin/check-issue-surface-globs.js +1787 -369
  41. package/dist/checks/bin/check-issue-title-grammar.js +1145 -225
  42. package/dist/checks/bin/check-issue-tranche-label.js +702 -170
  43. package/dist/checks/bin/check-main-branch-refusal.js +1157 -227
  44. package/dist/checks/bin/check-no-disk-state.js +1145 -225
  45. package/dist/checks/bin/check-pr-premise-reassert.js +1661 -338
  46. package/dist/checks/bin/check-pr-report-density.js +1145 -225
  47. package/dist/checks/bin/check-principal-test-plan-wait.js +2379 -249
  48. package/dist/checks/bin/check-quoted-command.js +2128 -501
  49. package/dist/checks/bin/check-reader-resolvable-prose.js +2170 -517
  50. package/dist/checks/bin/check-registry-gates.js +1228 -272
  51. package/dist/checks/bin/check-retired-vocabulary.js +2153 -507
  52. package/dist/checks/bin/check-review-gate.js +1932 -350
  53. package/dist/checks/bin/check-single-plan-pr.js +1208 -229
  54. package/dist/checks/bin/check-surface-scope.js +1414 -244
  55. package/dist/checks/bin/check-test-plan.js +2381 -252
  56. package/dist/checks/bin/check-token-collection-wired.js +1145 -225
  57. package/dist/checks/bin/check-workspace-escape.js +2141 -514
  58. package/dist/checks/bin/verify-coherence.js +493 -86
  59. package/dist/checks/bin/verify-dispatch.js +512 -132
  60. package/dist/checks/bin/verify-docs.js +549 -124
  61. package/dist/index.js +22702 -17900
  62. package/dist/lib/pre-push-cache-test-run.js +1026 -233
  63. package/dist/lib/pre-push-select-tests.js +922 -173
  64. package/package.json +12 -1
  65. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/anchored-region.ts +13 -2
  66. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-render.ts +55 -26
  67. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/types.ts +12 -1
  68. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dispatch-gate.ts +22 -1
  69. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doctrine-portability.ts +6 -1
  70. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/entry-point.ts +27 -0
  71. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/gate-audience.ts +2 -1
  72. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/index.ts +19 -2
  73. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-validation.ts +593 -55
  74. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/narration.ts +1 -0
  75. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/pr-report-density.ts +6 -4
  76. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/retired-vocabulary.ts +19 -2
  77. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-policy.ts +32 -13
  78. package/studio-standalone/apps/vinaya-studio/web/.next/BUILD_ID +1 -1
  79. package/studio-standalone/apps/vinaya-studio/web/.next/build-manifest.json +3 -3
  80. package/studio-standalone/apps/vinaya-studio/web/.next/prerender-manifest.json +3 -3
  81. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.html +1 -1
  82. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.rsc +1 -1
  83. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  84. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  85. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  86. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  87. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  88. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page/server-reference-manifest.json +2 -2
  89. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page.js.nft.json +1 -1
  90. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  91. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page/server-reference-manifest.json +2 -2
  92. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page.js.nft.json +1 -1
  93. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page_client-reference-manifest.js +1 -1
  94. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page/server-reference-manifest.json +2 -2
  95. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js +1 -1
  96. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js.nft.json +1 -1
  97. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page_client-reference-manifest.js +1 -1
  98. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page/server-reference-manifest.json +2 -2
  99. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js +1 -1
  100. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js.nft.json +1 -1
  101. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page_client-reference-manifest.js +1 -1
  102. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page/server-reference-manifest.json +2 -2
  103. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js +1 -1
  104. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js.nft.json +1 -1
  105. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page_client-reference-manifest.js +1 -1
  106. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page/server-reference-manifest.json +3 -3
  107. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js +1 -1
  108. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js.nft.json +1 -1
  109. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page_client-reference-manifest.js +1 -1
  110. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page/server-reference-manifest.json +2 -2
  111. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js +2 -2
  112. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js.nft.json +1 -1
  113. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page_client-reference-manifest.js +1 -1
  114. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page/server-reference-manifest.json +2 -2
  115. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js +1 -1
  116. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js.nft.json +1 -1
  117. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page_client-reference-manifest.js +1 -1
  118. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page/server-reference-manifest.json +2 -2
  119. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js +1 -1
  120. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js.nft.json +1 -1
  121. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page_client-reference-manifest.js +1 -1
  122. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/1q96_modules_@clerk_nextjs_dist_esm_app-router_client_keyless-creator-reader_0lom2js.js +1 -1
  123. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__08e39jo._.js +1 -1
  124. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0ls23oh._.js +1 -1
  125. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0sxadt2._.js +13 -0
  126. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1a3j3n1._.js +57 -0
  127. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1gjqmhq._.js +1 -1
  128. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1wc4-ip._.js +1 -1
  129. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__1ug9syi._.js → [root-of-the-server]__1wzfiav._.js} +1 -1
  130. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_08onyya._.js +1 -1
  131. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_096f46i._.js +1 -1
  132. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0af2one._.js +1 -1
  133. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0e5tkdd._.js +1 -1
  134. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0kf2g72._.js +1 -1
  135. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0zf4d27._.js +1 -1
  136. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1-wo68i._.js +1 -1
  137. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1achbh9._.js +1 -1
  138. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/node_modules_@clerk_nextjs_dist_esm_app-router_server-actions_1x7vfhn.js +2 -2
  139. package/studio-standalone/apps/vinaya-studio/web/.next/server/middleware-build-manifest.js +3 -3
  140. package/studio-standalone/apps/vinaya-studio/web/.next/server/pages/500.html +1 -1
  141. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.js +1 -1
  142. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.json +4 -4
  143. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{06_55xbp7rcbi.js → 1p3vr9qts86_b.js} +1 -1
  144. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{2brkwv169ygep.js → 21tunzmxjvm2a.js} +1 -1
  145. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{33rszkngkuoko.js → 38kom-9c-oi65.js} +1 -1
  146. package/studio-standalone/apps/vinaya-studio/web/package.json +2 -2
  147. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__04adkz-._.js +0 -57
  148. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__19jyp3m._.js +0 -13
  149. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → Y3oaZSTSP9PivUuJvxK1W}/_buildManifest.js +0 -0
  150. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → Y3oaZSTSP9PivUuJvxK1W}/_clientMiddlewareManifest.js +0 -0
  151. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → Y3oaZSTSP9PivUuJvxK1W}/_ssgManifest.js +0 -0
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/checks/bin/check-body-bare-digits.ts
4
- import { execFileSync as execFileSync3 } from "node:child_process";
4
+ import { execFileSync as execFileSync4 } from "node:child_process";
5
5
 
6
6
  // ../../packages/aeg-core/src/entry-point.ts
7
7
  import { realpathSync } from "node:fs";
@@ -42,7 +42,6 @@ var GATE_AUDIENCE = {
42
42
  };
43
43
  var NON_GATE_BINS = [
44
44
  "archive-task",
45
- "assign-task-issue",
46
45
  "dead-branch-audit",
47
46
  "eval-agent-compliance",
48
47
  "open-issue",
@@ -305,6 +304,25 @@ async function runAsync(args) {
305
304
  function ghApiGet(path) {
306
305
  return JSON.parse(run(["api", path]));
307
306
  }
307
+ var MAX_PER_PAGE = 100;
308
+ var MAX_PAGES = 100;
309
+ async function ghApiGetAllPagesAsync(pathWithoutPage, opts) {
310
+ const [base = pathWithoutPage, query = ""] = pathWithoutPage.split("?");
311
+ const params = new URLSearchParams(query);
312
+ params.set("per_page", String(MAX_PER_PAGE));
313
+ const all = [];
314
+ for (let page = 1;page <= MAX_PAGES; page++) {
315
+ params.set("page", String(page));
316
+ const args = ["api", `${base}?${params.toString()}`];
317
+ if (opts?.jq)
318
+ args.push("-q", opts.jq);
319
+ const batch = JSON.parse(await runAsync(args));
320
+ all.push(...batch);
321
+ if (batch.length < MAX_PER_PAGE)
322
+ return all;
323
+ }
324
+ throw new Error(`ghApiGetAllPagesAsync: "${pathWithoutPage}" did not terminate within ${MAX_PAGES} pages (${MAX_PAGES * MAX_PER_PAGE} items) — refusing to keep walking.`);
325
+ }
308
326
  function issueListByLabelArgs(owner, repo, label) {
309
327
  return [
310
328
  "issue",
@@ -716,6 +734,10 @@ function intentGoalForSlug(description, slug) {
716
734
  function matchesLegacyMilestone(milestones, slug) {
717
735
  return milestones.find((m) => m.title === slug) ?? null;
718
736
  }
737
+ var TRANCHE_SLUG_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*-v\d+$/;
738
+ function slugShapedTitles(milestones) {
739
+ return milestones.map((m) => m.title).filter((t) => TRANCHE_SLUG_SHAPE.test(t));
740
+ }
719
741
  function factsFromLegacyMilestone(milestone) {
720
742
  return {
721
743
  goal: milestone.description ?? "",
@@ -749,6 +771,90 @@ function findMilestoneForSlug(owner, repo, slug) {
749
771
  return resolveLegacyFacts(legacy, issues);
750
772
  return { goal: goalFromMilestones(milestones, slug), lifecycle: lifecycleFromIssues(issues) };
751
773
  }
774
+ function trancheSlugsFromLabels(labels) {
775
+ const slugs = [];
776
+ for (const l of labels) {
777
+ const slug = trancheSlugOf(l.name);
778
+ if (slug !== null)
779
+ slugs.push(slug);
780
+ }
781
+ return slugs;
782
+ }
783
+ async function indexTrancheMilestonesAsync(owner, repo) {
784
+ const [milestones, labels] = await Promise.all([
785
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`),
786
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`)
787
+ ]);
788
+ const active = [];
789
+ const archived = [];
790
+ const facts = new Map;
791
+ const legacySlugs = new Set(slugShapedTitles(milestones));
792
+ const legacyMilestoneBySlug = new Map(milestones.filter((m) => legacySlugs.has(m.title)).map((m) => [m.title, m]));
793
+ const newPathSlugs = trancheSlugsFromLabels(labels).filter((slug) => !legacySlugs.has(slug));
794
+ const uniqueNewPathSlugs = [...new Set(newPathSlugs)];
795
+ const uniqueLegacySlugs = [...legacySlugs];
796
+ const [legacyIssuesBySlug, newPathIssuesBySlug] = await Promise.all([
797
+ Promise.all(uniqueLegacySlugs.map((slug) => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug)))),
798
+ Promise.all(uniqueNewPathSlugs.map((slug) => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))))
799
+ ]);
800
+ uniqueLegacySlugs.forEach((slug, i) => {
801
+ const m = legacyMilestoneBySlug.get(slug);
802
+ if (!m)
803
+ return;
804
+ const ref = { slug, goal: m.description ?? "" };
805
+ const f = resolveLegacyFacts(m, legacyIssuesBySlug[i] ?? []);
806
+ if (f.lifecycle === "complete")
807
+ archived.push(ref);
808
+ else if (f.lifecycle === "active")
809
+ active.push(ref);
810
+ facts.set(slug, f);
811
+ });
812
+ uniqueNewPathSlugs.forEach((slug, i) => {
813
+ const issues = newPathIssuesBySlug[i] ?? [];
814
+ const lifecycle = lifecycleFromIssues(issues);
815
+ const goal = goalFromMilestones(milestones, slug);
816
+ const f = { goal, lifecycle };
817
+ facts.set(slug, f);
818
+ if (lifecycle === "active")
819
+ active.push({ slug, goal });
820
+ else if (lifecycle === "complete")
821
+ archived.push({ slug, goal });
822
+ });
823
+ return { active, archived, facts, legacySlugs };
824
+ }
825
+ async function indexTrancheMilestonesForSlugAsync(owner, repo, slug) {
826
+ const [milestones, labels, issues] = await Promise.all([
827
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`),
828
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`),
829
+ ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))
830
+ ]);
831
+ const active = [];
832
+ const archived = [];
833
+ const facts = new Map;
834
+ const legacySlugs = new Set;
835
+ const legacyMilestone = slugShapedTitles(milestones).includes(slug) ? matchesLegacyMilestone(milestones, slug) : null;
836
+ if (legacyMilestone) {
837
+ legacySlugs.add(slug);
838
+ const ref = { slug, goal: legacyMilestone.description ?? "" };
839
+ const f = resolveLegacyFacts(legacyMilestone, issues);
840
+ if (f.lifecycle === "complete")
841
+ archived.push(ref);
842
+ else if (f.lifecycle === "active")
843
+ active.push(ref);
844
+ facts.set(slug, f);
845
+ } else if (trancheSlugsFromLabels(labels).includes(slug)) {
846
+ const lifecycle = lifecycleFromIssues(issues);
847
+ const goal = goalFromMilestones(milestones, slug);
848
+ facts.set(slug, { goal, lifecycle });
849
+ if (lifecycle === "active")
850
+ active.push({ slug, goal });
851
+ else if (lifecycle === "complete")
852
+ archived.push({ slug, goal });
853
+ }
854
+ const openLegacyTitles = new Set(slugShapedTitles(milestones.filter((m) => m.state === "open")));
855
+ const otherOpenLegacySlugs = [...openLegacyTitles].filter((t) => t !== slug);
856
+ return { active, archived, facts, legacySlugs, otherOpenLegacySlugs };
857
+ }
752
858
 
753
859
  // ../../packages/aeg-forge-state/src/derive-from-forge.ts
754
860
  function trancheFromIssues(slug, issues, known) {
@@ -1409,6 +1515,125 @@ var graphql2 = withDefaults3(request, {
1409
1515
  method: "POST",
1410
1516
  url: "/graphql"
1411
1517
  });
1518
+
1519
+ // ../../packages/aeg-forge-state/src/fetch-provenance.ts
1520
+ var PROVENANCE_PATTERN = /^###\s+AEG provenance\b/im;
1521
+ function provenanceMatchesIssue(text, issueNum) {
1522
+ if (!PROVENANCE_PATTERN.test(text))
1523
+ return false;
1524
+ const m = text.match(/^-\s*Issue:\s*#(\d+)/im);
1525
+ return m !== null && Number(m[1]) === issueNum;
1526
+ }
1527
+ function isPrCloser(closer) {
1528
+ return closer !== null && typeof closer.number === "number";
1529
+ }
1530
+ async function fetchProvenanceViaCrossReferences(issueNums, owner, repo, token) {
1531
+ const result = new Map;
1532
+ if (issueNums.length === 0)
1533
+ return result;
1534
+ const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
1535
+ const perIssue = issueNums.map((n) => `
1536
+ i_${n}: issue(number: ${n}) {
1537
+ timelineItems(first: 50, itemTypes: [CROSS_REFERENCED_EVENT]) {
1538
+ nodes {
1539
+ ... on CrossReferencedEvent {
1540
+ source {
1541
+ ... on PullRequest {
1542
+ number
1543
+ body
1544
+ comments(first: 50) { nodes { body } }
1545
+ }
1546
+ }
1547
+ }
1548
+ }
1549
+ }
1550
+ }`).join("");
1551
+ const query = `query ProvenanceCrossRef($owner: String!, $repo: String!) {
1552
+ repository(owner: $owner, name: $repo) {${perIssue}
1553
+ }
1554
+ }`;
1555
+ let response;
1556
+ try {
1557
+ response = await client(query, { owner, repo });
1558
+ } catch {
1559
+ return result;
1560
+ }
1561
+ if (!response.repository)
1562
+ return result;
1563
+ for (const n of issueNums) {
1564
+ const raw = response.repository[`i_${n}`];
1565
+ const nodes = raw?.timelineItems?.nodes ?? [];
1566
+ const found = nodes.some(({ source }) => {
1567
+ if (!source || typeof source.number !== "number")
1568
+ return false;
1569
+ const pr = source;
1570
+ if (provenanceMatchesIssue(pr.body ?? "", n))
1571
+ return true;
1572
+ return pr.comments.nodes.some((c) => provenanceMatchesIssue(c.body, n));
1573
+ });
1574
+ result.set(n, found);
1575
+ }
1576
+ return result;
1577
+ }
1578
+ async function fetchProvenance(issueNums, owner, repo, token) {
1579
+ const result = new Map;
1580
+ if (issueNums.length === 0)
1581
+ return result;
1582
+ const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
1583
+ const perIssue = issueNums.map((n) => `
1584
+ i_${n}: issue(number: ${n}) {
1585
+ timelineItems(last: 1, itemTypes: [CLOSED_EVENT]) {
1586
+ nodes {
1587
+ ... on ClosedEvent {
1588
+ closer {
1589
+ ... on PullRequest {
1590
+ number
1591
+ body
1592
+ comments(first: 50) {
1593
+ nodes { body }
1594
+ }
1595
+ }
1596
+ }
1597
+ }
1598
+ }
1599
+ }
1600
+ }`).join("");
1601
+ const query = `query Provenance($owner: String!, $repo: String!) {
1602
+ repository(owner: $owner, name: $repo) {${perIssue}
1603
+ }
1604
+ }`;
1605
+ let response;
1606
+ try {
1607
+ response = await client(query, { owner, repo });
1608
+ } catch {
1609
+ return result;
1610
+ }
1611
+ if (!response.repository)
1612
+ return result;
1613
+ const needsFallback = [];
1614
+ for (const n of issueNums) {
1615
+ const raw = response.repository[`i_${n}`];
1616
+ if (!raw) {
1617
+ result.set(n, false);
1618
+ continue;
1619
+ }
1620
+ const closer = raw.timelineItems?.nodes?.[0]?.closer;
1621
+ const c = closer ?? null;
1622
+ if (!isPrCloser(c)) {
1623
+ needsFallback.push(n);
1624
+ continue;
1625
+ }
1626
+ const bodyHas = PROVENANCE_PATTERN.test(c.body ?? "");
1627
+ const commentHas = c.comments.nodes.some((x) => PROVENANCE_PATTERN.test(x.body));
1628
+ result.set(n, bodyHas || commentHas);
1629
+ }
1630
+ if (needsFallback.length > 0) {
1631
+ const fallback = await fetchProvenanceViaCrossReferences(needsFallback, owner, repo, token);
1632
+ for (const [n, found] of fallback)
1633
+ result.set(n, found);
1634
+ }
1635
+ return result;
1636
+ }
1412
1637
  // ../../packages/aeg-forge-state/src/github-token.ts
1413
1638
  import { execFile as execFile2 } from "node:child_process";
1414
1639
  import { promisify as promisify2 } from "node:util";
@@ -1638,6 +1863,84 @@ function describeError(err) {
1638
1863
  return err;
1639
1864
  return "unknown error";
1640
1865
  }
1866
+ // ../../packages/aeg-forge-state/src/prior-tranche-archival.ts
1867
+ function defaultPriorTrancheArchivalDeps() {
1868
+ let facts = new Map;
1869
+ return {
1870
+ activeTrancheSlugs: async (excludeSlug, repo) => {
1871
+ const index = await indexTrancheMilestonesAsync(repo.owner, repo.repo);
1872
+ facts = index.facts;
1873
+ return index.active.map((m) => m.slug).filter((slug) => slug !== excludeSlug);
1874
+ },
1875
+ deriveTranche: (slug, repo) => deriveTrancheFromForge(repo.owner, repo.repo, slug, facts.get(slug)),
1876
+ openIssues: async (slug, repo) => (await fetchTrancheIssuesAsync(repo.owner, repo.repo, slug)).filter((issue) => issue.state === "OPEN").map((issue) => ({ number: issue.number }))
1877
+ };
1878
+ }
1879
+ function reason(err) {
1880
+ return err instanceof Error ? err.message.split(`
1881
+ `)[0] ?? "failed" : String(err);
1882
+ }
1883
+ async function resolvePriorTrancheArchival(projects, excludeSlug, repo, deps = defaultPriorTrancheArchivalDeps()) {
1884
+ if (projects.length === 0)
1885
+ return { facts: [], infraFailure: null };
1886
+ let candidates;
1887
+ try {
1888
+ candidates = await deps.activeTrancheSlugs(excludeSlug, repo);
1889
+ } catch (err) {
1890
+ return {
1891
+ facts: [],
1892
+ infraFailure: `severity:infra — could not read the active tranches (${reason(err)}); whether a prior tranche is archived is unknown.`
1893
+ };
1894
+ }
1895
+ const facts = [];
1896
+ const unreadable = [];
1897
+ const derived = new Map;
1898
+ const derive = (slug) => {
1899
+ let p = derived.get(slug);
1900
+ if (!p) {
1901
+ p = deps.deriveTranche(slug, repo);
1902
+ derived.set(slug, p);
1903
+ }
1904
+ return p;
1905
+ };
1906
+ for (const project of projects) {
1907
+ let found = null;
1908
+ let unknown = false;
1909
+ for (const slug of candidates) {
1910
+ let candidateTranche;
1911
+ try {
1912
+ candidateTranche = await derive(slug);
1913
+ } catch {
1914
+ unknown = true;
1915
+ unreadable.push(`the tasks of tranche \`${slug}\` (project \`${project}\`)`);
1916
+ break;
1917
+ }
1918
+ if (!candidateTranche.tasks.some((t) => t.projects.includes(project)))
1919
+ continue;
1920
+ let openIssues;
1921
+ try {
1922
+ openIssues = await deps.openIssues(slug, repo);
1923
+ } catch {
1924
+ openIssues = null;
1925
+ }
1926
+ if (openIssues === null) {
1927
+ unknown = true;
1928
+ unreadable.push(`the open Issues of tranche \`${slug}\` (project \`${project}\`)`);
1929
+ break;
1930
+ }
1931
+ if (openIssues.length === 0) {
1932
+ found = { project, priorTrancheSlug: slug, archived: false };
1933
+ break;
1934
+ }
1935
+ }
1936
+ if (!unknown)
1937
+ facts.push(found ?? { project, priorTrancheSlug: null, archived: false });
1938
+ }
1939
+ return {
1940
+ facts,
1941
+ infraFailure: unreadable.length === 0 ? null : `severity:infra — could not read ${unreadable.join(", ")}; whether a prior tranche is archived is unknown.`
1942
+ };
1943
+ }
1641
1944
  // ../../packages/aeg-forge-state/src/fetch-open-issues.ts
1642
1945
  async function fetchOpenIssuesByLabel(slugs, owner, repo, token) {
1643
1946
  const result = new Map;
@@ -1712,6 +2015,10 @@ function buildQuery(issueNumbers) {
1712
2015
  }
1713
2016
  }`;
1714
2017
  }
2018
+ // ../../packages/aeg-forge-state/src/list-issue-milestones.ts
2019
+ function issueMilestonesFromIssues(issues) {
2020
+ return issues.filter((i) => i.state === "OPEN").map((i) => ({ issue: i.number, milestoneTitle: i.milestone?.title ?? null }));
2021
+ }
1715
2022
  // ../../packages/aeg-forge-state/src/resolve-repo.ts
1716
2023
  import { execFile as execFile3 } from "node:child_process";
1717
2024
  import { promisify as promisify3 } from "node:util";
@@ -1774,7 +2081,8 @@ var ANCHOR_FIELDS = [
1774
2081
  "PREMISE",
1775
2082
  "TEST-PLAN",
1776
2083
  "EVIDENCE",
1777
- "BEYOND-SURFACE"
2084
+ "BEYOND-SURFACE",
2085
+ "LIVE"
1778
2086
  ];
1779
2087
  function anchoredRegionBounds(body, field) {
1780
2088
  const masked = maskCode(body);
@@ -1975,7 +2283,6 @@ var DERIVABLE_STATUSES = DERIVED_STATUSES.filter((s) => s !== "backlog");
1975
2283
  // ../../packages/aeg-core/src/waiver-label.ts
1976
2284
  var WAIVER_LABEL = label("waiver-docs");
1977
2285
  var WAIVER_LABEL_REVIEW = label("waiver-review");
1978
- var PRINCIPAL_ALLOWLIST = ["daniboomerang"];
1979
2286
  function isPrincipal(login, principalAllowlist) {
1980
2287
  if (login === null)
1981
2288
  return false;
@@ -1994,6 +2301,14 @@ var RULING_ORDINAL_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Ruling ordinal:\s*(\d+)(
1994
2301
  var BRIEF_HASH_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Brief hash:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
1995
2302
  var POLICY_DIGEST_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Policy digest:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
1996
2303
  var BASE_SHA_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Judged base:\s*([0-9a-f]{7,40})(?![A-Za-z0-9])/im;
2304
+ var MANIFEST_VERSION_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Manifest version:\s*(\d+)\s*$/im;
2305
+ var PAUSE_BOUND_RULING_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Pause-bound ruling:\s*(?:(\S+)\|(\S+)\|([0-9a-f]{64})|\(none\))\s*$/im;
2306
+ function extractPauseBoundRuling(comment) {
2307
+ const m = comment.match(PAUSE_BOUND_RULING_PATTERN);
2308
+ if (!m)
2309
+ return;
2310
+ return m[1] ? { rulingId: m[1], pauseId: m[2], contentDigest: m[3] } : null;
2311
+ }
1997
2312
  function firstFiveLines(comment) {
1998
2313
  return comment.split(`
1999
2314
  `).slice(0, 5).join(`
@@ -2087,6 +2402,8 @@ function extractVerdict(comments, valuePattern, missingLabel) {
2087
2402
  danglingNote: `the most recent ${missingLabel} verdict comment carries a VERDICT-shaped line outside the first-five-line read window`
2088
2403
  };
2089
2404
  }
2405
+ const versionMatch = latest.match(MANIFEST_VERSION_PATTERN);
2406
+ const pauseBoundRuling = extractPauseBoundRuling(latest);
2090
2407
  return {
2091
2408
  value: m[1].toUpperCase().replace(/[_-]/g, " "),
2092
2409
  headSha: extractHeadSha(latest),
@@ -2095,6 +2412,8 @@ function extractVerdict(comments, valuePattern, missingLabel) {
2095
2412
  briefHash: extractBriefHash(latest),
2096
2413
  policyDigest: extractPolicyDigest(latest),
2097
2414
  baseSha: extractBaseSha(latest),
2415
+ ...versionMatch ? { manifestVersion: Number.parseInt(versionMatch[1], 10) } : {},
2416
+ ...pauseBoundRuling === undefined ? {} : { pauseBoundRuling },
2098
2417
  findingSeverities: extractFindingSeverities(latest),
2099
2418
  danglingNote: null
2100
2419
  };
@@ -2105,6 +2424,16 @@ function extractCodeReviewVerdict(comments) {
2105
2424
  function extractSecurityReviewVerdict(comments) {
2106
2425
  return extractVerdict(comments, /^[ \t]*(?:\*{1,3}|_{1,3})?VERDICT:\s*(PASS|FAIL)(?![A-Za-z0-9])/im, "security-review");
2107
2426
  }
2427
+
2428
+ // ../../packages/aeg-core/src/review-status.ts
2429
+ var DEVELOPER_ROUND_MARKER = /<!--\s*aeg:developer:round-(\d+)\s*-->/i;
2430
+ function parseDeveloperRoundMarker(body) {
2431
+ const m = body.match(DEVELOPER_ROUND_MARKER);
2432
+ if (!m)
2433
+ return null;
2434
+ const n = Number(m[1]);
2435
+ return Number.isFinite(n) ? n : null;
2436
+ }
2108
2437
  // ../../packages/aeg-core/src/report-tokens.ts
2109
2438
  var DASH_LOOKALIKES = {
2110
2439
  "-": "‑",
@@ -2800,14 +3129,14 @@ function checkTestPlan(prBody) {
2800
3129
  const region = located.found ? located.section : prBody;
2801
3130
  if (TEST_PLAN_UNIT_TESTS_ONLY_RE.test(region))
2802
3131
  return { status: "pass", errors: [] };
2803
- if (/\*\*\[(?:agent|principal)\]\*\*/.test(region))
3132
+ if (/\*\*\[(?:agent|principal|live)\]\*\*/.test(region))
2804
3133
  return { status: "pass", errors: [] };
2805
3134
  if (located.found && extractFencedBlocks(region).length > 0)
2806
3135
  return { status: "pass", errors: [] };
2807
3136
  return {
2808
3137
  status: "fail",
2809
3138
  errors: [
2810
- "brief-validation Test Plan: no Test Plan section found — expected `Test Plan: unit-tests-only`, a fenced `[agent]` command list, or at least one `**[agent]**`/`**[principal]**`-tagged checklist item."
3139
+ "brief-validation Test Plan: no Test Plan section found — expected `Test Plan: unit-tests-only`, a fenced `[agent]` command list, or at least one `**[agent]**`/`**[principal]**`/`**[live]**`-tagged item."
2811
3140
  ]
2812
3141
  };
2813
3142
  }
@@ -3429,6 +3758,375 @@ function checkPrReportDensity(prBody) {
3429
3758
  const results = [checkDecisionsDensity(prBody), checkScopeDensity(prBody)];
3430
3759
  return { errors: results.flatMap((r) => r.errors) };
3431
3760
  }
3761
+ // ../../packages/aeg-core/src/prose-rules.ts
3762
+ var RETIRED_GLOBAL_EXEMPTIONS = [
3763
+ "docs/decisions-legacy.md",
3764
+ "apps/herald-ai/docs/",
3765
+ "apps/vada-ai/docs/",
3766
+ "aeg-root/tranches/completed/",
3767
+ "packages/aeg-core/src/docs/published-prose",
3768
+ "packages/aeg-core/src/retired-vocabulary.test.ts",
3769
+ "packages/aeg-core/src/retired-vocabulary.ts",
3770
+ "/fixtures/",
3771
+ "/node_modules/",
3772
+ "/.next/",
3773
+ "/.turbo/"
3774
+ ];
3775
+ var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
3776
+ var TRANCHE_MODEL_FILE = "/tranche-model.md";
3777
+ var RETIRED_PATTERN_EXEMPTIONS = {
3778
+ [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
3779
+ [String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`]: [
3780
+ "docs-index.md",
3781
+ "apps/vada-ai/specs/legacy/README.md",
3782
+ "apps/vada-ai/specs/vada-product-spec.md",
3783
+ "apps/vada-ai/web/CLAUDE.md",
3784
+ "apps/vada-ai/CLAUDE.md"
3785
+ ],
3786
+ "decisions-legacy": [
3787
+ "packages/aeg-core/src/file-classify.ts",
3788
+ "packages/aeg-core/src/file-classify.test.ts",
3789
+ "packages/aeg-core/src/pr-tier.test.ts",
3790
+ "docs-index.md",
3791
+ ".claude/skills/database/SKILL.md",
3792
+ ".claude/skills/vada-architecture/SKILL.md",
3793
+ "apps/vada-ai/specs/vada-byok-principles.md",
3794
+ "apps/vada-ai/web/CLAUDE.md",
3795
+ "apps/vada-ai/CLAUDE.md"
3796
+ ],
3797
+ CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
3798
+ ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
3799
+ };
3800
+ var retiredPatterns = [
3801
+ String.raw`\bD-[0-9]{3}\b`,
3802
+ "D-(###|NNN|nnn|xxx)",
3803
+ "decision (entry|logged)",
3804
+ "decision-log entry",
3805
+ "decision log entry",
3806
+ "decision log(s|ged|ging)?([^a-z]|$)",
3807
+ "decision-log",
3808
+ "decision entr",
3809
+ "decisions? (are |is )?logged",
3810
+ "log entries",
3811
+ String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`,
3812
+ "decisions-legacy",
3813
+ "CONTRADICTION",
3814
+ "assumes Tier 3",
3815
+ "Lock: ?YES",
3816
+ "Lock: ?NO",
3817
+ "lock approvals?",
3818
+ "approves locks",
3819
+ "Conforms to lock",
3820
+ "Challenges lock",
3821
+ "checkDecisionNumbersFresh",
3822
+ String.raw`roles/team-leader\.md`,
3823
+ String.raw`\(,`,
3824
+ String.raw`,\)`,
3825
+ String.raw`\(\.\)`,
3826
+ ...PLAN_ON_DISK_PATTERNS
3827
+ ];
3828
+ var published = [
3829
+ ["decision-id", "a decision id", /\bD-\d{3,}\b/],
3830
+ ["section-ref", "a section reference", /§/],
3831
+ ["forge-number", "a forge number", /#\d+/],
3832
+ ["retired-name", "the retired public name", /\bAEG\b/],
3833
+ ["tranche-slug", "a tranche slug", /\b[a-z][a-z0-9]*(?:-[a-z0-9]+)+-v\d+\b/],
3834
+ [
3835
+ "label-vocabulary",
3836
+ "forge label vocabulary",
3837
+ /(?:vinaya\/)?\b(?:tranche|iteration|tier|needs|waiver|project|aeg):(?![/\s]|$)/
3838
+ ],
3839
+ ["internal-path", "a repo-internal path", /\b(?:packages|apps|aeg-root|tools|scripts)\//],
3840
+ ["internal-path", "a repo-internal path", /\.(?:claude|husky|github)\//],
3841
+ [
3842
+ "internal-path",
3843
+ "a repo-internal file",
3844
+ /(?:^|[\s(`"'[])[\w.-]+(?:\/[\w.-]+)*\.(?:ts|tsx|js|jsx|mjs|cjs|sh|ya?ml|json|md)\b/
3845
+ ]
3846
+ ];
3847
+ var DEFAULT_PROSE_RULES = [
3848
+ {
3849
+ id: "forge-number",
3850
+ group: "reader-resolvable",
3851
+ scopes: ["ships", "reader-facing", "spec"],
3852
+ patterns: { prose: /#[0-9]{2,4}/g },
3853
+ flags: ["global"],
3854
+ message: "a forge number",
3855
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
3856
+ exemptions: []
3857
+ },
3858
+ {
3859
+ id: "tranche-slug",
3860
+ group: "reader-resolvable",
3861
+ scopes: ["ships", "reader-facing", "product", "spec"],
3862
+ patterns: { prose: /[a-z][a-z-]+-v[0-9]/g },
3863
+ flags: ["global"],
3864
+ message: "an internal tranche slug",
3865
+ severity: { ships: "warning", "reader-facing": "warning", product: "error", spec: "error" },
3866
+ exemptions: []
3867
+ },
3868
+ {
3869
+ id: "task-number",
3870
+ group: "reader-resolvable",
3871
+ scopes: ["spec"],
3872
+ patterns: { prose: /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi },
3873
+ flags: ["global", "ignore-case"],
3874
+ message: "a task number",
3875
+ severity: { spec: "error" },
3876
+ exemptions: []
3877
+ },
3878
+ {
3879
+ id: "source-comment-tranche-slug",
3880
+ group: "reader-resolvable",
3881
+ scopes: ["source-comment"],
3882
+ patterns: { comment: /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g },
3883
+ flags: ["global"],
3884
+ message: "a tranche-slug citation",
3885
+ severity: { "source-comment": "warning" },
3886
+ exemptions: []
3887
+ },
3888
+ {
3889
+ id: "source-comment-forge-number",
3890
+ group: "reader-resolvable",
3891
+ scopes: ["source-comment"],
3892
+ patterns: { comment: /#[0-9]{2,}/g },
3893
+ flags: ["global"],
3894
+ message: "a forge-number citation",
3895
+ severity: { "source-comment": "warning" },
3896
+ exemptions: []
3897
+ },
3898
+ {
3899
+ id: "legacy-batch-name",
3900
+ group: "reader-resolvable",
3901
+ scopes: ["ships", "reader-facing", "spec"],
3902
+ patterns: {},
3903
+ flags: ["built-in"],
3904
+ message: "an internal tranche slug",
3905
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
3906
+ exemptions: [],
3907
+ builtIn: true
3908
+ },
3909
+ {
3910
+ id: "coined-term",
3911
+ group: "reader-resolvable",
3912
+ scopes: ["ships", "reader-facing"],
3913
+ patterns: {},
3914
+ flags: ["built-in"],
3915
+ message: "uses coined term without defining it inline or linking the glossary",
3916
+ severity: { ships: "warning", "reader-facing": "warning" },
3917
+ exemptions: [],
3918
+ builtIn: true
3919
+ },
3920
+ ...retiredPatterns.map((pattern, index) => ({
3921
+ id: `retired-vocabulary-${index + 1}`,
3922
+ group: "retired-vocabulary",
3923
+ scopes: ["repository"],
3924
+ patterns: { repository: pattern },
3925
+ flags: [],
3926
+ message: "retired vocabulary",
3927
+ severity: { repository: "error" },
3928
+ exemptions: RETIRED_GLOBAL_EXEMPTIONS,
3929
+ patternExemptions: RETIRED_PATTERN_EXEMPTIONS
3930
+ })),
3931
+ ...published.map(([id, message, pattern]) => ({
3932
+ id,
3933
+ group: "published-prose",
3934
+ scopes: ["published"],
3935
+ patterns: { published: pattern },
3936
+ flags: [],
3937
+ message,
3938
+ severity: { published: "error" },
3939
+ exemptions: [".worktrees/task/<tranche>/<n>", "task/<tranche>/<n>", ".worktrees/"]
3940
+ }))
3941
+ ];
3942
+ var rulesForGroup = (group) => DEFAULT_PROSE_RULES.filter((rule) => rule.group === group);
3943
+ var RESOLVABLE_SCOPES = ["ships", "reader-facing", "product", "spec", "source-comment"];
3944
+ var RETIRED_SCOPES = ["repository"];
3945
+ var CONFIGURABLE_PROSE_SCOPES = [...RESOLVABLE_SCOPES, ...RETIRED_SCOPES];
3946
+ function groupOfScope(scope) {
3947
+ if (RESOLVABLE_SCOPES.includes(scope))
3948
+ return "reader-resolvable";
3949
+ if (RETIRED_SCOPES.includes(scope))
3950
+ return "retired-vocabulary";
3951
+ return;
3952
+ }
3953
+ var CONFIGURED_PROSE_FLAGS = ["i", "u"];
3954
+ var CONFIGURED_PATTERN_MAX_LENGTH = 200;
3955
+ var CONFIGURABLE_DEFAULT_RULES = DEFAULT_PROSE_RULES.filter((rule) => rule.group !== "published-prose");
3956
+ function allowedScopesFor(rule) {
3957
+ if (rule.builtIn)
3958
+ return rule.scopes;
3959
+ return rule.group === "retired-vocabulary" ? RETIRED_SCOPES : RESOLVABLE_SCOPES;
3960
+ }
3961
+ function normalizeRepoPath(entry) {
3962
+ let out = entry.replace(/\\/g, "/");
3963
+ while (out.startsWith("./"))
3964
+ out = out.slice(2);
3965
+ out = out.replace(/\/{2,}/g, "/");
3966
+ while (out.endsWith("/"))
3967
+ out = out.slice(0, -1);
3968
+ return out;
3969
+ }
3970
+ function isConfiguredExempt(path, exempt, repoRoot) {
3971
+ if (exempt.length === 0)
3972
+ return false;
3973
+ const root = repoRoot === undefined ? undefined : normalizeRepoPath(repoRoot);
3974
+ let rel = normalizeRepoPath(path);
3975
+ if (root && rel.startsWith(`${root}/`))
3976
+ rel = rel.slice(root.length + 1);
3977
+ return exempt.some((entry) => {
3978
+ const e = normalizeRepoPath(entry);
3979
+ return rel === e || rel.startsWith(`${e}/`);
3980
+ });
3981
+ }
3982
+ function ruleReads(set, rule, path) {
3983
+ return !isConfiguredExempt(path, set.exempt, set.repoRoot) && !isConfiguredExempt(path, rule.exempt, set.repoRoot);
3984
+ }
3985
+ var RESOLVABLE_RUN_ORDER = [
3986
+ "forge-number",
3987
+ "tranche-slug",
3988
+ "legacy-batch-name",
3989
+ "task-number",
3990
+ "source-comment-tranche-slug",
3991
+ "source-comment-forge-number",
3992
+ "coined-term"
3993
+ ];
3994
+ var REPORT_GROUPS = { "task-number": 2, "legacy-batch-name": 2 };
3995
+ function scopeDefaultSeverity(scope, sourceCommentSeverity) {
3996
+ if (scope === "source-comment")
3997
+ return sourceCommentSeverity ?? "warning";
3998
+ if (scope === "repository")
3999
+ return "error";
4000
+ return "warning";
4001
+ }
4002
+ function applySeverity(scopes, base, setting) {
4003
+ const out = {};
4004
+ for (const scope of scopes) {
4005
+ const configured = typeof setting === "string" ? setting : setting?.[scope];
4006
+ const value = configured ?? base[scope];
4007
+ if (value !== undefined)
4008
+ out[scope] = value;
4009
+ }
4010
+ return out;
4011
+ }
4012
+ function defaultPatternFor(rule) {
4013
+ const cache = new Map;
4014
+ return (scope) => {
4015
+ if (cache.has(scope))
4016
+ return cache.get(scope) ?? null;
4017
+ const own = rule.patterns[scope] ?? (scope === "source-comment" ? rule.patterns.comment : rule.patterns.prose) ?? Object.values(rule.patterns)[0];
4018
+ const compiled = own === undefined ? null : own instanceof RegExp ? own : new RegExp(own);
4019
+ cache.set(scope, compiled);
4020
+ return compiled;
4021
+ };
4022
+ }
4023
+ function customPatternFor(rule, global) {
4024
+ const cache = new Map;
4025
+ return (scope) => {
4026
+ if (cache.has(scope))
4027
+ return cache.get(scope) ?? null;
4028
+ const source = rule.patterns?.[scope] ?? rule.pattern;
4029
+ const compiled = source === undefined ? null : new RegExp(source, `${rule.flags ?? ""}${global ? "g" : ""}`);
4030
+ cache.set(scope, compiled);
4031
+ return compiled;
4032
+ };
4033
+ }
4034
+ function resolveProseRules(config = undefined, options = {}) {
4035
+ const rules = [];
4036
+ const defaults = config?.defaults ?? {};
4037
+ for (const rule of CONFIGURABLE_DEFAULT_RULES) {
4038
+ const override = defaults[rule.id];
4039
+ if (override === "off")
4040
+ continue;
4041
+ const group = rule.group;
4042
+ const scopes = override?.scopes ?? rule.scopes;
4043
+ const base = {};
4044
+ for (const scope of scopes) {
4045
+ base[scope] = scope === "source-comment" ? options.sourceCommentSeverity ?? rule.severity[scope] ?? "warning" : rule.severity[scope] ?? scopeDefaultSeverity(scope, options.sourceCommentSeverity);
4046
+ }
4047
+ rules.push({
4048
+ id: rule.id,
4049
+ group,
4050
+ custom: false,
4051
+ builtIn: rule.builtIn === true,
4052
+ scopes,
4053
+ message: rule.message,
4054
+ severity: applySeverity(scopes, base, override?.severity),
4055
+ exempt: override?.exempt ?? [],
4056
+ substringExempt: rule.exemptions,
4057
+ reportGroup: REPORT_GROUPS[rule.id],
4058
+ patternFor: defaultPatternFor(rule)
4059
+ });
4060
+ }
4061
+ for (const rule of config?.custom ?? []) {
4062
+ const group = groupOfScope(rule.scopes[0] ?? "") ?? "reader-resolvable";
4063
+ const base = {};
4064
+ for (const scope of rule.scopes)
4065
+ base[scope] = scopeDefaultSeverity(scope, options.sourceCommentSeverity);
4066
+ rules.push({
4067
+ id: rule.id,
4068
+ group,
4069
+ custom: true,
4070
+ builtIn: false,
4071
+ scopes: rule.scopes,
4072
+ message: rule.means,
4073
+ severity: applySeverity(rule.scopes, base, rule.severity),
4074
+ exempt: rule.exempt ?? [],
4075
+ substringExempt: [],
4076
+ patternFor: customPatternFor(rule, group === "reader-resolvable")
4077
+ });
4078
+ }
4079
+ if (options.decisionRecordsPath !== undefined)
4080
+ rules.push(decisionRecordCitationRule(options.decisionRecordsPath));
4081
+ const order = (rule) => {
4082
+ const at = RESOLVABLE_RUN_ORDER.indexOf(rule.id);
4083
+ return rule.custom || at === -1 ? RESOLVABLE_RUN_ORDER.length : at;
4084
+ };
4085
+ const resolvable = rules.filter((rule) => rule.group === "reader-resolvable");
4086
+ const sorted = resolvable.map((rule, index) => ({ rule, index })).sort((a, b) => order(a.rule) - order(b.rule) || a.index - b.index).map(({ rule }) => rule);
4087
+ return {
4088
+ rules: [...sorted, ...rules.filter((rule) => rule.group === "retired-vocabulary")],
4089
+ exempt: config?.exempt ?? [],
4090
+ repoRoot: options.repoRoot
4091
+ };
4092
+ }
4093
+ function rulesOfGroup(set, group) {
4094
+ return set.rules.filter((rule) => rule.group === group);
4095
+ }
4096
+ function rulesInScope(set, scope) {
4097
+ return set.rules.filter((rule) => rule.scopes.includes(scope));
4098
+ }
4099
+ var DEFAULT_PROSE_RULE_SET = resolveProseRules();
4100
+ var DECISION_RECORD_CITATION_ID = "decision-record-citation";
4101
+ var DECISION_RECORD_CITATION_SCOPES = ["ships", "product", "spec", "source-comment"];
4102
+ var DECISION_RECORD_CITATION_MESSAGE = "a decision-record number";
4103
+ function escapeRegExp(text) {
4104
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4105
+ }
4106
+ function decisionRecordCitationPattern(decisionRecordsPath) {
4107
+ const folder = escapeRegExp(normalizeRepoPath(decisionRecordsPath));
4108
+ return new RegExp(String.raw`\bADR[- ]?[0-9]+\b|(?<![A-Za-z0-9_-])${folder}/[0-9]+[A-Za-z0-9._-]*`, "g");
4109
+ }
4110
+ function decisionRecordCitationRule(decisionRecordsPath) {
4111
+ const folder = normalizeRepoPath(decisionRecordsPath);
4112
+ const pattern = decisionRecordCitationPattern(folder);
4113
+ const severity = {};
4114
+ for (const scope of DECISION_RECORD_CITATION_SCOPES)
4115
+ severity[scope] = "error";
4116
+ return {
4117
+ id: DECISION_RECORD_CITATION_ID,
4118
+ group: "reader-resolvable",
4119
+ custom: false,
4120
+ builtIn: false,
4121
+ scopes: DECISION_RECORD_CITATION_SCOPES,
4122
+ message: DECISION_RECORD_CITATION_MESSAGE,
4123
+ severity,
4124
+ exempt: [folder],
4125
+ substringExempt: [],
4126
+ patternFor: () => pattern
4127
+ };
4128
+ }
4129
+
3432
4130
  // ../../packages/aeg-core/src/reader-resolvable-prose.ts
3433
4131
  var PRODUCT_SLUG_SCOPE = [
3434
4132
  "apps/cli/src",
@@ -3440,8 +4138,8 @@ var PRODUCT_SLUG_SCOPE = [
3440
4138
  function isUnderOrEqual(path, prefix) {
3441
4139
  return path === prefix || path.startsWith(`${prefix}/`);
3442
4140
  }
3443
- function isProductScopeFile(path) {
3444
- return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
4141
+ function isProductScopeFile(path, productPaths) {
4142
+ return productPaths.some((prefix) => isUnderOrEqual(path, normalizeRepoPath(prefix)));
3445
4143
  }
3446
4144
  var SHIPS_PREFIX = "aeg-root/";
3447
4145
  function shipsArchivePrefix(shipsPrefix) {
@@ -3449,13 +4147,7 @@ function shipsArchivePrefix(shipsPrefix) {
3449
4147
  }
3450
4148
  var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
3451
4149
  function normalizeSpecPath(entry) {
3452
- let out = entry.replace(/\\/g, "/");
3453
- while (out.startsWith("./"))
3454
- out = out.slice(2);
3455
- out = out.replace(/\/{2,}/g, "/");
3456
- while (out.endsWith("/"))
3457
- out = out.slice(0, -1);
3458
- return out;
4150
+ return normalizeRepoPath(entry);
3459
4151
  }
3460
4152
  function isSpecFile2(path, specPaths) {
3461
4153
  if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
@@ -3467,7 +4159,7 @@ function isSpecFile2(path, specPaths) {
3467
4159
  function isClaudeMdFile(path) {
3468
4160
  return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
3469
4161
  }
3470
- function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
4162
+ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS, productPaths = PRODUCT_SLUG_SCOPE) {
3471
4163
  if (path.startsWith(shipsPrefix)) {
3472
4164
  return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
3473
4165
  }
@@ -3478,7 +4170,7 @@ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPr
3478
4170
  return "internal";
3479
4171
  if (isSpecFile2(path, specPaths))
3480
4172
  return "spec";
3481
- if (isProductScopeFile(path))
4173
+ if (isProductScopeFile(path, productPaths))
3482
4174
  return "product";
3483
4175
  return null;
3484
4176
  }
@@ -3503,9 +4195,16 @@ function lineAt(content, index) {
3503
4195
  }
3504
4196
  return line;
3505
4197
  }
3506
- var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
3507
- var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
3508
- var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
4198
+ var readerRules = rulesForGroup("reader-resolvable");
4199
+ var readerPattern = (id, scope = "prose") => {
4200
+ const pattern = readerRules.find((rule) => rule.id === id)?.patterns[scope];
4201
+ if (!(pattern instanceof RegExp))
4202
+ throw new Error(`default prose rule ${id} has no ${scope} pattern`);
4203
+ return pattern;
4204
+ };
4205
+ var FORGE_NUMBER_PATTERN = readerPattern("forge-number");
4206
+ var TRANCHE_SLUG_VN_PATTERN = readerPattern("tranche-slug");
4207
+ var TASK_NUMBER_PATTERN = readerPattern("task-number");
3509
4208
  function legacySlugPattern(legacySlugs) {
3510
4209
  if (legacySlugs.length === 0)
3511
4210
  return null;
@@ -3515,48 +4214,61 @@ function legacySlugPattern(legacySlugs) {
3515
4214
  function specGrandfatherPaths(specGrandfather) {
3516
4215
  return Array.isArray(specGrandfather) ? [...specGrandfather] : Object.keys(specGrandfather);
3517
4216
  }
3518
- function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4217
+ var REFERENCE_CLASSES = new Set(["ships", "reader-facing", "product", "spec"]);
4218
+ function referenceRulesFor(set, cls) {
4219
+ return rulesInScope(set, cls).filter((rule) => rule.group === "reader-resolvable" && rule.id !== "coined-term");
4220
+ }
4221
+ function citations(pattern, text, group) {
4222
+ const out = [];
4223
+ const re = pattern.global ? pattern : new RegExp(pattern.source, `${pattern.flags}g`);
4224
+ re.lastIndex = 0;
4225
+ let match = re.exec(text);
4226
+ while (match !== null) {
4227
+ if (match[0] === "") {
4228
+ re.lastIndex++;
4229
+ } else {
4230
+ const cited = group !== undefined ? match[group] ?? match[0] : match[0];
4231
+ out.push({ cited, index: match.index + match[0].indexOf(cited) });
4232
+ }
4233
+ match = re.exec(text);
4234
+ }
4235
+ re.lastIndex = 0;
4236
+ return out;
4237
+ }
4238
+ function customMessage(rule, cited) {
4239
+ return `${rule.id}: ${rule.message} ("${cited}")`;
4240
+ }
4241
+ function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS, options = {}) {
4242
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4243
+ const productPaths = options.productPaths ?? PRODUCT_SLUG_SCOPE;
3519
4244
  const findings = [];
3520
4245
  const legacyPattern = legacySlugPattern(legacySlugs);
3521
4246
  const grandfatheredWhole = new Set(Array.isArray(specGrandfather) ? specGrandfather : []);
3522
4247
  const limits = new Map(Array.isArray(specGrandfather) ? [] : Object.entries(specGrandfather));
3523
- const patterns = [
3524
- { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
3525
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
3526
- ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
3527
- ];
3528
- const productPatterns = [
3529
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
3530
- ];
3531
- const specPatterns = [
3532
- ...patterns,
3533
- { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
3534
- ];
3535
4248
  for (const file of files) {
3536
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
3537
- if (!cls || cls === "internal")
3538
- continue;
3539
- if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
4249
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths, productPaths);
4250
+ if (!cls || !REFERENCE_CLASSES.has(cls))
3540
4251
  continue;
3541
4252
  if (cls === "spec" && grandfatheredWhole.has(file.path))
3542
4253
  continue;
3543
- const blocking = cls === "product" || cls === "spec";
3544
4254
  const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
3545
- const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
3546
4255
  const fileFindings = [];
3547
- for (const { pattern, what, group } of patternsToRun) {
3548
- pattern.lastIndex = 0;
3549
- let match = pattern.exec(scrubbed);
3550
- while (match !== null) {
3551
- const cited = group !== undefined ? match[group] ?? match[0] : match[0];
3552
- const citedIndex = match.index + match[0].indexOf(cited);
4256
+ for (const rule of referenceRulesFor(set, cls)) {
4257
+ if (!ruleReads(set, rule, file.path))
4258
+ continue;
4259
+ const pattern = !rule.custom && rule.id === "legacy-batch-name" ? legacyPattern : rule.patternFor(cls);
4260
+ if (!pattern)
4261
+ continue;
4262
+ const blocking = rule.severity[cls] === "error";
4263
+ const what = cls === "product" ? `${rule.message} in product code` : rule.message;
4264
+ for (const { cited, index } of citations(pattern, scrubbed, rule.custom ? undefined : rule.reportGroup)) {
3553
4265
  fileFindings.push({
3554
4266
  file: file.path,
3555
- line: lineAt(scrubbed, citedIndex),
3556
- message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
3557
- blocking
4267
+ line: lineAt(scrubbed, index),
4268
+ message: rule.custom ? customMessage(rule, cited) : `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4269
+ blocking,
4270
+ rule: rule.id
3558
4271
  });
3559
- match = pattern.exec(scrubbed);
3560
4272
  }
3561
4273
  }
3562
4274
  const limit = cls === "spec" ? limits.get(file.path) : undefined;
@@ -3597,11 +4309,17 @@ function definesOrLinksGlossary(content, term) {
3597
4309
  return true;
3598
4310
  return /docs\/glossary|glossary\.md/i.test(content);
3599
4311
  }
3600
- function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
4312
+ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, options = {}) {
3601
4313
  const findings = [];
4314
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4315
+ const rule = set.rules.find((r) => !r.custom && r.id === "coined-term");
4316
+ if (!rule)
4317
+ return findings;
3602
4318
  for (const file of files) {
3603
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3604
- if (!cls || !SWEPT_CLASSES.has(cls))
4319
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, DEFAULT_SPEC_PATHS, options.productPaths);
4320
+ if (!cls || !SWEPT_CLASSES.has(cls) || !rule.scopes.includes(cls))
4321
+ continue;
4322
+ if (!ruleReads(set, rule, file.path))
3605
4323
  continue;
3606
4324
  const scrubbed = stripNonProse(file.path, file.content);
3607
4325
  for (const term of glossaryTerms) {
@@ -3614,14 +4332,15 @@ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, read
3614
4332
  file: file.path,
3615
4333
  line,
3616
4334
  message: `uses coined term "${term}" without defining it inline or linking the glossary`,
3617
- blocking: false
4335
+ blocking: rule.severity[cls] === "error",
4336
+ rule: rule.id
3618
4337
  });
3619
4338
  }
3620
4339
  }
3621
4340
  return findings;
3622
4341
  }
3623
- var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
3624
- var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
4342
+ var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = readerPattern("source-comment-tranche-slug", "comment");
4343
+ var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = readerPattern("source-comment-forge-number", "comment");
3625
4344
  function extractComments(path, content) {
3626
4345
  if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
3627
4346
  return content.replace(/[^\n]/g, "");
@@ -3718,39 +4437,40 @@ function extractComments(path, content) {
3718
4437
  }
3719
4438
  return out;
3720
4439
  }
3721
- function checkSourceComments(files, allowlist = []) {
4440
+ function checkSourceComments(files, allowlist = [], options = {}) {
3722
4441
  const findings = [];
3723
4442
  const allowed = new Set(allowlist);
3724
- const patterns = [
3725
- { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
3726
- { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
3727
- ];
4443
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4444
+ const rules = rulesInScope(set, "source-comment").filter((rule) => rule.group === "reader-resolvable");
3728
4445
  for (const file of files) {
3729
4446
  if (!file.path.endsWith(".ts"))
3730
4447
  continue;
3731
4448
  if (allowed.has(file.path))
3732
4449
  continue;
3733
4450
  const comments = extractComments(file.path, file.content);
3734
- for (const { pattern, what } of patterns) {
3735
- pattern.lastIndex = 0;
3736
- let match = pattern.exec(comments);
3737
- while (match !== null) {
4451
+ for (const rule of rules) {
4452
+ if (!ruleReads(set, rule, file.path))
4453
+ continue;
4454
+ const pattern = rule.patternFor("source-comment");
4455
+ if (!pattern)
4456
+ continue;
4457
+ for (const { cited, index } of citations(pattern, comments)) {
3738
4458
  findings.push({
3739
4459
  file: file.path,
3740
- line: lineAt(comments, match.index),
3741
- message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
3742
- blocking: false
4460
+ line: lineAt(comments, index),
4461
+ message: rule.custom ? customMessage(rule, cited) : `comment cites ${rule.message} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4462
+ blocking: rule.severity["source-comment"] === "error",
4463
+ rule: rule.id
3743
4464
  });
3744
- match = pattern.exec(comments);
3745
4465
  }
3746
4466
  }
3747
4467
  }
3748
4468
  return findings;
3749
4469
  }
3750
- function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4470
+ function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS, options = {}) {
3751
4471
  return [
3752
- ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
3753
- ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
4472
+ ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths, options),
4473
+ ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix, options)
3754
4474
  ];
3755
4475
  }
3756
4476
  function parseGlossaryTerms(glossaryContent) {
@@ -3953,8 +4673,19 @@ function checkDocClaims(files, fileReader) {
3953
4673
  };
3954
4674
  }
3955
4675
 
3956
- // ../../packages/aeg-core/src/issue-validation.ts
3957
- function hasRationaleField(body, labelPattern) {
4676
+ // ../../packages/aeg-core/src/protected-paths.ts
4677
+ import { posix as posixPath } from "node:path";
4678
+ var PROTECTED_ADMIN_PATHS = ["vinaya.config.json", ".vinaya/doc-owners", ".github/", "aeg-root/"];
4679
+ function normalizeTouchedPath(path) {
4680
+ return posixPath.resolve("/", path.replace(/\\/g, "/")).replace(/^\/+/, "");
4681
+ }
4682
+ function isProtectedAdminPath(path) {
4683
+ const normalized = normalizeTouchedPath(path);
4684
+ return PROTECTED_ADMIN_PATHS.some((prefix) => normalized === prefix || normalized.startsWith(prefix));
4685
+ }
4686
+
4687
+ // ../../packages/aeg-core/src/issue-validation.ts
4688
+ function hasRationaleField(body, labelPattern) {
3958
4689
  const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
3959
4690
  return re.test(body);
3960
4691
  }
@@ -4072,13 +4803,20 @@ function globCoversPath(glob, path) {
4072
4803
  return !p.includes("/");
4073
4804
  return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
4074
4805
  }
4806
+ function surfaceEntryResolves(entry, resolvesToFile, pinnedFiles) {
4807
+ if (resolvesToFile(entry))
4808
+ return true;
4809
+ const directory = entry.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
4810
+ return pinnedFiles.some((path) => path.startsWith(`${directory}/`));
4811
+ }
4075
4812
  function checkSurfaceGlobsResolve(body, resolvesToFile) {
4076
4813
  const surface = parseIssueSurface(body);
4077
4814
  if (!surface.ok)
4078
4815
  return { status: "pass", errors: [] };
4816
+ const pinnedFiles = boundaryPinnedFiles(body);
4079
4817
  const errors = [];
4080
4818
  for (const glob of surface.value.in) {
4081
- if (!resolvesToFile(glob)) {
4819
+ if (!surfaceEntryResolves(glob, resolvesToFile, pinnedFiles)) {
4082
4820
  errors.push(`issue-validation Surface: \`${glob}\` in \`## Surface\`'s \`in:\` list matches no tracked file — a Surface that cannot resolve cannot render a brief's file list.`);
4083
4821
  }
4084
4822
  }
@@ -4108,6 +4846,14 @@ function recordedBeyondSurfacePaths(body) {
4108
4846
  return paths;
4109
4847
  }
4110
4848
  function checkSurfaceScope(changedFiles, surface, recorded) {
4849
+ for (const path of changedFiles) {
4850
+ if (!isProtectedAdminPath(path))
4851
+ continue;
4852
+ const normalized = normalizeTouchedPath(path);
4853
+ if (!surface.in.some((glob) => globCoversPath(glob, normalized))) {
4854
+ return { ok: false, violation: { path, reason: "protected" } };
4855
+ }
4856
+ }
4111
4857
  const listed = new Set(recorded);
4112
4858
  const violation = beyondSurfacePaths(changedFiles, surface).find((entry) => !listed.has(entry.path));
4113
4859
  return violation ? { ok: false, violation } : { ok: true };
@@ -4163,12 +4909,22 @@ function checkPartsCiteDefinedObjectives(body) {
4163
4909
  }
4164
4910
  return { status: errors.length > 0 ? "fail" : "pass", errors };
4165
4911
  }
4912
+ var ISSUE_LIVE_LINE_RE = /^-\s*\*{2}\[live\]\*{2}(.*)$/gim;
4913
+ function liveCommand(text) {
4914
+ const trimmed = text.trim();
4915
+ const span = /^(`+)(.+)\1$/.exec(trimmed);
4916
+ return span ? span[2].trim() : trimmed;
4917
+ }
4918
+ function liveItemsIn(region) {
4919
+ return [...region.matchAll(ISSUE_LIVE_LINE_RE)].map((m) => liveCommand(m[1] ?? "")).filter(Boolean);
4920
+ }
4921
+ function parseLiveTestPlanItems(body) {
4922
+ const located = locateTestPlanSection(body);
4923
+ return located.found ? liveItemsIn(located.section) : [];
4924
+ }
4166
4925
  function isTaskIssueLabelSet(labels) {
4167
4926
  return hasLabel("tranche", labels);
4168
4927
  }
4169
- function checkTrancheLabelPresence(_body, _labels) {
4170
- return { status: "pass", errors: [] };
4171
- }
4172
4928
  function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
4173
4929
  if (!isTaskIssueLabelSet(labels))
4174
4930
  return { status: "pass", errors: [] };
@@ -4184,6 +4940,7 @@ function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTi
4184
4940
  };
4185
4941
  }
4186
4942
  var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
4943
+ var PATH_TEXT = (body) => stripCode(body, { inlineSpans: "keep" });
4187
4944
  function isControlCodePoint(codePoint) {
4188
4945
  return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
4189
4946
  }
@@ -4244,8 +5001,14 @@ function checkProjectsRegistered(body, _labels, registeredNames) {
4244
5001
  }
4245
5002
  return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
4246
5003
  }
5004
+ function rationaleFieldText(text, labelPattern) {
5005
+ const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})[^\\n]*\\n?([\\s\\S]*?)(?=\\n\\s*(?:\\*\\*[A-Z]|#{1,4}\\s)|(?![\\s\\S]))`, "im");
5006
+ const m = re.exec(text);
5007
+ return m ? m[0] : "";
5008
+ }
4247
5009
  var DOC_PATH_RE = /(?:(?:aeg-root|apps|packages|specs|docs|tools|\.claude|\.github)\/[\w./@-]*\.(?:md|mdx)|\.claude\/(?:skills|rules)\/[\w./-]+|\b(?:docs-index|decisions|projects|state-machine|enforcement|process|README|CLAUDE)\.md\b|\b[\w-]+-(?:spec|decisions|backlog)\.md\b)/i;
4248
5010
  var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
5011
+ var RATIONALE_PATH_RE_GLOBAL = /`([\w.@-]+(?:\/[\w.@-]+)+)`/g;
4249
5012
  function normalizeEdgeId(s) {
4250
5013
  const qualified = splitSlugQualifiedEdge(s);
4251
5014
  return (qualified ? qualified.bareId : s).replace(/^#/, "").trim();
@@ -4253,6 +5016,15 @@ function normalizeEdgeId(s) {
4253
5016
  function edgesNameEachOther(a, b) {
4254
5017
  return a.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(b.ref)) || b.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(a.ref));
4255
5018
  }
5019
+ var BOUNDARY_OUT_RE = /\bOut\s*:\s*([\s\S]*)$/im;
5020
+ function boundaryOutText(body) {
5021
+ const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
5022
+ const m = BOUNDARY_OUT_RE.exec(boundary);
5023
+ return m ? m[1] : "";
5024
+ }
5025
+ function namedPathsIn(text) {
5026
+ return [...new Set([...text.matchAll(RATIONALE_PATH_RE_GLOBAL)].map((m) => m[1]))].filter((p) => !/^https?:\/\//i.test(p));
5027
+ }
4256
5028
  var FILE_EXTENSIONS = new Set([
4257
5029
  "ts",
4258
5030
  "tsx",
@@ -4274,6 +5046,11 @@ var FILE_EXTENSIONS = new Set([
4274
5046
  "html",
4275
5047
  "css"
4276
5048
  ]);
5049
+ function boundaryPinnedFiles(body) {
5050
+ const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
5051
+ const excluded = new Set(namedPathsIn(boundaryOutText(body)));
5052
+ return namedPathsIn(boundary).filter((p) => looksLikeFilePath(p) && !excluded.has(p));
5053
+ }
4277
5054
  var CI_SHARD_DIR = "apps/cli/tests/ci-shards";
4278
5055
  var CI_SHARD_PROBE = `${CI_SHARD_DIR}/shard-1.txt`;
4279
5056
 
@@ -4298,7 +5075,7 @@ function isGrandfathered(isoDate) {
4298
5075
  return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
4299
5076
  }
4300
5077
  var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
4301
- function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
5078
+ function checkA1(entries, principalAllowlist) {
4302
5079
  const failures = [];
4303
5080
  for (const e of entries) {
4304
5081
  if (!e.facts)
@@ -4328,6 +5105,37 @@ function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
4328
5105
  note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4329
5106
  };
4330
5107
  }
5108
+ function checkA2(entries, hasProvenanceByKey) {
5109
+ const failures = [];
5110
+ for (const e of entries) {
5111
+ if (!e.facts)
5112
+ continue;
5113
+ if (e.facts.issueState !== "closed" || e.facts.prState !== "merged")
5114
+ continue;
5115
+ const key = `${e.trancheSlug}/${e.task.id}`;
5116
+ const hasProvenance = hasProvenanceByKey.get(key);
5117
+ if (hasProvenance === undefined)
5118
+ continue;
5119
+ if (!hasProvenance) {
5120
+ failures.push({
5121
+ code: "archived-without-provenance",
5122
+ issue: e.task.issue,
5123
+ tranche: e.trancheSlug,
5124
+ task: e.task.id,
5125
+ reason: "Closing PR has no `### AEG provenance` comment (Archivist close-out missing)",
5126
+ grandfathered: isGrandfathered(e.facts.mergedAt)
5127
+ });
5128
+ }
5129
+ }
5130
+ const activeFails = failures.filter((f) => !f.grandfathered);
5131
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
5132
+ return {
5133
+ check: "A2",
5134
+ status,
5135
+ failures,
5136
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
5137
+ };
5138
+ }
4331
5139
  function checkA3(entries) {
4332
5140
  const failures = [];
4333
5141
  for (const e of entries) {
@@ -4543,6 +5351,33 @@ function checkL1(files, entriesBySlug) {
4543
5351
  note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
4544
5352
  };
4545
5353
  }
5354
+ function checkL2(files, entriesBySlug) {
5355
+ const failures = [];
5356
+ for (const f of files) {
5357
+ if (!f.archived)
5358
+ continue;
5359
+ const entries = entriesBySlug.get(f.slug) ?? [];
5360
+ for (const e of entries) {
5361
+ if (!e.facts)
5362
+ continue;
5363
+ if (e.facts.issueState === "open") {
5364
+ failures.push({
5365
+ code: "premature-archive",
5366
+ issue: e.task.issue,
5367
+ tranche: f.slug,
5368
+ task: e.task.id,
5369
+ reason: `Archived tranche has open task-Issue #${e.task.issue ?? "?"} (premature archive)`
5370
+ });
5371
+ }
5372
+ }
5373
+ }
5374
+ return {
5375
+ check: "L2",
5376
+ status: "info",
5377
+ failures,
5378
+ note: failures.length > 0 ? `${failures.length} archived tranche(s) with an open task-Issue — investigate (advisory)` : undefined
5379
+ };
5380
+ }
4546
5381
  function checkL3(files) {
4547
5382
  const active = files.filter((f) => !f.archived);
4548
5383
  return {
@@ -4552,6 +5387,51 @@ function checkL3(files) {
4552
5387
  note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
4553
5388
  };
4554
5389
  }
5390
+ function checkL4(activeTrancheSlugs, issueMilestones) {
5391
+ const activeSet = new Set(activeTrancheSlugs);
5392
+ const failures = [];
5393
+ for (const f of issueMilestones) {
5394
+ if (!activeSet.has(f.tranche))
5395
+ continue;
5396
+ if (f.milestoneTitle === f.tranche)
5397
+ continue;
5398
+ failures.push({
5399
+ code: "milestone-drift",
5400
+ issue: f.issue,
5401
+ tranche: f.tranche,
5402
+ reason: f.milestoneTitle === null ? `Issue #${f.issue} carries ${trancheLabel(f.tranche)} (active) but has no GitHub-native milestone attached` : `Issue #${f.issue} carries ${trancheLabel(f.tranche)} (active) but is attached to Milestone "${f.milestoneTitle}" instead`
5403
+ });
5404
+ }
5405
+ return {
5406
+ check: "L4",
5407
+ status: "info",
5408
+ failures,
5409
+ note: failures.length > 0 ? `${failures.length} open task-Issue(s) in an active tranche whose GitHub-native milestone doesn't match their ${label("tranche")}<slug> label (cosmetic drift, advisory)` : undefined
5410
+ };
5411
+ }
5412
+ function checkL5(activeTrancheSlugs, entriesBySlug) {
5413
+ const failures = [];
5414
+ for (const slug of activeTrancheSlugs) {
5415
+ const entries = entriesBySlug.get(slug) ?? [];
5416
+ const withFacts = entries.filter((e) => e.facts !== undefined);
5417
+ if (withFacts.length === 0)
5418
+ continue;
5419
+ const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
5420
+ if (allClosed) {
5421
+ failures.push({
5422
+ code: "tranche-not-archived",
5423
+ tranche: slug,
5424
+ reason: "Every task Issue is closed but the tranche is not recorded as complete — archive it"
5425
+ });
5426
+ }
5427
+ }
5428
+ return {
5429
+ check: "L5",
5430
+ status: failures.length > 0 ? "fail" : "pass",
5431
+ failures,
5432
+ note: failures.length > 0 ? `${failures.length} tranche(s) whose task Issues are all closed but were never archived` : undefined
5433
+ };
5434
+ }
4555
5435
  function extractClosesReferences(prBody) {
4556
5436
  const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
4557
5437
  const stripped = stripCode(prBody);
@@ -4647,6 +5527,58 @@ function extractIssue(body) {
4647
5527
  }
4648
5528
  // ../../packages/aeg-core/src/review-input-manifest.ts
4649
5529
  import { createHash as createHash4 } from "node:crypto";
5530
+
5531
+ // ../../packages/aeg-core/src/ruling-ordinal.ts
5532
+ var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
5533
+ function newestPrincipalRulingOrdinal(comments, allowlist) {
5534
+ let best = 0;
5535
+ for (const c of comments) {
5536
+ if (!isPrincipal(c.author, allowlist))
5537
+ continue;
5538
+ const firstLine = (c.body.split(`
5539
+ `)[0] ?? "").trim();
5540
+ const m = RULING_MARKER_ORDINAL.exec(firstLine);
5541
+ if (!m)
5542
+ continue;
5543
+ const k = Number.parseInt(m[1], 10);
5544
+ if (k > best)
5545
+ best = k;
5546
+ }
5547
+ return best;
5548
+ }
5549
+ function parseRulingIdentity(rulingId) {
5550
+ const m = /^(issue-)?(\d+)-(\d+)$/.exec(rulingId);
5551
+ if (!m)
5552
+ return null;
5553
+ const ref = Number.parseInt(m[2], 10);
5554
+ const ordinal = Number.parseInt(m[3], 10);
5555
+ if (ref <= 0 || ordinal <= 0)
5556
+ return null;
5557
+ return { target: m[1] ? "issue" : "pr", ref, ordinal };
5558
+ }
5559
+ function principalRulingTextById(comments, allowlist, rulingId) {
5560
+ const identity = parseRulingIdentity(rulingId);
5561
+ if (identity === null)
5562
+ return null;
5563
+ const matches = comments.filter((c) => {
5564
+ if (!isPrincipal(c.author, allowlist))
5565
+ return false;
5566
+ const m = RULING_MARKER_ORDINAL.exec((c.body.split(`
5567
+ `)[0] ?? "").trim());
5568
+ return m !== null && Number.parseInt(m[1], 10) === identity.ordinal;
5569
+ });
5570
+ if (matches.length !== 1)
5571
+ return null;
5572
+ const body = matches[0].body;
5573
+ const idx = body.indexOf(`
5574
+ `);
5575
+ return idx === -1 ? "" : body.slice(idx + 1).trim();
5576
+ }
5577
+
5578
+ // ../../packages/aeg-core/src/review-input-manifest.ts
5579
+ function pauseBoundRulingDigest(rulingText) {
5580
+ return createHash4("sha256").update(rulingText).digest("hex");
5581
+ }
4650
5582
  function briefHash(brief) {
4651
5583
  return createHash4("sha256").update(`${brief}
4652
5584
  `).digest("hex");
@@ -4707,14 +5639,19 @@ function compareManifest(echoed, current, patchIdOf) {
4707
5639
  const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4708
5640
  const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4709
5641
  const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
5642
+ const legacyCurrent = current.manifestVersion === undefined;
5643
+ const manifestVersion = legacyCurrent ? echoed.manifestVersion === undefined || echoed.manifestVersion === null : echoed.manifestVersion === current.manifestVersion;
5644
+ const pauseBoundRuling = legacyCurrent ? true : Object.hasOwn(echoed, "pauseBoundRuling") && JSON.stringify(echoed.pauseBoundRuling) === JSON.stringify(current.pauseBoundRuling);
4710
5645
  const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4711
5646
  return {
4712
- bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
5647
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && pauseBoundRuling && manifestVersion && policyDigestBound,
4713
5648
  head,
4714
5649
  base,
4715
5650
  briefHash: briefHashBound,
4716
5651
  objectivesVersion,
4717
5652
  rulingOrdinal,
5653
+ pauseBoundRuling,
5654
+ manifestVersion,
4718
5655
  policyDigest: policyDigestBound
4719
5656
  };
4720
5657
  }
@@ -4730,7 +5667,7 @@ function renderGateDeferred(deferred) {
4730
5667
  return ` ${deferred.length} finding(s) deferred, not blocking this round: ${items}.`;
4731
5668
  }
4732
5669
  function checkReviewGate(input) {
4733
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
5670
+ const { principalAllowlist } = input;
4734
5671
  const waived = isWaiverLabelActorVerified({
4735
5672
  label: WAIVER_LABEL_REVIEW,
4736
5673
  labels: input.labels,
@@ -4769,27 +5706,33 @@ function checkReviewGate(input) {
4769
5706
  const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4770
5707
  const securityClean = securityTextClean && securityPolicyClean;
4771
5708
  const currentManifest = {
5709
+ ...input.manifestVersion === undefined ? {} : { manifestVersion: input.manifestVersion },
4772
5710
  headSha: input.headSha,
4773
5711
  baseSha: input.baseSha ?? null,
4774
5712
  briefHash: input.briefHash ?? null,
4775
5713
  objectivesVersion: input.objectivesVersion,
4776
5714
  rulingOrdinal: input.rulingOrdinal,
5715
+ pauseBoundRuling: input.pauseBoundRuling ?? null,
4777
5716
  policyDigest: policyDigest(policy)
4778
5717
  };
4779
5718
  const codeReviewEchoed = {
5719
+ manifestVersion: codeReview.manifestVersion,
4780
5720
  headSha: codeReview.headSha,
4781
5721
  baseSha: codeReview.baseSha,
4782
5722
  briefHash: codeReview.briefHash,
4783
5723
  objectivesVersion: codeReview.objectivesVersion,
4784
5724
  rulingOrdinal: codeReview.rulingOrdinal,
5725
+ pauseBoundRuling: codeReview.pauseBoundRuling,
4785
5726
  policyDigest: codeReview.policyDigest
4786
5727
  };
4787
5728
  const securityEchoed = {
5729
+ manifestVersion: security.manifestVersion,
4788
5730
  headSha: security.headSha,
4789
5731
  baseSha: security.baseSha,
4790
5732
  briefHash: security.briefHash,
4791
5733
  objectivesVersion: security.objectivesVersion,
4792
5734
  rulingOrdinal: security.rulingOrdinal,
5735
+ pauseBoundRuling: security.pauseBoundRuling,
4793
5736
  policyDigest: security.policyDigest
4794
5737
  };
4795
5738
  const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
@@ -4828,6 +5771,10 @@ function checkReviewGate(input) {
4828
5771
  problems.push(`the newest code-review verdict was cast against brief hash ${codeReview.briefHash ?? "none"}, the frozen brief's current hash is ${currentManifest.briefHash ?? "none"}`);
4829
5772
  } else if (!codeReviewBinding.policyDigest) {
4830
5773
  problems.push(`the newest code-review verdict was cast against review policy digest ${codeReview.policyDigest ?? "none"}, this repository's current policy digest is ${currentManifest.policyDigest}`);
5774
+ } else if (!codeReviewBinding.manifestVersion) {
5775
+ problems.push(`the newest code-review verdict echoes manifest version ${codeReview.manifestVersion ?? "none"}, the frozen review-input manifest is version ${currentManifest.manifestVersion ?? "unversioned"}`);
5776
+ } else if (!codeReviewBinding.pauseBoundRuling) {
5777
+ problems.push(`the newest code-review verdict echoes pauseBoundRuling ${renderBinding(codeReview.pauseBoundRuling)}, the frozen review-input manifest binds ${renderBinding(currentManifest.pauseBoundRuling)}`);
4831
5778
  }
4832
5779
  if (!securityTextClean) {
4833
5780
  problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
@@ -4845,6 +5792,10 @@ function checkReviewGate(input) {
4845
5792
  problems.push(`the newest security-review verdict was cast against brief hash ${security.briefHash ?? "none"}, the frozen brief's current hash is ${currentManifest.briefHash ?? "none"}`);
4846
5793
  } else if (!securityBinding.policyDigest) {
4847
5794
  problems.push(`the newest security-review verdict was cast against review policy digest ${security.policyDigest ?? "none"}, this repository's current policy digest is ${currentManifest.policyDigest}`);
5795
+ } else if (!securityBinding.manifestVersion) {
5796
+ problems.push(`the newest security-review verdict echoes manifest version ${security.manifestVersion ?? "none"}, the frozen review-input manifest is version ${currentManifest.manifestVersion ?? "unversioned"}`);
5797
+ } else if (!securityBinding.pauseBoundRuling) {
5798
+ problems.push(`the newest security-review verdict echoes pauseBoundRuling ${renderBinding(security.pauseBoundRuling)}, the frozen review-input manifest binds ${renderBinding(currentManifest.pauseBoundRuling)}`);
4848
5799
  }
4849
5800
  const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4850
5801
  return {
@@ -4853,29 +5804,16 @@ function checkReviewGate(input) {
4853
5804
  waived: false
4854
5805
  };
4855
5806
  }
5807
+ function renderBinding(binding) {
5808
+ if (binding === undefined)
5809
+ return "(absent)";
5810
+ return binding === null ? "(none)" : `${binding.rulingId}|${binding.pauseId}|${binding.contentDigest}`;
5811
+ }
4856
5812
  var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4857
5813
  var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4858
5814
  function isChangesetsReleasePr(branch, author, expectedAuthor) {
4859
5815
  return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4860
5816
  }
4861
- // ../../packages/aeg-core/src/ruling-ordinal.ts
4862
- var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4863
- function newestPrincipalRulingOrdinal(comments, allowlist) {
4864
- let best = 0;
4865
- for (const c of comments) {
4866
- if (!isPrincipal(c.author, allowlist))
4867
- continue;
4868
- const firstLine = (c.body.split(`
4869
- `)[0] ?? "").trim();
4870
- const m = RULING_MARKER_ORDINAL.exec(firstLine);
4871
- if (!m)
4872
- continue;
4873
- const k = Number.parseInt(m[1], 10);
4874
- if (k > best)
4875
- best = k;
4876
- }
4877
- return best;
4878
- }
4879
5817
  // ../../packages/aeg-core/src/markdown-table.ts
4880
5818
  function splitRow(line) {
4881
5819
  const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
@@ -5027,7 +5965,6 @@ var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
5027
5965
  var NON_GATE_BIN_NAMES = NON_GATE_BINS;
5028
5966
  var TWIN_CANDIDATE_EXCEPTIONS = {
5029
5967
  "apps/cli/src/checks/bin/check-dead-branch-push.ts": 'Ring 0 "Pushing to a branch whose pull request already resolved" (implementation: check-push-target.ts)',
5030
- "apps/cli/src/checks/bin/check-issue-assignment.ts": `Ring 0 "A task branch's first push (Issue self-assignment)" (implementation: assign-task-issue.ts)`,
5031
5968
  "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
5032
5969
  };
5033
5970
  var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
@@ -5251,72 +6188,10 @@ function compareToBaseline(current, baseline) {
5251
6188
  };
5252
6189
  }
5253
6190
  // ../../packages/aeg-core/src/retired-vocabulary.ts
5254
- var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
5255
- var RETIRED_PATTERNS = [
5256
- String.raw`\bD-[0-9]{3}\b`,
5257
- "D-(###|NNN|nnn|xxx)",
5258
- "decision (entry|logged)",
5259
- "decision-log entry",
5260
- "decision log entry",
5261
- "decision log(s|ged|ging)?([^a-z]|$)",
5262
- "decision-log",
5263
- "decision entr",
5264
- "decisions? (are |is )?logged",
5265
- "log entries",
5266
- String.raw`decisions\.md`,
5267
- "decisions-legacy",
5268
- "CONTRADICTION",
5269
- "assumes Tier 3",
5270
- "Lock: ?YES",
5271
- "Lock: ?NO",
5272
- "lock approvals?",
5273
- "approves locks",
5274
- "Conforms to lock",
5275
- "Challenges lock",
5276
- "checkDecisionNumbersFresh",
5277
- String.raw`roles/team-leader\.md`,
5278
- String.raw`\(,`,
5279
- String.raw`,\)`,
5280
- String.raw`\(\.\)`,
5281
- ...PLAN_ON_DISK_PATTERNS
5282
- ];
5283
- var TRANCHE_MODEL_FILE = "/tranche-model.md";
5284
- var RETIRED_EXEMPT_SUBSTRINGS = [
5285
- "docs/decisions-legacy.md",
5286
- "apps/herald-ai/docs/",
5287
- "apps/vada-ai/docs/",
5288
- "aeg-root/tranches/completed/",
5289
- "packages/aeg-core/src/docs/published-prose",
5290
- "packages/aeg-core/src/retired-vocabulary.test.ts",
5291
- "packages/aeg-core/src/retired-vocabulary.ts",
5292
- "/fixtures/",
5293
- "/node_modules/",
5294
- "/.next/",
5295
- "/.turbo/"
5296
- ];
5297
- var PATTERN_EXEMPT = {
5298
- [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
5299
- [String.raw`decisions\.md`]: [
5300
- "docs-index.md",
5301
- "apps/vada-ai/specs/legacy/README.md",
5302
- "apps/vada-ai/specs/vada-product-spec.md",
5303
- "apps/vada-ai/web/CLAUDE.md",
5304
- "apps/vada-ai/CLAUDE.md"
5305
- ],
5306
- "decisions-legacy": [
5307
- "packages/aeg-core/src/file-classify.ts",
5308
- "packages/aeg-core/src/file-classify.test.ts",
5309
- "packages/aeg-core/src/pr-tier.test.ts",
5310
- "docs-index.md",
5311
- ".claude/skills/database/SKILL.md",
5312
- ".claude/skills/vada-architecture/SKILL.md",
5313
- "apps/vada-ai/specs/vada-byok-principles.md",
5314
- "apps/vada-ai/web/CLAUDE.md",
5315
- "apps/vada-ai/CLAUDE.md"
5316
- ],
5317
- CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
5318
- ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
5319
- };
6191
+ var retiredRules = rulesForGroup("retired-vocabulary");
6192
+ var RETIRED_PATTERNS = retiredRules.map((rule) => rule.patterns.repository);
6193
+ var PATTERN_EXEMPT = RETIRED_PATTERN_EXEMPTIONS;
6194
+ var DEFAULT_PATTERN_OF = new Map(retiredRules.map((rule) => [rule.id, rule.patterns.repository]));
5320
6195
  function lineNumbers(content, pattern) {
5321
6196
  const out = [];
5322
6197
  const lines = content.split(`
@@ -5327,22 +6202,29 @@ function lineNumbers(content, pattern) {
5327
6202
  }
5328
6203
  return out;
5329
6204
  }
5330
- function scanRetiredVocabulary(files) {
6205
+ function scanRetiredVocabulary(files, rules = DEFAULT_PROSE_RULE_SET) {
5331
6206
  const findings = [];
6207
+ const retired = rulesOfGroup(rules, "retired-vocabulary");
5332
6208
  for (const file of files) {
5333
- if (RETIRED_EXEMPT_SUBSTRINGS.some((e) => file.path.includes(e)))
5334
- continue;
5335
- for (const pattern of RETIRED_PATTERNS) {
5336
- const patternExempt = PATTERN_EXEMPT[pattern] ?? [];
5337
- if (patternExempt.some((e) => file.path.includes(e)))
6209
+ for (const rule of retired) {
6210
+ if (rule.substringExempt.some((e) => file.path.includes(e)))
6211
+ continue;
6212
+ if (!ruleReads(rules, rule, file.path))
6213
+ continue;
6214
+ const re = rule.patternFor("repository");
6215
+ if (!re)
6216
+ continue;
6217
+ const pattern = rule.custom ? re.source : DEFAULT_PATTERN_OF.get(rule.id) ?? re.source;
6218
+ if (!rule.custom && (PATTERN_EXEMPT[pattern] ?? []).some((e) => file.path.includes(e)))
5338
6219
  continue;
5339
- const re = new RegExp(pattern);
5340
6220
  for (const line of lineNumbers(file.content, re)) {
5341
6221
  findings.push({
5342
6222
  file: file.path,
5343
6223
  line,
5344
6224
  pattern,
5345
- message: `claims a retired AEG mechanism is still live (matches /${pattern}/)`
6225
+ message: rule.custom ? `${rule.id}: ${rule.message} (matches /${pattern}/)` : `claims a retired AEG mechanism is still live (matches /${pattern}/)`,
6226
+ rule: rule.id,
6227
+ blocking: rule.severity.repository === "error"
5346
6228
  });
5347
6229
  }
5348
6230
  }
@@ -5366,7 +6248,7 @@ function isSelfDependency(dep, task, issue) {
5366
6248
  function checkDispatchReadiness(input) {
5367
6249
  const { trancheSlug, task } = input;
5368
6250
  const taskLabel = `task ${task.id} (tranche ${trancheSlug})`;
5369
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
6251
+ const { principalAllowlist } = input;
5370
6252
  const blockerDetails = [];
5371
6253
  const push = (blockerClass, message) => {
5372
6254
  blockerDetails.push({ class: blockerClass, message });
@@ -5458,6 +6340,16 @@ function pushesAnyBranchRef(pushRefs) {
5458
6340
  return pushRefs.split(`
5459
6341
  `).map((line) => line.trim()).filter((line) => line.length > 0).some((line) => line.split(/\s+/)[2]?.startsWith("refs/heads/") === true);
5460
6342
  }
6343
+ function resolveDefaultBranch(facts) {
6344
+ const { originHead, hasOriginMain, hasOriginMaster } = facts;
6345
+ if (originHead !== null && originHead !== "")
6346
+ return originHead;
6347
+ if (hasOriginMain)
6348
+ return "main";
6349
+ if (hasOriginMaster)
6350
+ return "master";
6351
+ return null;
6352
+ }
5461
6353
  function checkMainBranchRefusal(facts) {
5462
6354
  const { currentSymbolicBranch, defaultBranch, pushRefs = null } = facts;
5463
6355
  if (currentSymbolicBranch === null)
@@ -5718,54 +6610,61 @@ function checkFirstPushDispatchGate(input) {
5718
6610
  reason: `verify-dispatch reports READY TO DISPATCH for \`${branch}\`.`
5719
6611
  };
5720
6612
  }
5721
- // ../../packages/aeg-core/src/issue-assignment.ts
5722
- function decideIssueAssignment(input) {
5723
- const { branch, remoteRefExists, issue, assignees, login } = input;
5724
- if (parseTaskBranch(branch) === null) {
5725
- return {
5726
- action: "skip",
5727
- reason: `Branch \`${branch}\` is not a task/<tranche>/<n> branch — Issue self-assignment only applies to task branches.`
5728
- };
5729
- }
5730
- if (remoteRefExists) {
5731
- return {
5732
- action: "skip",
5733
- reason: `Branch \`${branch}\` already exists on the remote — not its first push, nothing to assign.`
5734
- };
5735
- }
5736
- if (issue === null) {
5737
- return {
5738
- action: "skip",
5739
- reason: `No Issue resolved for \`${branch}\` from its topology row — skipping self-assignment (the gate owns refusing an unplanned branch).`
5740
- };
5741
- }
5742
- if (assignees === null) {
5743
- return {
5744
- action: "skip",
5745
- reason: `Could not read Issue #${issue}'s current assignees — skipping rather than risking a double-assign (fail-open, never a guess).`
5746
- };
5747
- }
5748
- if (assignees.length > 0) {
5749
- return {
5750
- action: "skip",
5751
- reason: `Issue #${issue} is already assigned (${assignees.join(", ")}) — no-op.`
5752
- };
5753
- }
5754
- if (login === null) {
5755
- return {
5756
- action: "skip",
5757
- reason: "Could not resolve the authenticated `gh` login — never assigning anyone other than the actual pusher, so skipping."
5758
- };
6613
+ // ../../packages/aeg-core/src/live-record.ts
6614
+ var RECORD_LINE_RE = /^-\s*\[([ xX])\]\s*\*\*\[live\]\*\*\s+(`+) ?(.+?) ?\2(?!`)\s+—\s+(passed|failed|unverified)\s+at\s+`([^`]+)`/;
6615
+ function liveMarkers(body) {
6616
+ const masked = maskCode(body);
6617
+ return [...masked.matchAll(/<!--\s*AEG:LIVE:(?:START|END)\s*-->/g)].map((m) => ({
6618
+ start: m.index,
6619
+ end: m.index + m[0].length
6620
+ }));
6621
+ }
6622
+ var AMBIGUOUS_RECORD_LINE = {
6623
+ line: "- [ ] **[live]** the pull request body carries more than one `AEG:LIVE` marker pair, so the driver's record cannot be told apart",
6624
+ ticked: false,
6625
+ command: "",
6626
+ outcome: "failed",
6627
+ head: ""
6628
+ };
6629
+ function readLiveRecord(body) {
6630
+ const markers = liveMarkers(body).length;
6631
+ if (markers === 0)
6632
+ return [];
6633
+ if (markers !== 2)
6634
+ return [AMBIGUOUS_RECORD_LINE];
6635
+ const region = anchoredRegion(body, "LIVE");
6636
+ if (region === null)
6637
+ return [];
6638
+ const lines = [];
6639
+ for (const raw of region.split(`
6640
+ `)) {
6641
+ const line = raw.trim();
6642
+ const m = RECORD_LINE_RE.exec(line);
6643
+ if (!m)
6644
+ continue;
6645
+ lines.push({
6646
+ line,
6647
+ ticked: m[1].toLowerCase() === "x",
6648
+ command: m[3],
6649
+ outcome: m[4],
6650
+ head: m[5]
6651
+ });
5759
6652
  }
5760
- return {
5761
- action: "assign",
5762
- issue,
5763
- login,
5764
- reason: `First push of \`${branch}\` — assigning Issue #${issue} to @${login} (the authenticated pusher).`
5765
- };
6653
+ return lines;
5766
6654
  }
5767
6655
  // ../../packages/aeg-core/src/test-plan-gate.ts
5768
- function evaluateTestPlanGate(body, branch) {
6656
+ function gradedLiveLines(record, live) {
6657
+ if (live === undefined)
6658
+ return record.map((entry) => entry.line);
6659
+ const commands = new Set(live.liveCommands);
6660
+ const others = record.filter((entry) => !commands.has(entry.command)).map((entry) => entry.line);
6661
+ const graded = live.liveCommands.map((command) => {
6662
+ const atHead = record.filter((entry) => entry.command === command && entry.head === live.head);
6663
+ return (atHead.find((entry) => entry.ticked) ?? atHead[0])?.line ?? `- [ ] **[live]** \`${command}\` — no passed run recorded at \`${live.head || "an unknown head"}\``;
6664
+ });
6665
+ return [...others, ...graded];
6666
+ }
6667
+ function evaluateTestPlanGate(body, branch, live) {
5769
6668
  if (!body) {
5770
6669
  return {
5771
6670
  verdict: "pass",
@@ -5776,7 +6675,9 @@ function evaluateTestPlanGate(body, branch) {
5776
6675
  };
5777
6676
  }
5778
6677
  const located = locateTestPlanSection(body);
5779
- if (!located.found) {
6678
+ const liveLines = gradedLiveLines(readLiveRecord(body), live);
6679
+ const liveUnticked = liveLines.some((line) => /^[-*]\s+\[\s\]/.test(line));
6680
+ if (!located.found && !liveUnticked) {
5780
6681
  if (parseTaskBranchIdentity(branch) !== null) {
5781
6682
  return {
5782
6683
  verdict: "fail",
@@ -5796,15 +6697,18 @@ function evaluateTestPlanGate(body, branch) {
5796
6697
  ]
5797
6698
  };
5798
6699
  }
5799
- const section = located.section;
5800
- if (/unit-tests-only/i.test(section)) {
6700
+ const section = located.found ? located.section : "";
6701
+ if (/unit-tests-only/i.test(section) && !liveUnticked) {
5801
6702
  return {
5802
6703
  verdict: "pass",
5803
6704
  messages: ["Test Plan: unit-tests-only — pure-logic brief, CI unit-tests are the proof.", "PASS."]
5804
6705
  };
5805
6706
  }
5806
- const checkboxLines = section.split(`
5807
- `).map((line) => line.trimStart()).filter((line) => /^[-*]\s+\[[ xX]\]\s*\*{0,2}\[principal\]\*{0,2}/i.test(line));
6707
+ const checkboxLines = [
6708
+ ...section.split(`
6709
+ `).map((line) => line.trimStart()).filter((line) => /^[-*]\s+\[[ xX]\]\s*\*{0,2}\[principal\]\*{0,2}/i.test(line)),
6710
+ ...liveLines
6711
+ ];
5808
6712
  if (checkboxLines.length === 0) {
5809
6713
  return {
5810
6714
  verdict: "pass",
@@ -5821,7 +6725,9 @@ function evaluateTestPlanGate(body, branch) {
5821
6725
  messages.push("", "FAIL — the following [principal] Test Plan items are unticked:");
5822
6726
  for (const line of unchecked)
5823
6727
  messages.push(` ${line}`);
5824
- messages.push("", "Per aeg-root/roles/developer.md (Verification), a PR is not mergeable while any [principal] Test Plan box is unticked.", "The Principal runs the item in a real signed-in browser and ticks the box.", "Note: editing the PR body does not retrigger most workflows. If your PR body changes do not surface here, push an empty commit to re-run.");
6728
+ messages.push("", "Per aeg-root/roles/developer.md (Verification), a PR is not mergeable while any [principal] Test Plan box is unticked.", "The Principal runs the item in a real signed-in browser and ticks the box.", ...liveUnticked ? [
6729
+ "An unticked [live] line is a live run that failed or that the review loop could not verify on its host: a later head re-runs it, or the Principal runs it and ticks the box."
6730
+ ] : [], "Note: editing the PR body does not retrigger most workflows. If your PR body changes do not surface here, push an empty commit to re-run.");
5825
6731
  return { verdict: "fail", messages };
5826
6732
  }
5827
6733
  messages.push("All [principal] Test Plan items ticked — runtime verification complete.", "PASS.");
@@ -6010,9 +6916,11 @@ var LineageSchema = z3.object({
6010
6916
  parent: z3.string().nullable()
6011
6917
  }).strict();
6012
6918
  var InputVersionsSchema = z3.object({
6919
+ manifest_version: z3.literal(2).nullable().optional(),
6013
6920
  objectives_version: z3.string().nullable(),
6014
6921
  brief_hash: z3.string().nullable(),
6015
6922
  ruling_ordinal: z3.number().int().nullable(),
6923
+ pause_bound_ruling: z3.object({ rulingId: z3.string().min(1), pauseId: z3.string().min(1), contentDigest: z3.string().min(1) }).strict().nullable().optional(),
6016
6924
  policy_digest: z3.string().nullable()
6017
6925
  }).strict();
6018
6926
  var ProvenanceSchema = z3.enum(["parent_attributed", "env_correlated", "self_reported", "unavailable"]);
@@ -6560,17 +7468,19 @@ function buildHeader(input) {
6560
7468
  parent: lineageFieldFromEnv(input.env.parent)
6561
7469
  },
6562
7470
  input_versions: {
7471
+ manifest_version: input.inputVersions?.manifestVersion ?? null,
6563
7472
  objectives_version: input.inputVersions?.objectivesVersion ?? null,
6564
7473
  brief_hash: input.inputVersions?.briefHash ?? null,
6565
7474
  ruling_ordinal: input.inputVersions?.rulingOrdinal ?? null,
7475
+ pause_bound_ruling: input.inputVersions?.pauseBoundRuling ?? null,
6566
7476
  policy_digest: input.inputVersions?.policyDigest ?? null
6567
7477
  },
6568
7478
  provenance: provenanceFor(input),
6569
7479
  work: {
6570
7480
  ref: lineageFieldFromEnv(input.env.workRef) ?? (issue === null ? null : String(issue)),
6571
7481
  repo: input.repo,
6572
- change: null,
6573
- revision: null
7482
+ change: pr === undefined ? null : String(pr),
7483
+ revision: input.revision ?? null
6574
7484
  },
6575
7485
  flow: {
6576
7486
  id: lineageFieldFromEnv(input.env.flow) ?? "vinaya",
@@ -6758,6 +7668,12 @@ var ManifestRecordSchema = z4.object({
6758
7668
  briefHash: z4.string().min(1).nullable(),
6759
7669
  objectivesVersion: z4.string().min(1).nullable(),
6760
7670
  rulingOrdinal: epochNumber,
7671
+ manifestVersion: z4.literal(2).optional(),
7672
+ pauseBoundRuling: z4.object({
7673
+ rulingId: z4.string().min(1),
7674
+ pauseId: z4.string().min(1),
7675
+ contentDigest: z4.string().min(1)
7676
+ }).strict().nullable().optional(),
6761
7677
  policyDigest: z4.string().min(1),
6762
7678
  recordedAt: isoTimestamp
6763
7679
  }).strict();
@@ -6779,7 +7695,11 @@ var LoopStateRecordSchema = z4.object({
6779
7695
  deliveredFindings: roundHeadIdentity.nullable(),
6780
7696
  repeatMemory: z4.object({
6781
7697
  blockingFindings: z4.array(z4.string()),
6782
- lastFailure: z4.object({ signature: z4.string(), message: z4.string() }).nullable()
7698
+ lastFailure: z4.object({ signature: z4.string(), message: z4.string(), developerAttemptedSince: z4.boolean().optional() }).nullable()
7699
+ }).strict().optional(),
7700
+ developerHandoff: z4.object({
7701
+ findings: z4.array(z4.object({ id: z4.string().min(1), description: z4.string().min(1) }).strict()),
7702
+ failingChecks: z4.array(z4.string().min(1))
6783
7703
  }).strict().optional(),
6784
7704
  publicationExpectedBase: z4.string().regex(/^[0-9a-f]{40}$/).nullable().optional(),
6785
7705
  taskStartedAt: isoTimestamp.optional(),
@@ -6842,29 +7762,320 @@ import { promisify as promisify4 } from "node:util";
6842
7762
  import { existsSync, mkdirSync, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync } from "node:fs";
6843
7763
  import { homedir } from "node:os";
6844
7764
  import { dirname, isAbsolute, join, resolve } from "node:path";
6845
- import { z as z5 } from "zod";
7765
+ import { z as z6 } from "zod";
7766
+
7767
+ // src/checks/contract.ts
7768
+ var CHECK_SCHEMA_VERSION = 1;
7769
+ function emitCheckError(error) {
7770
+ process.stderr.write(`${JSON.stringify(error)}
7771
+ `);
7772
+ }
6846
7773
 
6847
7774
  // src/lib/agent-vendors.ts
6848
7775
  var AGENT_VENDORS = ["skills", "claude", "gemini"];
6849
7776
 
7777
+ // src/lib/prose-rules-config.ts
7778
+ import safeRegex from "safe-regex2";
7779
+ import { z as z5 } from "zod";
7780
+ var SEVERITIES = ["error", "warning"];
7781
+ var OVERRIDE_KEYS = ["scopes", "severity", "exempt"];
7782
+ var FIXED_DEFAULT_KEYS = ["pattern", "patterns", "flags", "means", "message", "id"];
7783
+ var CUSTOM_KEYS = ["id", "pattern", "patterns", "flags", "means", "scopes", "severity", "exempt"];
7784
+ var DEFAULT_IDS = new Set([...DEFAULT_PROSE_RULES.map((rule) => rule.id), DECISION_RECORD_CITATION_ID]);
7785
+ function isPlainObject3(value) {
7786
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7787
+ }
7788
+ function outsideRepositoryReason(entry) {
7789
+ if (entry.startsWith("/") || /^[A-Za-z]:/.test(entry))
7790
+ return "must be a repository-relative path, not an absolute one";
7791
+ if (entry.split(/[\\/]/).includes(".."))
7792
+ return "must stay inside the repository — no `..` segment";
7793
+ return null;
7794
+ }
7795
+ var RepoRelativePathSchema = z5.string().min(1).superRefine((entry, ctx) => {
7796
+ const reason = outsideRepositoryReason(entry);
7797
+ if (reason)
7798
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, message: reason });
7799
+ });
7800
+ function pathListIssues(value, path, issues) {
7801
+ if (!Array.isArray(value)) {
7802
+ issues.push({ path, message: "must be a list of repository-relative paths" });
7803
+ return;
7804
+ }
7805
+ value.forEach((entry, index) => {
7806
+ if (typeof entry !== "string" || entry.length === 0) {
7807
+ issues.push({ path: [...path, index], message: "must be a non-empty repository-relative path" });
7808
+ return;
7809
+ }
7810
+ const reason = outsideRepositoryReason(entry);
7811
+ if (reason)
7812
+ issues.push({ path: [...path, index], message: reason });
7813
+ });
7814
+ }
7815
+ function scopeListIssues(value, path, allowed, issues) {
7816
+ if (!Array.isArray(value) || value.length === 0) {
7817
+ issues.push({ path, message: "must name at least one scope" });
7818
+ return null;
7819
+ }
7820
+ const scopes = [];
7821
+ value.forEach((scope, index) => {
7822
+ if (typeof scope !== "string" || !CONFIGURABLE_PROSE_SCOPES.includes(scope)) {
7823
+ issues.push({
7824
+ path: [...path, index],
7825
+ message: scope === "published" ? 'scope "published" is not configurable here — the published pass is configured by proseGates.published.allow' : `unknown scope ${JSON.stringify(scope)} — the scopes are: ${CONFIGURABLE_PROSE_SCOPES.join(", ")}`
7826
+ });
7827
+ return;
7828
+ }
7829
+ if (!allowed.includes(scope)) {
7830
+ issues.push({
7831
+ path: [...path, index],
7832
+ message: `scope "${scope}" is not one this rule can run in — it can run in: ${allowed.join(", ")}`
7833
+ });
7834
+ return;
7835
+ }
7836
+ scopes.push(scope);
7837
+ });
7838
+ return scopes;
7839
+ }
7840
+ function severityIssues(value, path, scopes, issues) {
7841
+ if (typeof value === "string") {
7842
+ if (!SEVERITIES.includes(value)) {
7843
+ issues.push({ path, message: `unknown severity ${JSON.stringify(value)} — use "error" or "warning"` });
7844
+ }
7845
+ return;
7846
+ }
7847
+ if (!isPlainObject3(value)) {
7848
+ issues.push({ path, message: 'must be "error", "warning", or a map from scope to one of them' });
7849
+ return;
7850
+ }
7851
+ for (const [scope, severity] of Object.entries(value)) {
7852
+ if (!scopes.includes(scope)) {
7853
+ issues.push({ path: [...path, scope], message: `names scope "${scope}", which this rule's scopes do not cover` });
7854
+ }
7855
+ if (typeof severity !== "string" || !SEVERITIES.includes(severity)) {
7856
+ issues.push({
7857
+ path: [...path, scope],
7858
+ message: `unknown severity ${JSON.stringify(severity)} — use "error" or "warning"`
7859
+ });
7860
+ }
7861
+ }
7862
+ }
7863
+ function patternIssues(source, flags, path, issues) {
7864
+ if (typeof source !== "string" || source.length === 0) {
7865
+ issues.push({ path, message: "must be a non-empty regular expression" });
7866
+ return;
7867
+ }
7868
+ if (source.length > CONFIGURED_PATTERN_MAX_LENGTH) {
7869
+ issues.push({
7870
+ path,
7871
+ message: `is ${source.length} characters, over the ${CONFIGURED_PATTERN_MAX_LENGTH}-character limit for a configured pattern`
7872
+ });
7873
+ return;
7874
+ }
7875
+ try {
7876
+ new RegExp(source, flags);
7877
+ } catch (err) {
7878
+ issues.push({ path, message: `does not compile: ${err.message}` });
7879
+ return;
7880
+ }
7881
+ if (!safeRegex(source, { limit: Number.MAX_SAFE_INTEGER })) {
7882
+ issues.push({
7883
+ path,
7884
+ message: "has star height above one (a repeated group that itself repeats), which can take exponential time — " + "safe-regex2 refuses it. The shipped defaults are not held to this limit, so a pattern copied from one of " + "them can still be refused here; rewrite it without the nested repetition."
7885
+ });
7886
+ }
7887
+ }
7888
+ function flagIssues(value, path, issues) {
7889
+ if (value === undefined)
7890
+ return "";
7891
+ if (typeof value !== "string") {
7892
+ issues.push({ path, message: 'must be a string of flags, e.g. "i"' });
7893
+ return "";
7894
+ }
7895
+ const seen = new Set;
7896
+ for (const flag of value) {
7897
+ if (!CONFIGURED_PROSE_FLAGS.includes(flag)) {
7898
+ issues.push({
7899
+ path,
7900
+ message: `unknown flag ${JSON.stringify(flag)} — only ${CONFIGURED_PROSE_FLAGS.map((f) => `"${f}"`).join(" and ")} are allowed`
7901
+ });
7902
+ return "";
7903
+ }
7904
+ if (seen.has(flag)) {
7905
+ issues.push({ path, message: `repeats the flag "${flag}"` });
7906
+ return "";
7907
+ }
7908
+ seen.add(flag);
7909
+ }
7910
+ return value;
7911
+ }
7912
+ function defaultsIssues(value, issues) {
7913
+ const base = ["defaults"];
7914
+ if (!isPlainObject3(value)) {
7915
+ issues.push({ path: base, message: 'must map a default rule id to "off" or an override' });
7916
+ return;
7917
+ }
7918
+ for (const [id, override] of Object.entries(value)) {
7919
+ const path = [...base, id];
7920
+ const rule = CONFIGURABLE_DEFAULT_RULES.find((candidate) => candidate.id === id);
7921
+ if (!rule) {
7922
+ issues.push({
7923
+ path,
7924
+ message: `unknown default rule id "${id}" — \`vinaya check --plan\` lists the rules each prose check runs`
7925
+ });
7926
+ continue;
7927
+ }
7928
+ if (override === "off")
7929
+ continue;
7930
+ if (!isPlainObject3(override)) {
7931
+ issues.push({ path, message: 'must be "off" or an object with any of scopes, severity, exempt' });
7932
+ continue;
7933
+ }
7934
+ for (const key of Object.keys(override)) {
7935
+ if (OVERRIDE_KEYS.includes(key))
7936
+ continue;
7937
+ issues.push({
7938
+ path: [...path, key],
7939
+ message: FIXED_DEFAULT_KEYS.includes(key) ? `a default rule's ${key} is fixed — add a custom rule under proseGates.rules.custom instead` : `unknown key "${key}" — a default rule takes only scopes, severity and exempt`
7940
+ });
7941
+ }
7942
+ const scopes = override.scopes === undefined ? [...rule.scopes] : scopeListIssues(override.scopes, [...path, "scopes"], allowedScopesFor(rule), issues);
7943
+ if (override.severity !== undefined && scopes)
7944
+ severityIssues(override.severity, [...path, "severity"], scopes, issues);
7945
+ if (override.exempt !== undefined)
7946
+ pathListIssues(override.exempt, [...path, "exempt"], issues);
7947
+ }
7948
+ }
7949
+ function customIssues(value, issues) {
7950
+ if (!Array.isArray(value)) {
7951
+ issues.push({ path: ["custom"], message: "must be a list of rules" });
7952
+ return;
7953
+ }
7954
+ const ids = new Set;
7955
+ value.forEach((rule, index) => {
7956
+ const path = ["custom", index];
7957
+ if (!isPlainObject3(rule)) {
7958
+ issues.push({ path, message: "must be a rule object" });
7959
+ return;
7960
+ }
7961
+ for (const key of Object.keys(rule)) {
7962
+ if (!CUSTOM_KEYS.includes(key)) {
7963
+ issues.push({ path: [...path, key], message: `unknown key "${key}" — a rule takes ${CUSTOM_KEYS.join(", ")}` });
7964
+ }
7965
+ }
7966
+ if (typeof rule.id !== "string" || rule.id.length === 0) {
7967
+ issues.push({ path: [...path, "id"], message: "a custom rule needs an id" });
7968
+ } else if (DEFAULT_IDS.has(rule.id)) {
7969
+ issues.push({
7970
+ path: [...path, "id"],
7971
+ message: `"${rule.id}" is a default rule id — a custom rule needs its own id; retune the default under proseGates.rules.defaults instead`
7972
+ });
7973
+ } else if (ids.has(rule.id)) {
7974
+ issues.push({ path: [...path, "id"], message: `"${rule.id}" is used by an earlier custom rule` });
7975
+ } else {
7976
+ ids.add(rule.id);
7977
+ }
7978
+ if (typeof rule.means !== "string" || rule.means.trim().length === 0) {
7979
+ issues.push({ path: [...path, "means"], message: "a custom rule needs a message (`means`)" });
7980
+ }
7981
+ let scopes = null;
7982
+ if (rule.scopes === undefined) {
7983
+ issues.push({ path: [...path, "scopes"], message: "a custom rule needs at least one scope (`scopes`)" });
7984
+ } else {
7985
+ scopes = scopeListIssues(rule.scopes, [...path, "scopes"], CONFIGURABLE_PROSE_SCOPES, issues);
7986
+ }
7987
+ if (scopes && new Set(scopes.map(groupOfScope)).size > 1) {
7988
+ issues.push({
7989
+ path: [...path, "scopes"],
7990
+ message: 'mixes scopes of both prose checks — "repository" belongs to retired-vocabulary and every other scope to reader-resolvable-prose; write one rule per check'
7991
+ });
7992
+ }
7993
+ const flags = flagIssues(rule.flags, [...path, "flags"], issues);
7994
+ if (rule.pattern === undefined && rule.patterns === undefined) {
7995
+ issues.push({
7996
+ path: [...path, "pattern"],
7997
+ message: "a custom rule needs a `pattern` or a per-scope `patterns` map"
7998
+ });
7999
+ }
8000
+ if (rule.pattern !== undefined)
8001
+ patternIssues(rule.pattern, flags, [...path, "pattern"], issues);
8002
+ if (rule.patterns !== undefined) {
8003
+ if (!isPlainObject3(rule.patterns)) {
8004
+ issues.push({ path: [...path, "patterns"], message: "must map a scope to a regular expression" });
8005
+ } else {
8006
+ for (const [scope, source] of Object.entries(rule.patterns)) {
8007
+ if (scopes && !scopes.includes(scope)) {
8008
+ issues.push({
8009
+ path: [...path, "patterns", scope],
8010
+ message: `names scope "${scope}", which this rule's scopes do not cover`
8011
+ });
8012
+ continue;
8013
+ }
8014
+ patternIssues(source, flags, [...path, "patterns", scope], issues);
8015
+ }
8016
+ if (rule.pattern === undefined && scopes) {
8017
+ for (const scope of scopes) {
8018
+ if (!(scope in rule.patterns)) {
8019
+ issues.push({
8020
+ path: [...path, "patterns"],
8021
+ message: `has no pattern for scope "${scope}" — add one, or a \`pattern\` every other scope uses`
8022
+ });
8023
+ }
8024
+ }
8025
+ }
8026
+ }
8027
+ }
8028
+ if (rule.severity !== undefined && scopes)
8029
+ severityIssues(rule.severity, [...path, "severity"], scopes, issues);
8030
+ if (rule.exempt !== undefined)
8031
+ pathListIssues(rule.exempt, [...path, "exempt"], issues);
8032
+ });
8033
+ }
8034
+ function proseRulesIssues(value) {
8035
+ const issues = [];
8036
+ if (!isPlainObject3(value))
8037
+ return [{ path: [], message: "must be an object with any of exempt, defaults, custom" }];
8038
+ for (const key of Object.keys(value)) {
8039
+ if (!["exempt", "defaults", "custom"].includes(key)) {
8040
+ issues.push({ path: [key], message: `unknown key "${key}" — proseGates.rules takes exempt, defaults and custom` });
8041
+ }
8042
+ }
8043
+ if (value.exempt !== undefined)
8044
+ pathListIssues(value.exempt, ["exempt"], issues);
8045
+ if (value.defaults !== undefined)
8046
+ defaultsIssues(value.defaults, issues);
8047
+ if (value.custom !== undefined)
8048
+ customIssues(value.custom, issues);
8049
+ return issues;
8050
+ }
8051
+ var ProseRulesSchema = z5.unknown().superRefine((value, ctx) => {
8052
+ for (const issue of proseRulesIssues(value)) {
8053
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, path: issue.path, message: issue.message });
8054
+ }
8055
+ }).transform((value) => value);
8056
+ var PublishedProseSchema = z5.object({
8057
+ allow: z5.array(z5.string().min(1)).optional()
8058
+ }).strict();
8059
+
6850
8060
  // src/lib/config.ts
6851
- var EnvEntrySchema = z5.union([
6852
- z5.literal(true),
6853
- z5.object({ optional: z5.literal(true) }),
6854
- z5.object({ anyOf: z5.array(z5.string()).min(2) }),
6855
- z5.string()
8061
+ var EnvEntrySchema = z6.union([
8062
+ z6.literal(true),
8063
+ z6.object({ optional: z6.literal(true) }),
8064
+ z6.object({ anyOf: z6.array(z6.string()).min(2) }),
8065
+ z6.string()
6856
8066
  ]);
6857
- var CheckEntrySchema = z5.object({
6858
- run: z5.string(),
6859
- scope: z5.enum(["diff", "full"]),
6860
- include: z5.array(z5.string()).optional(),
6861
- args: z5.array(z5.string()).optional(),
6862
- timeoutMs: z5.number().optional(),
6863
- env: z5.record(z5.string(), EnvEntrySchema).optional(),
6864
- requiresOpenPr: z5.boolean().optional(),
6865
- ownWorkflow: z5.boolean().optional(),
6866
- principalOwed: z5.literal(true).optional(),
6867
- validates: z5.enum(["body", "issue"]).optional()
8067
+ var CheckEntrySchema = z6.object({
8068
+ run: z6.string(),
8069
+ scope: z6.enum(["diff", "full"]),
8070
+ include: z6.array(z6.string()).optional(),
8071
+ args: z6.array(z6.string()).optional(),
8072
+ timeoutMs: z6.number().optional(),
8073
+ env: z6.record(z6.string(), EnvEntrySchema).optional(),
8074
+ requiresOpenPr: z6.boolean().optional(),
8075
+ ownWorkflow: z6.boolean().optional(),
8076
+ principalOwed: z6.literal(true).optional(),
8077
+ validates: z6.enum(["body", "issue"]).optional(),
8078
+ advisory: z6.literal(true).optional()
6868
8079
  }).superRefine((entry, ctx) => {
6869
8080
  if (!entry.env)
6870
8081
  return;
@@ -6874,22 +8085,22 @@ var CheckEntrySchema = z5.object({
6874
8085
  const members = value.anyOf;
6875
8086
  if (new Set(members).size !== members.length) {
6876
8087
  ctx.addIssue({
6877
- code: z5.ZodIssueCode.custom,
8088
+ code: z6.ZodIssueCode.custom,
6878
8089
  message: `env.${key}.anyOf has duplicate members`,
6879
8090
  path: ["env", key, "anyOf"]
6880
8091
  });
6881
8092
  }
6882
8093
  if (!members.includes(key)) {
6883
8094
  ctx.addIssue({
6884
- code: z5.ZodIssueCode.custom,
8095
+ code: z6.ZodIssueCode.custom,
6885
8096
  message: `env.${key}.anyOf must include "${key}" itself as a member`,
6886
8097
  path: ["env", key, "anyOf"]
6887
8098
  });
6888
8099
  }
6889
8100
  }
6890
8101
  });
6891
- var RoleEntrySchema = z5.object({
6892
- contract: z5.string().refine((p) => p.includes("/"), {
8102
+ var RoleEntrySchema = z6.object({
8103
+ contract: z6.string().refine((p) => p.includes("/"), {
6893
8104
  message: 'must be a path (contain at least one "/"), not a bare filename'
6894
8105
  })
6895
8106
  });
@@ -6913,17 +8124,17 @@ var BRIEF_BUILTINS = [
6913
8124
  "briefSections",
6914
8125
  "milestoneShape"
6915
8126
  ];
6916
- var BriefSectionSchema = z5.union([
6917
- z5.object({ builtin: z5.enum(BRIEF_BUILTINS) }),
6918
- z5.object({ heading: z5.string().min(1), name: z5.string().optional() }),
6919
- z5.object({ field: z5.string().min(1), name: z5.string().optional() }),
6920
- z5.object({ phrase: z5.string().min(1), name: z5.string().optional() })
8127
+ var BriefSectionSchema = z6.union([
8128
+ z6.object({ builtin: z6.enum(BRIEF_BUILTINS) }),
8129
+ z6.object({ heading: z6.string().min(1), name: z6.string().optional() }),
8130
+ z6.object({ field: z6.string().min(1), name: z6.string().optional() }),
8131
+ z6.object({ phrase: z6.string().min(1), name: z6.string().optional() })
6921
8132
  ]);
6922
- var BriefSchemaSchema = z5.object({
6923
- pr: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6924
- issue: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6925
- milestone: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6926
- ack: z5.array(z5.enum(BRIEF_BUILTINS)).optional()
8133
+ var BriefSchemaSchema = z6.object({
8134
+ pr: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8135
+ issue: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8136
+ milestone: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8137
+ ack: z6.array(z6.enum(BRIEF_BUILTINS)).optional()
6927
8138
  });
6928
8139
  function isSafeRepoRelPath(p) {
6929
8140
  if (p.length === 0)
@@ -6932,7 +8143,7 @@ function isSafeRepoRelPath(p) {
6932
8143
  return false;
6933
8144
  return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
6934
8145
  }
6935
- var SafeRepoRelPath = z5.string().refine(isSafeRepoRelPath, {
8146
+ var SafeRepoRelPath = z6.string().refine(isSafeRepoRelPath, {
6936
8147
  message: "must be a repo-root-relative path with no `..` segment or absolute root"
6937
8148
  });
6938
8149
  var CANONICAL_HOOK_BLOCK_PREFIXES = [".git/", ".husky/", ".vinaya/hooks/", ".claude/hooks/"];
@@ -6942,22 +8153,22 @@ function isCanonicalHookBlockPath(p) {
6942
8153
  var ManagedHookBlockPath = SafeRepoRelPath.refine(isCanonicalHookBlockPath, {
6943
8154
  message: `must start with one of ${CANONICAL_HOOK_BLOCK_PREFIXES.join(", ")} (byte-exact, case-sensitive)`
6944
8155
  });
6945
- var ManagedBlockRecordSchema = z5.object({
8156
+ var ManagedBlockRecordSchema = z6.object({
6946
8157
  path: ManagedHookBlockPath,
6947
- marker: z5.string(),
6948
- comment: z5.enum(["hash", "html"])
8158
+ marker: z6.string(),
8159
+ comment: z6.enum(["hash", "html"])
6949
8160
  });
6950
- var ManagedManifestSchema = z5.object({
6951
- version: z5.number().int().positive(),
6952
- files: z5.array(SafeRepoRelPath),
6953
- blocks: z5.array(ManagedBlockRecordSchema),
6954
- labels: z5.array(z5.string()),
6955
- agents: z5.array(z5.enum(AGENT_VENDORS)).optional()
8161
+ var ManagedManifestSchema = z6.object({
8162
+ version: z6.number().int().positive(),
8163
+ files: z6.array(SafeRepoRelPath),
8164
+ blocks: z6.array(ManagedBlockRecordSchema),
8165
+ labels: z6.array(z6.string()),
8166
+ agents: z6.array(z6.enum(AGENT_VENDORS)).optional()
6956
8167
  });
6957
- var ProjectEntrySchema = z5.object({
6958
- name: z5.string().min(1),
6959
- description: z5.string().min(1).optional(),
6960
- path: z5.string().min(1).optional()
8168
+ var ProjectEntrySchema = z6.object({
8169
+ name: z6.string().min(1),
8170
+ description: z6.string().min(1).optional(),
8171
+ path: z6.string().min(1).optional()
6961
8172
  });
6962
8173
  function parseTokensCollectDeclaration(value) {
6963
8174
  const m = value.trim().match(/^(\S+)\s+(\S+)$/);
@@ -6968,90 +8179,90 @@ function parseTokensCollectDeclaration(value) {
6968
8179
  return null;
6969
8180
  return { interpreter, script };
6970
8181
  }
6971
- var VinayaConfigSchema = z5.object({
6972
- rings: z5.object({
6973
- ring1_forgeWriteInterception: z5.boolean(),
6974
- ring2_asyncAudits: z5.boolean()
8182
+ var VinayaConfigObjectSchema = z6.object({
8183
+ rings: z6.object({
8184
+ ring1_forgeWriteInterception: z6.boolean(),
8185
+ ring2_asyncAudits: z6.boolean()
6975
8186
  }).optional(),
6976
- checks: z5.record(z5.string(), CheckEntrySchema).optional(),
6977
- roles: z5.record(z5.string(), RoleEntrySchema).optional(),
8187
+ checks: z6.record(z6.string(), CheckEntrySchema).optional(),
8188
+ roles: z6.record(z6.string(), RoleEntrySchema).optional(),
6978
8189
  briefSchema: BriefSchemaSchema.optional(),
6979
8190
  managed: ManagedManifestSchema.optional(),
6980
- principals: z5.array(z5.string()).min(1).optional(),
6981
- releaseActor: z5.string().min(1).optional(),
6982
- ci: z5.object({ setup: z5.string().min(1) }).optional(),
6983
- tokens: z5.object({
6984
- collect: z5.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
8191
+ principals: z6.array(z6.string()).min(1).optional(),
8192
+ releaseActor: z6.string().min(1).optional(),
8193
+ ci: z6.object({ setup: z6.string().min(1) }).optional(),
8194
+ tokens: z6.object({
8195
+ collect: z6.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
6985
8196
  message: 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
6986
8197
  })
6987
8198
  }).optional(),
6988
- blastRadius: z5.object({ extraDomains: z5.array(z5.string()).optional() }).optional(),
6989
- proseGates: z5.object({
6990
- doctrineRoot: z5.string().min(1).optional(),
6991
- readerFacingPrefix: z5.string().min(1).optional(),
6992
- readerFacingSuffix: z5.string().min(1).optional(),
6993
- legacySlugDir: z5.string().min(1).optional(),
6994
- sourceComments: z5.object({
6995
- globs: z5.array(z5.string().min(1)).optional(),
6996
- allowlist: z5.array(z5.string().min(1)).optional(),
6997
- severity: z5.enum(["warning", "error"]).optional()
8199
+ blastRadius: z6.object({ extraDomains: z6.array(z6.string()).optional() }).optional(),
8200
+ proseGates: z6.object({
8201
+ doctrineRoot: z6.string().min(1).optional(),
8202
+ readerFacingPrefix: z6.string().min(1).optional(),
8203
+ readerFacingSuffix: z6.string().min(1).optional(),
8204
+ legacySlugDir: z6.string().min(1).optional(),
8205
+ sourceComments: z6.object({
8206
+ globs: z6.array(z6.string().min(1)).optional(),
8207
+ allowlist: z6.array(z6.string().min(1)).optional(),
8208
+ severity: z6.enum(["warning", "error"]).optional()
6998
8209
  }).optional(),
6999
- specGrandfather: z5.union([z5.array(z5.string().min(1)), z5.record(z5.string().min(1), z5.number().int().min(0))]).optional(),
7000
- specPaths: z5.array(z5.string().min(1).refine((entry) => !entry.startsWith("/") && !/^[A-Za-z]:/.test(entry), {
7001
- message: "must be a repository-relative path, not an absolute one"
7002
- }).refine((entry) => !entry.split(/[\\/]/).includes(".."), {
7003
- message: "must stay inside the repository — no `..` segment"
7004
- })).optional()
8210
+ specGrandfather: z6.union([z6.array(z6.string().min(1)), z6.record(z6.string().min(1), z6.number().int().min(0))]).optional(),
8211
+ specPaths: z6.array(RepoRelativePathSchema).optional(),
8212
+ productPaths: z6.array(RepoRelativePathSchema).optional(),
8213
+ published: PublishedProseSchema.optional(),
8214
+ rules: ProseRulesSchema.optional()
7005
8215
  }).optional(),
7006
- projects: z5.array(ProjectEntrySchema).optional(),
7007
- dispatch: z5.object({
7008
- timeoutMs: z5.number().int().positive().optional(),
7009
- killGraceMs: z5.number().int().positive().optional(),
7010
- agent: z5.enum(["claude", "codex", "gemini"]).optional()
8216
+ projects: z6.array(ProjectEntrySchema).optional(),
8217
+ dispatch: z6.object({
8218
+ timeoutMs: z6.number().int().positive().optional(),
8219
+ reviewerTimeoutMs: z6.number().int().positive().optional(),
8220
+ killGraceMs: z6.number().int().positive().optional(),
8221
+ agent: z6.enum(["claude", "codex"]).optional()
7011
8222
  }).optional(),
7012
- reviewPolicy: z5.object({
7013
- codeReviewThreshold: z5.string().min(1).optional(),
7014
- securityThreshold: z5.string().min(1).optional(),
7015
- maxRounds: z5.number().optional(),
7016
- maxTaskMinutes: z5.number().optional()
8223
+ reviewPolicy: z6.object({
8224
+ codeReviewThreshold: z6.string().min(1).optional(),
8225
+ securityThreshold: z6.string().min(1).optional(),
8226
+ maxRounds: z6.number().optional(),
8227
+ maxTaskMinutes: z6.number().optional()
7017
8228
  }).optional(),
7018
- securityScan: z5.object({
7019
- command: z5.array(z5.string().min(1)).min(1)
8229
+ securityScan: z6.object({
8230
+ command: z6.array(z6.string().min(1)).min(1)
7020
8231
  }).optional(),
7021
- gateCutovers: z5.object({
7022
- objectivesSinceIssue: z5.number().int().nonnegative().optional(),
7023
- briefSectionsSinceIssue: z5.number().int().nonnegative().optional(),
7024
- documentationSinceIssue: z5.number().int().nonnegative().optional(),
7025
- briefRulesSincePr: z5.number().int().nonnegative().optional(),
7026
- agentBoxesRefusedSincePr: z5.number().int().nonnegative().optional()
8232
+ gateCutovers: z6.object({
8233
+ objectivesSinceIssue: z6.number().int().nonnegative().optional(),
8234
+ briefSectionsSinceIssue: z6.number().int().nonnegative().optional(),
8235
+ documentationSinceIssue: z6.number().int().nonnegative().optional(),
8236
+ briefRulesSincePr: z6.number().int().nonnegative().optional(),
8237
+ agentBoxesRefusedSincePr: z6.number().int().nonnegative().optional()
7027
8238
  }).optional(),
7028
- planning: z5.object({
7029
- collisionThreshold: z5.number().int().nonnegative().optional()
8239
+ planning: z6.object({
8240
+ collisionThreshold: z6.number().int().nonnegative().optional()
7030
8241
  }).optional(),
7031
- prePush: z5.object({
7032
- alwaysRun: z5.array(z5.string()).optional()
8242
+ prePush: z6.object({
8243
+ alwaysRun: z6.array(z6.string()).optional()
7033
8244
  }).optional(),
7034
- report: z5.object({
7035
- commandTimeoutMs: z5.number().int().positive().optional()
8245
+ report: z6.object({
8246
+ commandTimeoutMs: z6.number().int().positive().optional()
7036
8247
  }).superRefine((report, ctx) => {
7037
8248
  const commandTimeoutMs = report.commandTimeoutMs;
7038
8249
  if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
7039
8250
  ctx.addIssue({
7040
- code: z5.ZodIssueCode.custom,
8251
+ code: z6.ZodIssueCode.custom,
7041
8252
  path: ["commandTimeoutMs"],
7042
8253
  message: "must be at most 3600000 (1 hour)"
7043
8254
  });
7044
8255
  }
7045
8256
  }).optional(),
7046
- logPublish: z5.unknown().refine((v) => v === undefined, {
8257
+ logPublish: z6.unknown().refine((v) => v === undefined, {
7047
8258
  message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
7048
8259
  }),
7049
- runtimeDir: z5.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
7050
- logs: z5.object({
7051
- folder: z5.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
7052
- url: z5.string().url().optional(),
7053
- headers: z5.record(z5.string()).optional(),
7054
- readHeaders: z5.record(z5.string()).optional(),
8260
+ runtimeDir: z6.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
8261
+ logs: z6.object({
8262
+ folder: z6.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
8263
+ url: z6.string().url().optional(),
8264
+ headers: z6.record(z6.string()).optional(),
8265
+ readHeaders: z6.record(z6.string()).optional(),
7055
8266
  events: CustomEventDeclarationsSchema.optional()
7056
8267
  }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
7057
8268
  message: "logs: set at most one of folder/url"
@@ -7059,8 +8270,33 @@ var VinayaConfigSchema = z5.object({
7059
8270
  message: "logs: headers requires url"
7060
8271
  }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
7061
8272
  message: "logs: readHeaders requires url"
7062
- }).optional()
8273
+ }).optional(),
8274
+ decisionRecords: z6.object({
8275
+ path: RepoRelativePathSchema
8276
+ }).strict().optional()
7063
8277
  });
8278
+ function decisionRecordsPathIssue(path, doctrineRoot) {
8279
+ const reason = outsideRepositoryReason(path);
8280
+ if (reason)
8281
+ return reason;
8282
+ const folder = normalizeSpecPath(path);
8283
+ if (folder === "" || folder === ".")
8284
+ return "must name a folder, not the repository root";
8285
+ const root = normalizeSpecPath(doctrineRoot ?? "aeg-root");
8286
+ if (folder === root || folder.startsWith(`${root}/`)) {
8287
+ return `must be outside the doctrine tree "${root}" — decision records belong to this repository, not to the doctrine it ships`;
8288
+ }
8289
+ return null;
8290
+ }
8291
+ var VinayaConfigSchema = VinayaConfigObjectSchema.superRefine((config, ctx) => {
8292
+ const path = config.decisionRecords?.path;
8293
+ if (path === undefined || outsideRepositoryReason(path))
8294
+ return;
8295
+ const issue = decisionRecordsPathIssue(path, config.proseGates?.doctrineRoot);
8296
+ if (issue)
8297
+ ctx.addIssue({ code: z6.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
8298
+ });
8299
+ var VinayaConfigShape = VinayaConfigObjectSchema.shape;
7064
8300
  var GLOBAL_VINAYA_HOME = join(homedir(), ".vinaya");
7065
8301
  var GLOBAL_CONFIG_PATH = join(GLOBAL_VINAYA_HOME, "config.json");
7066
8302
  var LOCAL_CONFIG_FILENAME = "vinaya.config.json";
@@ -7141,9 +8377,6 @@ function stripGlobalOnlyKeys(config, path) {
7141
8377
  }
7142
8378
  return result;
7143
8379
  }
7144
- function resolvePrincipalAllowlist(config) {
7145
- return config?.principals ?? PRINCIPAL_ALLOWLIST;
7146
- }
7147
8380
  function resolveReleaseActor(config) {
7148
8381
  return config?.releaseActor ?? DEFAULT_RELEASE_ACTOR;
7149
8382
  }
@@ -7279,13 +8512,14 @@ function readTrustAnchorConfigAtRef(ref) {
7279
8512
  });
7280
8513
  return Buffer.from(raw, "utf-8").toString("base64");
7281
8514
  }
8515
+ var NO_TRUST_ANCHOR_REPO_MESSAGE = "could not resolve repo identity for the trust-anchor read";
7282
8516
  function ghFetchTrustAnchorConfig() {
7283
8517
  const probeRef = resolveCiTrustAnchorProbeRef();
7284
8518
  if (probeRef)
7285
8519
  return readTrustAnchorConfigAtRef(probeRef);
7286
8520
  const repo = trustAnchorRepo();
7287
8521
  if (!repo)
7288
- throw new Error("could not resolve repo identity for the trust-anchor read");
8522
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
7289
8523
  return execFileSync2("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
7290
8524
  encoding: "utf-8",
7291
8525
  stdio: ["ignore", "pipe", "pipe"]
@@ -7302,7 +8536,7 @@ async function ghFetchTrustAnchorConfigAsync() {
7302
8536
  }
7303
8537
  const repo = await trustAnchorRepoAsync();
7304
8538
  if (!repo)
7305
- throw new Error("could not resolve repo identity for the trust-anchor read");
8539
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
7306
8540
  const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4, killSignal: "SIGKILL" });
7307
8541
  return stdout;
7308
8542
  }
@@ -7328,6 +8562,47 @@ function loadTrustAnchorConfig(fetcher = ghFetchTrustAnchorConfig) {
7328
8562
  }
7329
8563
  return parseTrustAnchorContent(base64);
7330
8564
  }
8565
+ class PrincipalsUnresolvedError extends Error {
8566
+ kind;
8567
+ constructor(kind, message) {
8568
+ super(message);
8569
+ this.name = "PrincipalsUnresolvedError";
8570
+ this.kind = kind;
8571
+ }
8572
+ }
8573
+ var PRINCIPALS_FIX = 'add "principals": [...] to vinaya.config.json on the default branch';
8574
+ function fetchFailureReason(err) {
8575
+ const stderr = err?.stderr;
8576
+ const text = (typeof stderr === "string" ? stderr : stderr?.toString() ?? "").trim();
8577
+ return text.split(`
8578
+ `)[0]?.trim() || firstLine(err);
8579
+ }
8580
+ function principalsNotConfigured(why) {
8581
+ return new PrincipalsUnresolvedError("not-configured", `no Principal is configured (${why}) — ${PRINCIPALS_FIX}.`);
8582
+ }
8583
+ function resolveTrustedPrincipals(fetcher = ghFetchTrustAnchorConfig) {
8584
+ let content;
8585
+ try {
8586
+ content = fetcher();
8587
+ } catch (err) {
8588
+ if (err?.message === NO_TRUST_ANCHOR_REPO_MESSAGE) {
8589
+ throw principalsNotConfigured("no repository resolves for the read");
8590
+ }
8591
+ if (isMissingFileError(err))
8592
+ throw principalsNotConfigured("the default branch has no vinaya.config.json");
8593
+ throw new PrincipalsUnresolvedError("read-failed", `could not read "principals" from vinaya.config.json on the default branch: ${fetchFailureReason(err)}`);
8594
+ }
8595
+ const unusable = { why: "" };
8596
+ const config = parseTrustAnchorContent(content, (why) => {
8597
+ unusable.why = why;
8598
+ });
8599
+ if (config === null) {
8600
+ throw principalsNotConfigured(`vinaya.config.json on the default branch ${unusable.why ? `is unusable: ${unusable.why}` : "is empty"}`);
8601
+ }
8602
+ if (!config.principals)
8603
+ throw principalsNotConfigured('vinaya.config.json on the default branch sets no "principals"');
8604
+ return config.principals;
8605
+ }
7331
8606
  async function loadTrustAnchorConfigAsync(fetcher = ghFetchTrustAnchorConfigAsync, options = {}) {
7332
8607
  const warn = options.quiet ? () => {} : warnTrustAnchorFallback;
7333
8608
  let base64;
@@ -7367,20 +8642,261 @@ function loadConfig() {
7367
8642
  const path = configPath();
7368
8643
  if (!path)
7369
8644
  return null;
8645
+ let text;
7370
8646
  try {
7371
- const raw = JSON.parse(readFileSync2(path, "utf-8"));
7372
- return stripGlobalOnlyKeys(VinayaConfigSchema.parse(raw), path);
7373
- } catch {
8647
+ text = readFileSync2(path, "utf-8");
8648
+ } catch (err) {
8649
+ reportInvalidConfigOnce(path, `unreadable: ${err.message}`);
7374
8650
  return null;
7375
8651
  }
8652
+ let raw;
8653
+ try {
8654
+ raw = JSON.parse(text);
8655
+ } catch (err) {
8656
+ reportInvalidConfigOnce(path, `invalid JSON: ${err.message}`);
8657
+ return null;
8658
+ }
8659
+ const parsed = VinayaConfigSchema.safeParse(raw);
8660
+ if (!parsed.success) {
8661
+ reportInvalidConfigOnce(path, schemaIssueDetail(parsed.error));
8662
+ return null;
8663
+ }
8664
+ return stripGlobalOnlyKeys(parsed.data, path);
8665
+ }
8666
+ function schemaIssueDetail(error) {
8667
+ return error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
8668
+ }
8669
+ var emittedInvalidConfigReports = new Set;
8670
+ function reportInvalidConfigOnce(path, detail) {
8671
+ const key = `${path}
8672
+ ${detail}`;
8673
+ if (emittedInvalidConfigReports.has(key))
8674
+ return;
8675
+ emittedInvalidConfigReports.add(key);
8676
+ const message = `${path} is not a valid Vinaya configuration (${detail}) — falling back to built-in defaults.`;
8677
+ const checkName = process.env.VINAYA_CHECK_NAME;
8678
+ if (checkName) {
8679
+ emitCheckError({
8680
+ schema: CHECK_SCHEMA_VERSION,
8681
+ check: checkName,
8682
+ severity: "warning",
8683
+ message,
8684
+ agent_recovery_prompt: `Fix the failing keys in ${path} (${detail}) so the file parses and satisfies the configuration schema, then re-run.`,
8685
+ file: path
8686
+ });
8687
+ return;
8688
+ }
8689
+ console.error(`⚠ ${message}`);
8690
+ }
8691
+ function loadConfigChecked() {
8692
+ const path = configPath();
8693
+ if (!path)
8694
+ return { ok: true, config: null };
8695
+ let raw;
8696
+ try {
8697
+ raw = JSON.parse(readFileSync2(path, "utf-8"));
8698
+ } catch (err) {
8699
+ return { ok: false, path, error: `invalid JSON: ${err.message}` };
8700
+ }
8701
+ const parsed = VinayaConfigSchema.safeParse(raw);
8702
+ if (!parsed.success) {
8703
+ return { ok: false, path, error: schemaIssueDetail(parsed.error) };
8704
+ }
8705
+ return { ok: true, config: stripGlobalOnlyKeys(parsed.data, path) };
7376
8706
  }
7377
8707
  var TOKENS_COLLECT_TRUST_PATH = join(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
7378
8708
 
7379
- // src/checks/contract.ts
7380
- var CHECK_SCHEMA_VERSION = 1;
7381
- function emitCheckError(error) {
7382
- process.stderr.write(`${JSON.stringify(error)}
7383
- `);
8709
+ // src/lib/forge-snapshot.ts
8710
+ import { existsSync as existsSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
8711
+ import { join as join2 } from "node:path";
8712
+
8713
+ // src/lib/forge-read.ts
8714
+ import { execFileSync as execFileSync3 } from "node:child_process";
8715
+ var FORGE_READ_CEILING_BYTES = 64 * 1024 * 1024;
8716
+ var PAGE_SIZE = 100;
8717
+ var ghRunner = (args, maxBuffer) => execFileSync3("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer });
8718
+
8719
+ class ForgeReadOversizeError extends Error {
8720
+ subject;
8721
+ ceilingBytes;
8722
+ observedBytes;
8723
+ constructor(subject, observedBytes, atLeast = false, ceilingBytes = FORGE_READ_CEILING_BYTES) {
8724
+ super(`The forge response for ${subject} is ${atLeast ? "at least " : ""}${observedBytes} bytes, above the ${ceilingBytes}-byte read ceiling (FORGE_READ_CEILING_BYTES) — refusing rather than buffering it.`);
8725
+ this.name = "ForgeReadOversizeError";
8726
+ this.subject = subject;
8727
+ this.ceilingBytes = ceilingBytes;
8728
+ this.observedBytes = observedBytes;
8729
+ }
8730
+ }
8731
+ function isForgeReadOversize(err) {
8732
+ return err instanceof ForgeReadOversizeError;
8733
+ }
8734
+ function isBufferOverflow(err) {
8735
+ return err?.code === "ENOBUFS";
8736
+ }
8737
+ function runBounded(runner, args, subject, usedBytes) {
8738
+ const remaining = FORGE_READ_CEILING_BYTES - usedBytes;
8739
+ let out;
8740
+ try {
8741
+ out = runner(args, remaining);
8742
+ } catch (err) {
8743
+ if (isBufferOverflow(err))
8744
+ throw new ForgeReadOversizeError(subject, FORGE_READ_CEILING_BYTES + 1, true);
8745
+ throw err;
8746
+ }
8747
+ const size = Buffer.byteLength(out, "utf8");
8748
+ if (usedBytes + size > FORGE_READ_CEILING_BYTES)
8749
+ throw new ForgeReadOversizeError(subject, usedBytes + size);
8750
+ return out;
8751
+ }
8752
+ function readRestCommentRows(number, subjectLabel = `Issue ${number}`, runner = ghRunner) {
8753
+ const rows = [];
8754
+ let used = 0;
8755
+ for (let page = 1;; page++) {
8756
+ const out = runBounded(runner, ["api", `repos/{owner}/{repo}/issues/${number}/comments?per_page=${PAGE_SIZE}&page=${page}`], subjectLabel, used);
8757
+ used += Buffer.byteLength(out, "utf8");
8758
+ const pageRows = JSON.parse(out);
8759
+ rows.push(...pageRows);
8760
+ if (pageRows.length < PAGE_SIZE)
8761
+ return rows;
8762
+ }
8763
+ }
8764
+ function readIssueComments(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
8765
+ const number = resolveNumber(issue, subjectLabel, runner);
8766
+ const fromSnapshot = snapshotComments(number);
8767
+ if (fromSnapshot !== null)
8768
+ return fromSnapshot;
8769
+ return readRestCommentRows(number, subjectLabel, runner).map((r) => ({
8770
+ body: r.body ?? "",
8771
+ url: r.html_url ?? "",
8772
+ author: r.user?.login ? { login: r.user.login } : null
8773
+ }));
8774
+ }
8775
+ function readIssueBody(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
8776
+ if (forgeSnapshotDir() !== null) {
8777
+ const fromSnapshot = snapshotBody(resolveNumber(issue, subjectLabel, runner));
8778
+ if (fromSnapshot !== null)
8779
+ return fromSnapshot;
8780
+ }
8781
+ const out = runBounded(runner, ["issue", "view", String(issue), "--json", "body"], subjectLabel, 0);
8782
+ return JSON.parse(out).body ?? "";
8783
+ }
8784
+ function readIssueFields(issue, fields, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
8785
+ return JSON.parse(runBounded(runner, ["issue", "view", String(issue), "--json", fields], subjectLabel, 0));
8786
+ }
8787
+ function resolveNumber(issue, subjectLabel, runner) {
8788
+ if (typeof issue === "number")
8789
+ return issue;
8790
+ if (/^\d+$/.test(issue))
8791
+ return Number(issue);
8792
+ return readIssueFields(issue, "number", subjectLabel, runner).number;
8793
+ }
8794
+
8795
+ // src/lib/forge-snapshot.ts
8796
+ var FORGE_SNAPSHOT_DIR_ENV = "VINAYA_FORGE_SNAPSHOT_DIR";
8797
+ var PULL_FILE = "pull.json";
8798
+ var PULL_COMMENTS_FILE = "pull-comments.json";
8799
+ var ISSUE_FILE = "issue.json";
8800
+ var ISSUE_COMMENTS_FILE = "issue-comments.json";
8801
+ function forgeSnapshotDir(env = process.env) {
8802
+ if (env.GITHUB_ACTIONS !== "true")
8803
+ return null;
8804
+ const dir = env[FORGE_SNAPSHOT_DIR_ENV];
8805
+ return dir ? dir : null;
8806
+ }
8807
+
8808
+ class ForgeSnapshotIncompleteError extends Error {
8809
+ constructor(dir, file) {
8810
+ super(`the forge snapshot ${dir} has no ${file} — the pull request read that writes it did not complete, so this check refuses to read the forge in its place.`);
8811
+ this.name = "ForgeSnapshotIncompleteError";
8812
+ }
8813
+ }
8814
+
8815
+ class ForgeSnapshotIssueNotFoundError extends Error {
8816
+ constructor(issue) {
8817
+ super(`Issue #${issue} did not resolve (HTTP 404) when this run's forge snapshot was read.`);
8818
+ this.name = "ForgeSnapshotIssueNotFoundError";
8819
+ }
8820
+ }
8821
+ function readSnapshotFile(dir, file) {
8822
+ let text;
8823
+ try {
8824
+ text = readFileSync3(join2(dir, file), "utf8");
8825
+ } catch {
8826
+ throw new ForgeSnapshotIncompleteError(dir, file);
8827
+ }
8828
+ return JSON.parse(text);
8829
+ }
8830
+ function readComments(dir, file, number) {
8831
+ const parsed = readSnapshotFile(dir, file);
8832
+ if (parsed.number !== number)
8833
+ throw new ForgeSnapshotIncompleteError(dir, `${file} for #${number}`);
8834
+ return parsed.comments;
8835
+ }
8836
+ function snapshotPullRequest(number, env = process.env) {
8837
+ const dir = forgeSnapshotDir(env);
8838
+ if (dir === null)
8839
+ return null;
8840
+ const pull = readSnapshotFile(dir, PULL_FILE);
8841
+ return pull.number === number ? pull : null;
8842
+ }
8843
+ function snapshotIssue(number, env = process.env) {
8844
+ const dir = forgeSnapshotDir(env);
8845
+ if (dir === null)
8846
+ return null;
8847
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
8848
+ if (issue.number !== number)
8849
+ return null;
8850
+ if ("notFound" in issue)
8851
+ throw new ForgeSnapshotIssueNotFoundError(number);
8852
+ return issue;
8853
+ }
8854
+ function snapshotComments(number, env = process.env) {
8855
+ const dir = forgeSnapshotDir(env);
8856
+ if (dir === null)
8857
+ return null;
8858
+ if (snapshotPullRequest(number, env) !== null)
8859
+ return readComments(dir, PULL_COMMENTS_FILE, number);
8860
+ if (snapshotIssue(number, env) !== null)
8861
+ return readComments(dir, ISSUE_COMMENTS_FILE, number);
8862
+ return null;
8863
+ }
8864
+ function snapshotBody(number, env = process.env) {
8865
+ const pull = snapshotPullRequest(number, env);
8866
+ if (pull !== null)
8867
+ return pull.body;
8868
+ return snapshotIssue(number, env)?.body ?? null;
8869
+ }
8870
+ function incompleteForgeSnapshot(env = process.env) {
8871
+ const dir = forgeSnapshotDir(env);
8872
+ if (dir === null)
8873
+ return null;
8874
+ for (const file of [PULL_FILE, PULL_COMMENTS_FILE, ISSUE_FILE]) {
8875
+ if (!existsSync2(join2(dir, file)))
8876
+ return new ForgeSnapshotIncompleteError(dir, file).message;
8877
+ }
8878
+ try {
8879
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
8880
+ if (typeof issue.number === "number" && !("notFound" in issue) && !existsSync2(join2(dir, ISSUE_COMMENTS_FILE))) {
8881
+ return new ForgeSnapshotIncompleteError(dir, ISSUE_COMMENTS_FILE).message;
8882
+ }
8883
+ } catch (err) {
8884
+ return `the forge snapshot ${dir} has an unreadable ${ISSUE_FILE}: ${err.message}`;
8885
+ }
8886
+ return null;
8887
+ }
8888
+ function exitOnIncompleteForgeSnapshot(checkName, env = process.env) {
8889
+ const reason = incompleteForgeSnapshot(env);
8890
+ if (reason === null)
8891
+ return;
8892
+ emitCheckError({
8893
+ schema: CHECK_SCHEMA_VERSION,
8894
+ check: checkName,
8895
+ severity: "error",
8896
+ message: `${checkName}: ${reason}`,
8897
+ agent_recovery_prompt: `Re-run the whole workflow run so its pull request read step writes the snapshot again (its own log names the failed read), then let \`vinaya check ${checkName}\` re-run.`
8898
+ });
8899
+ process.exit(1);
7384
8900
  }
7385
8901
 
7386
8902
  // src/lib/numstat.ts
@@ -7694,8 +9210,11 @@ function checkBareDigits(rawBody) {
7694
9210
  // src/checks/bin/check-body-bare-digits.ts
7695
9211
  var CHECK_NAME = "body-bare-digits";
7696
9212
  function fetchPr(prNumber) {
9213
+ const fromSnapshot = snapshotPullRequest(prNumber);
9214
+ if (fromSnapshot !== null)
9215
+ return fromSnapshot;
7697
9216
  try {
7698
- const out = execFileSync3("gh", ["pr", "view", String(prNumber), "--json", "number,headRefName,author"], {
9217
+ const out = execFileSync4("gh", ["pr", "view", String(prNumber), "--json", "number,headRefName,author"], {
7699
9218
  encoding: "utf8",
7700
9219
  stdio: ["ignore", "pipe", "pipe"]
7701
9220
  });
@@ -7716,6 +9235,7 @@ function isExemptChangesetsReleasePr(prNumberStr) {
7716
9235
  return isChangesetsReleasePr(pr.headRefName, pr.author?.login ?? null, resolveReleaseActor(loadTrustAnchorConfig()));
7717
9236
  }
7718
9237
  function main() {
9238
+ exitOnIncompleteForgeSnapshot(CHECK_NAME);
7719
9239
  if (isExemptChangesetsReleasePr(process.env.PR_NUMBER)) {
7720
9240
  process.exit(0);
7721
9241
  }