@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,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/checks/bin/check-changeset-coverage.ts
4
- import { execFileSync as execFileSync9 } from "node:child_process";
5
- import { readdirSync as readdirSync3, readFileSync as readFileSync8 } from "node:fs";
6
- import { join as join10, relative as relative3 } from "node:path";
4
+ import { execFileSync as execFileSync10 } from "node:child_process";
5
+ import { readdirSync as readdirSync3, readFileSync as readFileSync9 } from "node:fs";
6
+ import { join as join11, relative as relative3 } from "node:path";
7
7
 
8
8
  // ../../packages/aeg-core/src/entry-point.ts
9
9
  import { realpathSync } from "node:fs";
@@ -44,7 +44,6 @@ var GATE_AUDIENCE = {
44
44
  };
45
45
  var NON_GATE_BINS = [
46
46
  "archive-task",
47
- "assign-task-issue",
48
47
  "dead-branch-audit",
49
48
  "eval-agent-compliance",
50
49
  "open-issue",
@@ -307,6 +306,25 @@ async function runAsync(args) {
307
306
  function ghApiGet(path) {
308
307
  return JSON.parse(run(["api", path]));
309
308
  }
309
+ var MAX_PER_PAGE = 100;
310
+ var MAX_PAGES = 100;
311
+ async function ghApiGetAllPagesAsync(pathWithoutPage, opts) {
312
+ const [base = pathWithoutPage, query = ""] = pathWithoutPage.split("?");
313
+ const params = new URLSearchParams(query);
314
+ params.set("per_page", String(MAX_PER_PAGE));
315
+ const all = [];
316
+ for (let page = 1;page <= MAX_PAGES; page++) {
317
+ params.set("page", String(page));
318
+ const args = ["api", `${base}?${params.toString()}`];
319
+ if (opts?.jq)
320
+ args.push("-q", opts.jq);
321
+ const batch = JSON.parse(await runAsync(args));
322
+ all.push(...batch);
323
+ if (batch.length < MAX_PER_PAGE)
324
+ return all;
325
+ }
326
+ throw new Error(`ghApiGetAllPagesAsync: "${pathWithoutPage}" did not terminate within ${MAX_PAGES} pages (${MAX_PAGES * MAX_PER_PAGE} items) — refusing to keep walking.`);
327
+ }
310
328
  function issueListByLabelArgs(owner, repo, label) {
311
329
  return [
312
330
  "issue",
@@ -718,6 +736,10 @@ function intentGoalForSlug(description, slug) {
718
736
  function matchesLegacyMilestone(milestones, slug) {
719
737
  return milestones.find((m) => m.title === slug) ?? null;
720
738
  }
739
+ var TRANCHE_SLUG_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*-v\d+$/;
740
+ function slugShapedTitles(milestones) {
741
+ return milestones.map((m) => m.title).filter((t) => TRANCHE_SLUG_SHAPE.test(t));
742
+ }
721
743
  function factsFromLegacyMilestone(milestone) {
722
744
  return {
723
745
  goal: milestone.description ?? "",
@@ -751,6 +773,90 @@ function findMilestoneForSlug(owner, repo, slug) {
751
773
  return resolveLegacyFacts(legacy, issues);
752
774
  return { goal: goalFromMilestones(milestones, slug), lifecycle: lifecycleFromIssues(issues) };
753
775
  }
776
+ function trancheSlugsFromLabels(labels) {
777
+ const slugs = [];
778
+ for (const l of labels) {
779
+ const slug = trancheSlugOf(l.name);
780
+ if (slug !== null)
781
+ slugs.push(slug);
782
+ }
783
+ return slugs;
784
+ }
785
+ async function indexTrancheMilestonesAsync(owner, repo) {
786
+ const [milestones, labels] = await Promise.all([
787
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`),
788
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`)
789
+ ]);
790
+ const active = [];
791
+ const archived = [];
792
+ const facts = new Map;
793
+ const legacySlugs = new Set(slugShapedTitles(milestones));
794
+ const legacyMilestoneBySlug = new Map(milestones.filter((m) => legacySlugs.has(m.title)).map((m) => [m.title, m]));
795
+ const newPathSlugs = trancheSlugsFromLabels(labels).filter((slug) => !legacySlugs.has(slug));
796
+ const uniqueNewPathSlugs = [...new Set(newPathSlugs)];
797
+ const uniqueLegacySlugs = [...legacySlugs];
798
+ const [legacyIssuesBySlug, newPathIssuesBySlug] = await Promise.all([
799
+ Promise.all(uniqueLegacySlugs.map((slug) => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug)))),
800
+ Promise.all(uniqueNewPathSlugs.map((slug) => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))))
801
+ ]);
802
+ uniqueLegacySlugs.forEach((slug, i) => {
803
+ const m = legacyMilestoneBySlug.get(slug);
804
+ if (!m)
805
+ return;
806
+ const ref = { slug, goal: m.description ?? "" };
807
+ const f = resolveLegacyFacts(m, legacyIssuesBySlug[i] ?? []);
808
+ if (f.lifecycle === "complete")
809
+ archived.push(ref);
810
+ else if (f.lifecycle === "active")
811
+ active.push(ref);
812
+ facts.set(slug, f);
813
+ });
814
+ uniqueNewPathSlugs.forEach((slug, i) => {
815
+ const issues = newPathIssuesBySlug[i] ?? [];
816
+ const lifecycle = lifecycleFromIssues(issues);
817
+ const goal = goalFromMilestones(milestones, slug);
818
+ const f = { goal, lifecycle };
819
+ facts.set(slug, f);
820
+ if (lifecycle === "active")
821
+ active.push({ slug, goal });
822
+ else if (lifecycle === "complete")
823
+ archived.push({ slug, goal });
824
+ });
825
+ return { active, archived, facts, legacySlugs };
826
+ }
827
+ async function indexTrancheMilestonesForSlugAsync(owner, repo, slug) {
828
+ const [milestones, labels, issues] = await Promise.all([
829
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`),
830
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`),
831
+ ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))
832
+ ]);
833
+ const active = [];
834
+ const archived = [];
835
+ const facts = new Map;
836
+ const legacySlugs = new Set;
837
+ const legacyMilestone = slugShapedTitles(milestones).includes(slug) ? matchesLegacyMilestone(milestones, slug) : null;
838
+ if (legacyMilestone) {
839
+ legacySlugs.add(slug);
840
+ const ref = { slug, goal: legacyMilestone.description ?? "" };
841
+ const f = resolveLegacyFacts(legacyMilestone, issues);
842
+ if (f.lifecycle === "complete")
843
+ archived.push(ref);
844
+ else if (f.lifecycle === "active")
845
+ active.push(ref);
846
+ facts.set(slug, f);
847
+ } else if (trancheSlugsFromLabels(labels).includes(slug)) {
848
+ const lifecycle = lifecycleFromIssues(issues);
849
+ const goal = goalFromMilestones(milestones, slug);
850
+ facts.set(slug, { goal, lifecycle });
851
+ if (lifecycle === "active")
852
+ active.push({ slug, goal });
853
+ else if (lifecycle === "complete")
854
+ archived.push({ slug, goal });
855
+ }
856
+ const openLegacyTitles = new Set(slugShapedTitles(milestones.filter((m) => m.state === "open")));
857
+ const otherOpenLegacySlugs = [...openLegacyTitles].filter((t) => t !== slug);
858
+ return { active, archived, facts, legacySlugs, otherOpenLegacySlugs };
859
+ }
754
860
 
755
861
  // ../../packages/aeg-forge-state/src/derive-from-forge.ts
756
862
  function trancheFromIssues(slug, issues, known) {
@@ -1411,6 +1517,125 @@ var graphql2 = withDefaults3(request, {
1411
1517
  method: "POST",
1412
1518
  url: "/graphql"
1413
1519
  });
1520
+
1521
+ // ../../packages/aeg-forge-state/src/fetch-provenance.ts
1522
+ var PROVENANCE_PATTERN = /^###\s+AEG provenance\b/im;
1523
+ function provenanceMatchesIssue(text, issueNum) {
1524
+ if (!PROVENANCE_PATTERN.test(text))
1525
+ return false;
1526
+ const m = text.match(/^-\s*Issue:\s*#(\d+)/im);
1527
+ return m !== null && Number(m[1]) === issueNum;
1528
+ }
1529
+ function isPrCloser(closer) {
1530
+ return closer !== null && typeof closer.number === "number";
1531
+ }
1532
+ async function fetchProvenanceViaCrossReferences(issueNums, owner, repo, token) {
1533
+ const result = new Map;
1534
+ if (issueNums.length === 0)
1535
+ return result;
1536
+ const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
1537
+ const perIssue = issueNums.map((n) => `
1538
+ i_${n}: issue(number: ${n}) {
1539
+ timelineItems(first: 50, itemTypes: [CROSS_REFERENCED_EVENT]) {
1540
+ nodes {
1541
+ ... on CrossReferencedEvent {
1542
+ source {
1543
+ ... on PullRequest {
1544
+ number
1545
+ body
1546
+ comments(first: 50) { nodes { body } }
1547
+ }
1548
+ }
1549
+ }
1550
+ }
1551
+ }
1552
+ }`).join("");
1553
+ const query = `query ProvenanceCrossRef($owner: String!, $repo: String!) {
1554
+ repository(owner: $owner, name: $repo) {${perIssue}
1555
+ }
1556
+ }`;
1557
+ let response;
1558
+ try {
1559
+ response = await client(query, { owner, repo });
1560
+ } catch {
1561
+ return result;
1562
+ }
1563
+ if (!response.repository)
1564
+ return result;
1565
+ for (const n of issueNums) {
1566
+ const raw = response.repository[`i_${n}`];
1567
+ const nodes = raw?.timelineItems?.nodes ?? [];
1568
+ const found = nodes.some(({ source }) => {
1569
+ if (!source || typeof source.number !== "number")
1570
+ return false;
1571
+ const pr = source;
1572
+ if (provenanceMatchesIssue(pr.body ?? "", n))
1573
+ return true;
1574
+ return pr.comments.nodes.some((c) => provenanceMatchesIssue(c.body, n));
1575
+ });
1576
+ result.set(n, found);
1577
+ }
1578
+ return result;
1579
+ }
1580
+ async function fetchProvenance(issueNums, owner, repo, token) {
1581
+ const result = new Map;
1582
+ if (issueNums.length === 0)
1583
+ return result;
1584
+ const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
1585
+ const perIssue = issueNums.map((n) => `
1586
+ i_${n}: issue(number: ${n}) {
1587
+ timelineItems(last: 1, itemTypes: [CLOSED_EVENT]) {
1588
+ nodes {
1589
+ ... on ClosedEvent {
1590
+ closer {
1591
+ ... on PullRequest {
1592
+ number
1593
+ body
1594
+ comments(first: 50) {
1595
+ nodes { body }
1596
+ }
1597
+ }
1598
+ }
1599
+ }
1600
+ }
1601
+ }
1602
+ }`).join("");
1603
+ const query = `query Provenance($owner: String!, $repo: String!) {
1604
+ repository(owner: $owner, name: $repo) {${perIssue}
1605
+ }
1606
+ }`;
1607
+ let response;
1608
+ try {
1609
+ response = await client(query, { owner, repo });
1610
+ } catch {
1611
+ return result;
1612
+ }
1613
+ if (!response.repository)
1614
+ return result;
1615
+ const needsFallback = [];
1616
+ for (const n of issueNums) {
1617
+ const raw = response.repository[`i_${n}`];
1618
+ if (!raw) {
1619
+ result.set(n, false);
1620
+ continue;
1621
+ }
1622
+ const closer = raw.timelineItems?.nodes?.[0]?.closer;
1623
+ const c = closer ?? null;
1624
+ if (!isPrCloser(c)) {
1625
+ needsFallback.push(n);
1626
+ continue;
1627
+ }
1628
+ const bodyHas = PROVENANCE_PATTERN.test(c.body ?? "");
1629
+ const commentHas = c.comments.nodes.some((x) => PROVENANCE_PATTERN.test(x.body));
1630
+ result.set(n, bodyHas || commentHas);
1631
+ }
1632
+ if (needsFallback.length > 0) {
1633
+ const fallback = await fetchProvenanceViaCrossReferences(needsFallback, owner, repo, token);
1634
+ for (const [n, found] of fallback)
1635
+ result.set(n, found);
1636
+ }
1637
+ return result;
1638
+ }
1414
1639
  // ../../packages/aeg-forge-state/src/github-token.ts
1415
1640
  import { execFile as execFile2 } from "node:child_process";
1416
1641
  import { promisify as promisify2 } from "node:util";
@@ -1640,6 +1865,84 @@ function describeError(err) {
1640
1865
  return err;
1641
1866
  return "unknown error";
1642
1867
  }
1868
+ // ../../packages/aeg-forge-state/src/prior-tranche-archival.ts
1869
+ function defaultPriorTrancheArchivalDeps() {
1870
+ let facts = new Map;
1871
+ return {
1872
+ activeTrancheSlugs: async (excludeSlug, repo) => {
1873
+ const index = await indexTrancheMilestonesAsync(repo.owner, repo.repo);
1874
+ facts = index.facts;
1875
+ return index.active.map((m) => m.slug).filter((slug) => slug !== excludeSlug);
1876
+ },
1877
+ deriveTranche: (slug, repo) => deriveTrancheFromForge(repo.owner, repo.repo, slug, facts.get(slug)),
1878
+ openIssues: async (slug, repo) => (await fetchTrancheIssuesAsync(repo.owner, repo.repo, slug)).filter((issue) => issue.state === "OPEN").map((issue) => ({ number: issue.number }))
1879
+ };
1880
+ }
1881
+ function reason(err) {
1882
+ return err instanceof Error ? err.message.split(`
1883
+ `)[0] ?? "failed" : String(err);
1884
+ }
1885
+ async function resolvePriorTrancheArchival(projects, excludeSlug, repo, deps = defaultPriorTrancheArchivalDeps()) {
1886
+ if (projects.length === 0)
1887
+ return { facts: [], infraFailure: null };
1888
+ let candidates;
1889
+ try {
1890
+ candidates = await deps.activeTrancheSlugs(excludeSlug, repo);
1891
+ } catch (err) {
1892
+ return {
1893
+ facts: [],
1894
+ infraFailure: `severity:infra — could not read the active tranches (${reason(err)}); whether a prior tranche is archived is unknown.`
1895
+ };
1896
+ }
1897
+ const facts = [];
1898
+ const unreadable = [];
1899
+ const derived = new Map;
1900
+ const derive = (slug) => {
1901
+ let p = derived.get(slug);
1902
+ if (!p) {
1903
+ p = deps.deriveTranche(slug, repo);
1904
+ derived.set(slug, p);
1905
+ }
1906
+ return p;
1907
+ };
1908
+ for (const project of projects) {
1909
+ let found = null;
1910
+ let unknown = false;
1911
+ for (const slug of candidates) {
1912
+ let candidateTranche;
1913
+ try {
1914
+ candidateTranche = await derive(slug);
1915
+ } catch {
1916
+ unknown = true;
1917
+ unreadable.push(`the tasks of tranche \`${slug}\` (project \`${project}\`)`);
1918
+ break;
1919
+ }
1920
+ if (!candidateTranche.tasks.some((t) => t.projects.includes(project)))
1921
+ continue;
1922
+ let openIssues;
1923
+ try {
1924
+ openIssues = await deps.openIssues(slug, repo);
1925
+ } catch {
1926
+ openIssues = null;
1927
+ }
1928
+ if (openIssues === null) {
1929
+ unknown = true;
1930
+ unreadable.push(`the open Issues of tranche \`${slug}\` (project \`${project}\`)`);
1931
+ break;
1932
+ }
1933
+ if (openIssues.length === 0) {
1934
+ found = { project, priorTrancheSlug: slug, archived: false };
1935
+ break;
1936
+ }
1937
+ }
1938
+ if (!unknown)
1939
+ facts.push(found ?? { project, priorTrancheSlug: null, archived: false });
1940
+ }
1941
+ return {
1942
+ facts,
1943
+ infraFailure: unreadable.length === 0 ? null : `severity:infra — could not read ${unreadable.join(", ")}; whether a prior tranche is archived is unknown.`
1944
+ };
1945
+ }
1643
1946
  // ../../packages/aeg-forge-state/src/fetch-open-issues.ts
1644
1947
  async function fetchOpenIssuesByLabel(slugs, owner, repo, token) {
1645
1948
  const result = new Map;
@@ -1714,6 +2017,10 @@ function buildQuery(issueNumbers) {
1714
2017
  }
1715
2018
  }`;
1716
2019
  }
2020
+ // ../../packages/aeg-forge-state/src/list-issue-milestones.ts
2021
+ function issueMilestonesFromIssues(issues) {
2022
+ return issues.filter((i) => i.state === "OPEN").map((i) => ({ issue: i.number, milestoneTitle: i.milestone?.title ?? null }));
2023
+ }
1717
2024
  // ../../packages/aeg-forge-state/src/resolve-repo.ts
1718
2025
  import { execFile as execFile3 } from "node:child_process";
1719
2026
  import { promisify as promisify3 } from "node:util";
@@ -1776,7 +2083,8 @@ var ANCHOR_FIELDS = [
1776
2083
  "PREMISE",
1777
2084
  "TEST-PLAN",
1778
2085
  "EVIDENCE",
1779
- "BEYOND-SURFACE"
2086
+ "BEYOND-SURFACE",
2087
+ "LIVE"
1780
2088
  ];
1781
2089
  function anchoredRegionBounds(body, field) {
1782
2090
  const masked = maskCode(body);
@@ -1977,7 +2285,6 @@ var DERIVABLE_STATUSES = DERIVED_STATUSES.filter((s) => s !== "backlog");
1977
2285
  // ../../packages/aeg-core/src/waiver-label.ts
1978
2286
  var WAIVER_LABEL = label("waiver-docs");
1979
2287
  var WAIVER_LABEL_REVIEW = label("waiver-review");
1980
- var PRINCIPAL_ALLOWLIST = ["daniboomerang"];
1981
2288
  function isPrincipal(login, principalAllowlist) {
1982
2289
  if (login === null)
1983
2290
  return false;
@@ -1996,6 +2303,14 @@ var RULING_ORDINAL_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Ruling ordinal:\s*(\d+)(
1996
2303
  var BRIEF_HASH_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Brief hash:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
1997
2304
  var POLICY_DIGEST_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Policy digest:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
1998
2305
  var BASE_SHA_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Judged base:\s*([0-9a-f]{7,40})(?![A-Za-z0-9])/im;
2306
+ var MANIFEST_VERSION_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Manifest version:\s*(\d+)\s*$/im;
2307
+ var PAUSE_BOUND_RULING_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Pause-bound ruling:\s*(?:(\S+)\|(\S+)\|([0-9a-f]{64})|\(none\))\s*$/im;
2308
+ function extractPauseBoundRuling(comment) {
2309
+ const m = comment.match(PAUSE_BOUND_RULING_PATTERN);
2310
+ if (!m)
2311
+ return;
2312
+ return m[1] ? { rulingId: m[1], pauseId: m[2], contentDigest: m[3] } : null;
2313
+ }
1999
2314
  function firstFiveLines(comment) {
2000
2315
  return comment.split(`
2001
2316
  `).slice(0, 5).join(`
@@ -2089,6 +2404,8 @@ function extractVerdict(comments, valuePattern, missingLabel) {
2089
2404
  danglingNote: `the most recent ${missingLabel} verdict comment carries a VERDICT-shaped line outside the first-five-line read window`
2090
2405
  };
2091
2406
  }
2407
+ const versionMatch = latest.match(MANIFEST_VERSION_PATTERN);
2408
+ const pauseBoundRuling = extractPauseBoundRuling(latest);
2092
2409
  return {
2093
2410
  value: m[1].toUpperCase().replace(/[_-]/g, " "),
2094
2411
  headSha: extractHeadSha(latest),
@@ -2097,6 +2414,8 @@ function extractVerdict(comments, valuePattern, missingLabel) {
2097
2414
  briefHash: extractBriefHash(latest),
2098
2415
  policyDigest: extractPolicyDigest(latest),
2099
2416
  baseSha: extractBaseSha(latest),
2417
+ ...versionMatch ? { manifestVersion: Number.parseInt(versionMatch[1], 10) } : {},
2418
+ ...pauseBoundRuling === undefined ? {} : { pauseBoundRuling },
2100
2419
  findingSeverities: extractFindingSeverities(latest),
2101
2420
  danglingNote: null
2102
2421
  };
@@ -2107,6 +2426,16 @@ function extractCodeReviewVerdict(comments) {
2107
2426
  function extractSecurityReviewVerdict(comments) {
2108
2427
  return extractVerdict(comments, /^[ \t]*(?:\*{1,3}|_{1,3})?VERDICT:\s*(PASS|FAIL)(?![A-Za-z0-9])/im, "security-review");
2109
2428
  }
2429
+
2430
+ // ../../packages/aeg-core/src/review-status.ts
2431
+ var DEVELOPER_ROUND_MARKER = /<!--\s*aeg:developer:round-(\d+)\s*-->/i;
2432
+ function parseDeveloperRoundMarker(body) {
2433
+ const m = body.match(DEVELOPER_ROUND_MARKER);
2434
+ if (!m)
2435
+ return null;
2436
+ const n = Number(m[1]);
2437
+ return Number.isFinite(n) ? n : null;
2438
+ }
2110
2439
  // ../../packages/aeg-core/src/report-tokens.ts
2111
2440
  var DASH_LOOKALIKES = {
2112
2441
  "-": "‑",
@@ -2802,14 +3131,14 @@ function checkTestPlan(prBody) {
2802
3131
  const region = located.found ? located.section : prBody;
2803
3132
  if (TEST_PLAN_UNIT_TESTS_ONLY_RE.test(region))
2804
3133
  return { status: "pass", errors: [] };
2805
- if (/\*\*\[(?:agent|principal)\]\*\*/.test(region))
3134
+ if (/\*\*\[(?:agent|principal|live)\]\*\*/.test(region))
2806
3135
  return { status: "pass", errors: [] };
2807
3136
  if (located.found && extractFencedBlocks(region).length > 0)
2808
3137
  return { status: "pass", errors: [] };
2809
3138
  return {
2810
3139
  status: "fail",
2811
3140
  errors: [
2812
- "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."
3141
+ "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."
2813
3142
  ]
2814
3143
  };
2815
3144
  }
@@ -3431,6 +3760,375 @@ function checkPrReportDensity(prBody) {
3431
3760
  const results = [checkDecisionsDensity(prBody), checkScopeDensity(prBody)];
3432
3761
  return { errors: results.flatMap((r) => r.errors) };
3433
3762
  }
3763
+ // ../../packages/aeg-core/src/prose-rules.ts
3764
+ var RETIRED_GLOBAL_EXEMPTIONS = [
3765
+ "docs/decisions-legacy.md",
3766
+ "apps/herald-ai/docs/",
3767
+ "apps/vada-ai/docs/",
3768
+ "aeg-root/tranches/completed/",
3769
+ "packages/aeg-core/src/docs/published-prose",
3770
+ "packages/aeg-core/src/retired-vocabulary.test.ts",
3771
+ "packages/aeg-core/src/retired-vocabulary.ts",
3772
+ "/fixtures/",
3773
+ "/node_modules/",
3774
+ "/.next/",
3775
+ "/.turbo/"
3776
+ ];
3777
+ var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
3778
+ var TRANCHE_MODEL_FILE = "/tranche-model.md";
3779
+ var RETIRED_PATTERN_EXEMPTIONS = {
3780
+ [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
3781
+ [String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`]: [
3782
+ "docs-index.md",
3783
+ "apps/vada-ai/specs/legacy/README.md",
3784
+ "apps/vada-ai/specs/vada-product-spec.md",
3785
+ "apps/vada-ai/web/CLAUDE.md",
3786
+ "apps/vada-ai/CLAUDE.md"
3787
+ ],
3788
+ "decisions-legacy": [
3789
+ "packages/aeg-core/src/file-classify.ts",
3790
+ "packages/aeg-core/src/file-classify.test.ts",
3791
+ "packages/aeg-core/src/pr-tier.test.ts",
3792
+ "docs-index.md",
3793
+ ".claude/skills/database/SKILL.md",
3794
+ ".claude/skills/vada-architecture/SKILL.md",
3795
+ "apps/vada-ai/specs/vada-byok-principles.md",
3796
+ "apps/vada-ai/web/CLAUDE.md",
3797
+ "apps/vada-ai/CLAUDE.md"
3798
+ ],
3799
+ CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
3800
+ ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
3801
+ };
3802
+ var retiredPatterns = [
3803
+ String.raw`\bD-[0-9]{3}\b`,
3804
+ "D-(###|NNN|nnn|xxx)",
3805
+ "decision (entry|logged)",
3806
+ "decision-log entry",
3807
+ "decision log entry",
3808
+ "decision log(s|ged|ging)?([^a-z]|$)",
3809
+ "decision-log",
3810
+ "decision entr",
3811
+ "decisions? (are |is )?logged",
3812
+ "log entries",
3813
+ String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`,
3814
+ "decisions-legacy",
3815
+ "CONTRADICTION",
3816
+ "assumes Tier 3",
3817
+ "Lock: ?YES",
3818
+ "Lock: ?NO",
3819
+ "lock approvals?",
3820
+ "approves locks",
3821
+ "Conforms to lock",
3822
+ "Challenges lock",
3823
+ "checkDecisionNumbersFresh",
3824
+ String.raw`roles/team-leader\.md`,
3825
+ String.raw`\(,`,
3826
+ String.raw`,\)`,
3827
+ String.raw`\(\.\)`,
3828
+ ...PLAN_ON_DISK_PATTERNS
3829
+ ];
3830
+ var published = [
3831
+ ["decision-id", "a decision id", /\bD-\d{3,}\b/],
3832
+ ["section-ref", "a section reference", /§/],
3833
+ ["forge-number", "a forge number", /#\d+/],
3834
+ ["retired-name", "the retired public name", /\bAEG\b/],
3835
+ ["tranche-slug", "a tranche slug", /\b[a-z][a-z0-9]*(?:-[a-z0-9]+)+-v\d+\b/],
3836
+ [
3837
+ "label-vocabulary",
3838
+ "forge label vocabulary",
3839
+ /(?:vinaya\/)?\b(?:tranche|iteration|tier|needs|waiver|project|aeg):(?![/\s]|$)/
3840
+ ],
3841
+ ["internal-path", "a repo-internal path", /\b(?:packages|apps|aeg-root|tools|scripts)\//],
3842
+ ["internal-path", "a repo-internal path", /\.(?:claude|husky|github)\//],
3843
+ [
3844
+ "internal-path",
3845
+ "a repo-internal file",
3846
+ /(?:^|[\s(`"'[])[\w.-]+(?:\/[\w.-]+)*\.(?:ts|tsx|js|jsx|mjs|cjs|sh|ya?ml|json|md)\b/
3847
+ ]
3848
+ ];
3849
+ var DEFAULT_PROSE_RULES = [
3850
+ {
3851
+ id: "forge-number",
3852
+ group: "reader-resolvable",
3853
+ scopes: ["ships", "reader-facing", "spec"],
3854
+ patterns: { prose: /#[0-9]{2,4}/g },
3855
+ flags: ["global"],
3856
+ message: "a forge number",
3857
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
3858
+ exemptions: []
3859
+ },
3860
+ {
3861
+ id: "tranche-slug",
3862
+ group: "reader-resolvable",
3863
+ scopes: ["ships", "reader-facing", "product", "spec"],
3864
+ patterns: { prose: /[a-z][a-z-]+-v[0-9]/g },
3865
+ flags: ["global"],
3866
+ message: "an internal tranche slug",
3867
+ severity: { ships: "warning", "reader-facing": "warning", product: "error", spec: "error" },
3868
+ exemptions: []
3869
+ },
3870
+ {
3871
+ id: "task-number",
3872
+ group: "reader-resolvable",
3873
+ scopes: ["spec"],
3874
+ patterns: { prose: /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi },
3875
+ flags: ["global", "ignore-case"],
3876
+ message: "a task number",
3877
+ severity: { spec: "error" },
3878
+ exemptions: []
3879
+ },
3880
+ {
3881
+ id: "source-comment-tranche-slug",
3882
+ group: "reader-resolvable",
3883
+ scopes: ["source-comment"],
3884
+ patterns: { comment: /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g },
3885
+ flags: ["global"],
3886
+ message: "a tranche-slug citation",
3887
+ severity: { "source-comment": "warning" },
3888
+ exemptions: []
3889
+ },
3890
+ {
3891
+ id: "source-comment-forge-number",
3892
+ group: "reader-resolvable",
3893
+ scopes: ["source-comment"],
3894
+ patterns: { comment: /#[0-9]{2,}/g },
3895
+ flags: ["global"],
3896
+ message: "a forge-number citation",
3897
+ severity: { "source-comment": "warning" },
3898
+ exemptions: []
3899
+ },
3900
+ {
3901
+ id: "legacy-batch-name",
3902
+ group: "reader-resolvable",
3903
+ scopes: ["ships", "reader-facing", "spec"],
3904
+ patterns: {},
3905
+ flags: ["built-in"],
3906
+ message: "an internal tranche slug",
3907
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
3908
+ exemptions: [],
3909
+ builtIn: true
3910
+ },
3911
+ {
3912
+ id: "coined-term",
3913
+ group: "reader-resolvable",
3914
+ scopes: ["ships", "reader-facing"],
3915
+ patterns: {},
3916
+ flags: ["built-in"],
3917
+ message: "uses coined term without defining it inline or linking the glossary",
3918
+ severity: { ships: "warning", "reader-facing": "warning" },
3919
+ exemptions: [],
3920
+ builtIn: true
3921
+ },
3922
+ ...retiredPatterns.map((pattern, index) => ({
3923
+ id: `retired-vocabulary-${index + 1}`,
3924
+ group: "retired-vocabulary",
3925
+ scopes: ["repository"],
3926
+ patterns: { repository: pattern },
3927
+ flags: [],
3928
+ message: "retired vocabulary",
3929
+ severity: { repository: "error" },
3930
+ exemptions: RETIRED_GLOBAL_EXEMPTIONS,
3931
+ patternExemptions: RETIRED_PATTERN_EXEMPTIONS
3932
+ })),
3933
+ ...published.map(([id, message, pattern]) => ({
3934
+ id,
3935
+ group: "published-prose",
3936
+ scopes: ["published"],
3937
+ patterns: { published: pattern },
3938
+ flags: [],
3939
+ message,
3940
+ severity: { published: "error" },
3941
+ exemptions: [".worktrees/task/<tranche>/<n>", "task/<tranche>/<n>", ".worktrees/"]
3942
+ }))
3943
+ ];
3944
+ var rulesForGroup = (group) => DEFAULT_PROSE_RULES.filter((rule) => rule.group === group);
3945
+ var RESOLVABLE_SCOPES = ["ships", "reader-facing", "product", "spec", "source-comment"];
3946
+ var RETIRED_SCOPES = ["repository"];
3947
+ var CONFIGURABLE_PROSE_SCOPES = [...RESOLVABLE_SCOPES, ...RETIRED_SCOPES];
3948
+ function groupOfScope(scope) {
3949
+ if (RESOLVABLE_SCOPES.includes(scope))
3950
+ return "reader-resolvable";
3951
+ if (RETIRED_SCOPES.includes(scope))
3952
+ return "retired-vocabulary";
3953
+ return;
3954
+ }
3955
+ var CONFIGURED_PROSE_FLAGS = ["i", "u"];
3956
+ var CONFIGURED_PATTERN_MAX_LENGTH = 200;
3957
+ var CONFIGURABLE_DEFAULT_RULES = DEFAULT_PROSE_RULES.filter((rule) => rule.group !== "published-prose");
3958
+ function allowedScopesFor(rule) {
3959
+ if (rule.builtIn)
3960
+ return rule.scopes;
3961
+ return rule.group === "retired-vocabulary" ? RETIRED_SCOPES : RESOLVABLE_SCOPES;
3962
+ }
3963
+ function normalizeRepoPath(entry) {
3964
+ let out = entry.replace(/\\/g, "/");
3965
+ while (out.startsWith("./"))
3966
+ out = out.slice(2);
3967
+ out = out.replace(/\/{2,}/g, "/");
3968
+ while (out.endsWith("/"))
3969
+ out = out.slice(0, -1);
3970
+ return out;
3971
+ }
3972
+ function isConfiguredExempt(path, exempt, repoRoot) {
3973
+ if (exempt.length === 0)
3974
+ return false;
3975
+ const root = repoRoot === undefined ? undefined : normalizeRepoPath(repoRoot);
3976
+ let rel = normalizeRepoPath(path);
3977
+ if (root && rel.startsWith(`${root}/`))
3978
+ rel = rel.slice(root.length + 1);
3979
+ return exempt.some((entry) => {
3980
+ const e = normalizeRepoPath(entry);
3981
+ return rel === e || rel.startsWith(`${e}/`);
3982
+ });
3983
+ }
3984
+ function ruleReads(set, rule, path) {
3985
+ return !isConfiguredExempt(path, set.exempt, set.repoRoot) && !isConfiguredExempt(path, rule.exempt, set.repoRoot);
3986
+ }
3987
+ var RESOLVABLE_RUN_ORDER = [
3988
+ "forge-number",
3989
+ "tranche-slug",
3990
+ "legacy-batch-name",
3991
+ "task-number",
3992
+ "source-comment-tranche-slug",
3993
+ "source-comment-forge-number",
3994
+ "coined-term"
3995
+ ];
3996
+ var REPORT_GROUPS = { "task-number": 2, "legacy-batch-name": 2 };
3997
+ function scopeDefaultSeverity(scope, sourceCommentSeverity) {
3998
+ if (scope === "source-comment")
3999
+ return sourceCommentSeverity ?? "warning";
4000
+ if (scope === "repository")
4001
+ return "error";
4002
+ return "warning";
4003
+ }
4004
+ function applySeverity(scopes, base, setting) {
4005
+ const out = {};
4006
+ for (const scope of scopes) {
4007
+ const configured = typeof setting === "string" ? setting : setting?.[scope];
4008
+ const value = configured ?? base[scope];
4009
+ if (value !== undefined)
4010
+ out[scope] = value;
4011
+ }
4012
+ return out;
4013
+ }
4014
+ function defaultPatternFor(rule) {
4015
+ const cache = new Map;
4016
+ return (scope) => {
4017
+ if (cache.has(scope))
4018
+ return cache.get(scope) ?? null;
4019
+ const own = rule.patterns[scope] ?? (scope === "source-comment" ? rule.patterns.comment : rule.patterns.prose) ?? Object.values(rule.patterns)[0];
4020
+ const compiled = own === undefined ? null : own instanceof RegExp ? own : new RegExp(own);
4021
+ cache.set(scope, compiled);
4022
+ return compiled;
4023
+ };
4024
+ }
4025
+ function customPatternFor(rule, global) {
4026
+ const cache = new Map;
4027
+ return (scope) => {
4028
+ if (cache.has(scope))
4029
+ return cache.get(scope) ?? null;
4030
+ const source = rule.patterns?.[scope] ?? rule.pattern;
4031
+ const compiled = source === undefined ? null : new RegExp(source, `${rule.flags ?? ""}${global ? "g" : ""}`);
4032
+ cache.set(scope, compiled);
4033
+ return compiled;
4034
+ };
4035
+ }
4036
+ function resolveProseRules(config = undefined, options = {}) {
4037
+ const rules = [];
4038
+ const defaults = config?.defaults ?? {};
4039
+ for (const rule of CONFIGURABLE_DEFAULT_RULES) {
4040
+ const override = defaults[rule.id];
4041
+ if (override === "off")
4042
+ continue;
4043
+ const group = rule.group;
4044
+ const scopes = override?.scopes ?? rule.scopes;
4045
+ const base = {};
4046
+ for (const scope of scopes) {
4047
+ base[scope] = scope === "source-comment" ? options.sourceCommentSeverity ?? rule.severity[scope] ?? "warning" : rule.severity[scope] ?? scopeDefaultSeverity(scope, options.sourceCommentSeverity);
4048
+ }
4049
+ rules.push({
4050
+ id: rule.id,
4051
+ group,
4052
+ custom: false,
4053
+ builtIn: rule.builtIn === true,
4054
+ scopes,
4055
+ message: rule.message,
4056
+ severity: applySeverity(scopes, base, override?.severity),
4057
+ exempt: override?.exempt ?? [],
4058
+ substringExempt: rule.exemptions,
4059
+ reportGroup: REPORT_GROUPS[rule.id],
4060
+ patternFor: defaultPatternFor(rule)
4061
+ });
4062
+ }
4063
+ for (const rule of config?.custom ?? []) {
4064
+ const group = groupOfScope(rule.scopes[0] ?? "") ?? "reader-resolvable";
4065
+ const base = {};
4066
+ for (const scope of rule.scopes)
4067
+ base[scope] = scopeDefaultSeverity(scope, options.sourceCommentSeverity);
4068
+ rules.push({
4069
+ id: rule.id,
4070
+ group,
4071
+ custom: true,
4072
+ builtIn: false,
4073
+ scopes: rule.scopes,
4074
+ message: rule.means,
4075
+ severity: applySeverity(rule.scopes, base, rule.severity),
4076
+ exempt: rule.exempt ?? [],
4077
+ substringExempt: [],
4078
+ patternFor: customPatternFor(rule, group === "reader-resolvable")
4079
+ });
4080
+ }
4081
+ if (options.decisionRecordsPath !== undefined)
4082
+ rules.push(decisionRecordCitationRule(options.decisionRecordsPath));
4083
+ const order = (rule) => {
4084
+ const at = RESOLVABLE_RUN_ORDER.indexOf(rule.id);
4085
+ return rule.custom || at === -1 ? RESOLVABLE_RUN_ORDER.length : at;
4086
+ };
4087
+ const resolvable = rules.filter((rule) => rule.group === "reader-resolvable");
4088
+ const sorted = resolvable.map((rule, index) => ({ rule, index })).sort((a, b) => order(a.rule) - order(b.rule) || a.index - b.index).map(({ rule }) => rule);
4089
+ return {
4090
+ rules: [...sorted, ...rules.filter((rule) => rule.group === "retired-vocabulary")],
4091
+ exempt: config?.exempt ?? [],
4092
+ repoRoot: options.repoRoot
4093
+ };
4094
+ }
4095
+ function rulesOfGroup(set, group) {
4096
+ return set.rules.filter((rule) => rule.group === group);
4097
+ }
4098
+ function rulesInScope(set, scope) {
4099
+ return set.rules.filter((rule) => rule.scopes.includes(scope));
4100
+ }
4101
+ var DEFAULT_PROSE_RULE_SET = resolveProseRules();
4102
+ var DECISION_RECORD_CITATION_ID = "decision-record-citation";
4103
+ var DECISION_RECORD_CITATION_SCOPES = ["ships", "product", "spec", "source-comment"];
4104
+ var DECISION_RECORD_CITATION_MESSAGE = "a decision-record number";
4105
+ function escapeRegExp(text) {
4106
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4107
+ }
4108
+ function decisionRecordCitationPattern(decisionRecordsPath) {
4109
+ const folder = escapeRegExp(normalizeRepoPath(decisionRecordsPath));
4110
+ return new RegExp(String.raw`\bADR[- ]?[0-9]+\b|(?<![A-Za-z0-9_-])${folder}/[0-9]+[A-Za-z0-9._-]*`, "g");
4111
+ }
4112
+ function decisionRecordCitationRule(decisionRecordsPath) {
4113
+ const folder = normalizeRepoPath(decisionRecordsPath);
4114
+ const pattern = decisionRecordCitationPattern(folder);
4115
+ const severity = {};
4116
+ for (const scope of DECISION_RECORD_CITATION_SCOPES)
4117
+ severity[scope] = "error";
4118
+ return {
4119
+ id: DECISION_RECORD_CITATION_ID,
4120
+ group: "reader-resolvable",
4121
+ custom: false,
4122
+ builtIn: false,
4123
+ scopes: DECISION_RECORD_CITATION_SCOPES,
4124
+ message: DECISION_RECORD_CITATION_MESSAGE,
4125
+ severity,
4126
+ exempt: [folder],
4127
+ substringExempt: [],
4128
+ patternFor: () => pattern
4129
+ };
4130
+ }
4131
+
3434
4132
  // ../../packages/aeg-core/src/reader-resolvable-prose.ts
3435
4133
  var PRODUCT_SLUG_SCOPE = [
3436
4134
  "apps/cli/src",
@@ -3442,8 +4140,8 @@ var PRODUCT_SLUG_SCOPE = [
3442
4140
  function isUnderOrEqual(path, prefix) {
3443
4141
  return path === prefix || path.startsWith(`${prefix}/`);
3444
4142
  }
3445
- function isProductScopeFile(path) {
3446
- return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
4143
+ function isProductScopeFile(path, productPaths) {
4144
+ return productPaths.some((prefix) => isUnderOrEqual(path, normalizeRepoPath(prefix)));
3447
4145
  }
3448
4146
  var SHIPS_PREFIX = "aeg-root/";
3449
4147
  function shipsArchivePrefix(shipsPrefix) {
@@ -3451,13 +4149,7 @@ function shipsArchivePrefix(shipsPrefix) {
3451
4149
  }
3452
4150
  var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
3453
4151
  function normalizeSpecPath(entry) {
3454
- let out = entry.replace(/\\/g, "/");
3455
- while (out.startsWith("./"))
3456
- out = out.slice(2);
3457
- out = out.replace(/\/{2,}/g, "/");
3458
- while (out.endsWith("/"))
3459
- out = out.slice(0, -1);
3460
- return out;
4152
+ return normalizeRepoPath(entry);
3461
4153
  }
3462
4154
  function isSpecFile2(path, specPaths) {
3463
4155
  if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
@@ -3469,7 +4161,7 @@ function isSpecFile2(path, specPaths) {
3469
4161
  function isClaudeMdFile(path) {
3470
4162
  return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
3471
4163
  }
3472
- function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
4164
+ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS, productPaths = PRODUCT_SLUG_SCOPE) {
3473
4165
  if (path.startsWith(shipsPrefix)) {
3474
4166
  return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
3475
4167
  }
@@ -3480,7 +4172,7 @@ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPr
3480
4172
  return "internal";
3481
4173
  if (isSpecFile2(path, specPaths))
3482
4174
  return "spec";
3483
- if (isProductScopeFile(path))
4175
+ if (isProductScopeFile(path, productPaths))
3484
4176
  return "product";
3485
4177
  return null;
3486
4178
  }
@@ -3505,9 +4197,16 @@ function lineAt(content, index) {
3505
4197
  }
3506
4198
  return line;
3507
4199
  }
3508
- var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
3509
- var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
3510
- var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
4200
+ var readerRules = rulesForGroup("reader-resolvable");
4201
+ var readerPattern = (id, scope = "prose") => {
4202
+ const pattern = readerRules.find((rule) => rule.id === id)?.patterns[scope];
4203
+ if (!(pattern instanceof RegExp))
4204
+ throw new Error(`default prose rule ${id} has no ${scope} pattern`);
4205
+ return pattern;
4206
+ };
4207
+ var FORGE_NUMBER_PATTERN = readerPattern("forge-number");
4208
+ var TRANCHE_SLUG_VN_PATTERN = readerPattern("tranche-slug");
4209
+ var TASK_NUMBER_PATTERN = readerPattern("task-number");
3511
4210
  function legacySlugPattern(legacySlugs) {
3512
4211
  if (legacySlugs.length === 0)
3513
4212
  return null;
@@ -3517,48 +4216,61 @@ function legacySlugPattern(legacySlugs) {
3517
4216
  function specGrandfatherPaths(specGrandfather) {
3518
4217
  return Array.isArray(specGrandfather) ? [...specGrandfather] : Object.keys(specGrandfather);
3519
4218
  }
3520
- function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4219
+ var REFERENCE_CLASSES = new Set(["ships", "reader-facing", "product", "spec"]);
4220
+ function referenceRulesFor(set, cls) {
4221
+ return rulesInScope(set, cls).filter((rule) => rule.group === "reader-resolvable" && rule.id !== "coined-term");
4222
+ }
4223
+ function citations(pattern, text, group) {
4224
+ const out = [];
4225
+ const re = pattern.global ? pattern : new RegExp(pattern.source, `${pattern.flags}g`);
4226
+ re.lastIndex = 0;
4227
+ let match = re.exec(text);
4228
+ while (match !== null) {
4229
+ if (match[0] === "") {
4230
+ re.lastIndex++;
4231
+ } else {
4232
+ const cited = group !== undefined ? match[group] ?? match[0] : match[0];
4233
+ out.push({ cited, index: match.index + match[0].indexOf(cited) });
4234
+ }
4235
+ match = re.exec(text);
4236
+ }
4237
+ re.lastIndex = 0;
4238
+ return out;
4239
+ }
4240
+ function customMessage(rule, cited) {
4241
+ return `${rule.id}: ${rule.message} ("${cited}")`;
4242
+ }
4243
+ function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS, options = {}) {
4244
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4245
+ const productPaths = options.productPaths ?? PRODUCT_SLUG_SCOPE;
3521
4246
  const findings = [];
3522
4247
  const legacyPattern = legacySlugPattern(legacySlugs);
3523
4248
  const grandfatheredWhole = new Set(Array.isArray(specGrandfather) ? specGrandfather : []);
3524
4249
  const limits = new Map(Array.isArray(specGrandfather) ? [] : Object.entries(specGrandfather));
3525
- const patterns = [
3526
- { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
3527
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
3528
- ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
3529
- ];
3530
- const productPatterns = [
3531
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
3532
- ];
3533
- const specPatterns = [
3534
- ...patterns,
3535
- { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
3536
- ];
3537
4250
  for (const file of files) {
3538
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
3539
- if (!cls || cls === "internal")
3540
- continue;
3541
- if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
4251
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths, productPaths);
4252
+ if (!cls || !REFERENCE_CLASSES.has(cls))
3542
4253
  continue;
3543
4254
  if (cls === "spec" && grandfatheredWhole.has(file.path))
3544
4255
  continue;
3545
- const blocking = cls === "product" || cls === "spec";
3546
4256
  const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
3547
- const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
3548
4257
  const fileFindings = [];
3549
- for (const { pattern, what, group } of patternsToRun) {
3550
- pattern.lastIndex = 0;
3551
- let match = pattern.exec(scrubbed);
3552
- while (match !== null) {
3553
- const cited = group !== undefined ? match[group] ?? match[0] : match[0];
3554
- const citedIndex = match.index + match[0].indexOf(cited);
4258
+ for (const rule of referenceRulesFor(set, cls)) {
4259
+ if (!ruleReads(set, rule, file.path))
4260
+ continue;
4261
+ const pattern = !rule.custom && rule.id === "legacy-batch-name" ? legacyPattern : rule.patternFor(cls);
4262
+ if (!pattern)
4263
+ continue;
4264
+ const blocking = rule.severity[cls] === "error";
4265
+ const what = cls === "product" ? `${rule.message} in product code` : rule.message;
4266
+ for (const { cited, index } of citations(pattern, scrubbed, rule.custom ? undefined : rule.reportGroup)) {
3555
4267
  fileFindings.push({
3556
4268
  file: file.path,
3557
- line: lineAt(scrubbed, citedIndex),
3558
- message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
3559
- blocking
4269
+ line: lineAt(scrubbed, index),
4270
+ message: rule.custom ? customMessage(rule, cited) : `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4271
+ blocking,
4272
+ rule: rule.id
3560
4273
  });
3561
- match = pattern.exec(scrubbed);
3562
4274
  }
3563
4275
  }
3564
4276
  const limit = cls === "spec" ? limits.get(file.path) : undefined;
@@ -3599,11 +4311,17 @@ function definesOrLinksGlossary(content, term) {
3599
4311
  return true;
3600
4312
  return /docs\/glossary|glossary\.md/i.test(content);
3601
4313
  }
3602
- function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
4314
+ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, options = {}) {
3603
4315
  const findings = [];
4316
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4317
+ const rule = set.rules.find((r) => !r.custom && r.id === "coined-term");
4318
+ if (!rule)
4319
+ return findings;
3604
4320
  for (const file of files) {
3605
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3606
- if (!cls || !SWEPT_CLASSES.has(cls))
4321
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, DEFAULT_SPEC_PATHS, options.productPaths);
4322
+ if (!cls || !SWEPT_CLASSES.has(cls) || !rule.scopes.includes(cls))
4323
+ continue;
4324
+ if (!ruleReads(set, rule, file.path))
3607
4325
  continue;
3608
4326
  const scrubbed = stripNonProse(file.path, file.content);
3609
4327
  for (const term of glossaryTerms) {
@@ -3616,14 +4334,15 @@ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, read
3616
4334
  file: file.path,
3617
4335
  line,
3618
4336
  message: `uses coined term "${term}" without defining it inline or linking the glossary`,
3619
- blocking: false
4337
+ blocking: rule.severity[cls] === "error",
4338
+ rule: rule.id
3620
4339
  });
3621
4340
  }
3622
4341
  }
3623
4342
  return findings;
3624
4343
  }
3625
- var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
3626
- var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
4344
+ var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = readerPattern("source-comment-tranche-slug", "comment");
4345
+ var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = readerPattern("source-comment-forge-number", "comment");
3627
4346
  function extractComments(path, content) {
3628
4347
  if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
3629
4348
  return content.replace(/[^\n]/g, "");
@@ -3720,39 +4439,40 @@ function extractComments(path, content) {
3720
4439
  }
3721
4440
  return out;
3722
4441
  }
3723
- function checkSourceComments(files, allowlist = []) {
4442
+ function checkSourceComments(files, allowlist = [], options = {}) {
3724
4443
  const findings = [];
3725
4444
  const allowed = new Set(allowlist);
3726
- const patterns = [
3727
- { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
3728
- { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
3729
- ];
4445
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4446
+ const rules = rulesInScope(set, "source-comment").filter((rule) => rule.group === "reader-resolvable");
3730
4447
  for (const file of files) {
3731
4448
  if (!file.path.endsWith(".ts"))
3732
4449
  continue;
3733
4450
  if (allowed.has(file.path))
3734
4451
  continue;
3735
4452
  const comments = extractComments(file.path, file.content);
3736
- for (const { pattern, what } of patterns) {
3737
- pattern.lastIndex = 0;
3738
- let match = pattern.exec(comments);
3739
- while (match !== null) {
4453
+ for (const rule of rules) {
4454
+ if (!ruleReads(set, rule, file.path))
4455
+ continue;
4456
+ const pattern = rule.patternFor("source-comment");
4457
+ if (!pattern)
4458
+ continue;
4459
+ for (const { cited, index } of citations(pattern, comments)) {
3740
4460
  findings.push({
3741
4461
  file: file.path,
3742
- line: lineAt(comments, match.index),
3743
- message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
3744
- blocking: false
4462
+ line: lineAt(comments, index),
4463
+ message: rule.custom ? customMessage(rule, cited) : `comment cites ${rule.message} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4464
+ blocking: rule.severity["source-comment"] === "error",
4465
+ rule: rule.id
3745
4466
  });
3746
- match = pattern.exec(comments);
3747
4467
  }
3748
4468
  }
3749
4469
  }
3750
4470
  return findings;
3751
4471
  }
3752
- function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4472
+ function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS, options = {}) {
3753
4473
  return [
3754
- ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
3755
- ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
4474
+ ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths, options),
4475
+ ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix, options)
3756
4476
  ];
3757
4477
  }
3758
4478
  function parseGlossaryTerms(glossaryContent) {
@@ -3955,6 +4675,17 @@ function checkDocClaims(files, fileReader) {
3955
4675
  };
3956
4676
  }
3957
4677
 
4678
+ // ../../packages/aeg-core/src/protected-paths.ts
4679
+ import { posix as posixPath } from "node:path";
4680
+ var PROTECTED_ADMIN_PATHS = ["vinaya.config.json", ".vinaya/doc-owners", ".github/", "aeg-root/"];
4681
+ function normalizeTouchedPath(path) {
4682
+ return posixPath.resolve("/", path.replace(/\\/g, "/")).replace(/^\/+/, "");
4683
+ }
4684
+ function isProtectedAdminPath(path) {
4685
+ const normalized = normalizeTouchedPath(path);
4686
+ return PROTECTED_ADMIN_PATHS.some((prefix) => normalized === prefix || normalized.startsWith(prefix));
4687
+ }
4688
+
3958
4689
  // ../../packages/aeg-core/src/issue-validation.ts
3959
4690
  function hasRationaleField(body, labelPattern) {
3960
4691
  const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
@@ -4074,13 +4805,20 @@ function globCoversPath(glob, path) {
4074
4805
  return !p.includes("/");
4075
4806
  return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
4076
4807
  }
4808
+ function surfaceEntryResolves(entry, resolvesToFile, pinnedFiles) {
4809
+ if (resolvesToFile(entry))
4810
+ return true;
4811
+ const directory = entry.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
4812
+ return pinnedFiles.some((path) => path.startsWith(`${directory}/`));
4813
+ }
4077
4814
  function checkSurfaceGlobsResolve(body, resolvesToFile) {
4078
4815
  const surface = parseIssueSurface(body);
4079
4816
  if (!surface.ok)
4080
4817
  return { status: "pass", errors: [] };
4818
+ const pinnedFiles = boundaryPinnedFiles(body);
4081
4819
  const errors = [];
4082
4820
  for (const glob of surface.value.in) {
4083
- if (!resolvesToFile(glob)) {
4821
+ if (!surfaceEntryResolves(glob, resolvesToFile, pinnedFiles)) {
4084
4822
  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.`);
4085
4823
  }
4086
4824
  }
@@ -4110,6 +4848,14 @@ function recordedBeyondSurfacePaths(body) {
4110
4848
  return paths;
4111
4849
  }
4112
4850
  function checkSurfaceScope(changedFiles, surface, recorded) {
4851
+ for (const path of changedFiles) {
4852
+ if (!isProtectedAdminPath(path))
4853
+ continue;
4854
+ const normalized = normalizeTouchedPath(path);
4855
+ if (!surface.in.some((glob) => globCoversPath(glob, normalized))) {
4856
+ return { ok: false, violation: { path, reason: "protected" } };
4857
+ }
4858
+ }
4113
4859
  const listed = new Set(recorded);
4114
4860
  const violation = beyondSurfacePaths(changedFiles, surface).find((entry) => !listed.has(entry.path));
4115
4861
  return violation ? { ok: false, violation } : { ok: true };
@@ -4165,12 +4911,22 @@ function checkPartsCiteDefinedObjectives(body) {
4165
4911
  }
4166
4912
  return { status: errors.length > 0 ? "fail" : "pass", errors };
4167
4913
  }
4914
+ var ISSUE_LIVE_LINE_RE = /^-\s*\*{2}\[live\]\*{2}(.*)$/gim;
4915
+ function liveCommand(text) {
4916
+ const trimmed = text.trim();
4917
+ const span = /^(`+)(.+)\1$/.exec(trimmed);
4918
+ return span ? span[2].trim() : trimmed;
4919
+ }
4920
+ function liveItemsIn(region) {
4921
+ return [...region.matchAll(ISSUE_LIVE_LINE_RE)].map((m) => liveCommand(m[1] ?? "")).filter(Boolean);
4922
+ }
4923
+ function parseLiveTestPlanItems(body) {
4924
+ const located = locateTestPlanSection(body);
4925
+ return located.found ? liveItemsIn(located.section) : [];
4926
+ }
4168
4927
  function isTaskIssueLabelSet(labels) {
4169
4928
  return hasLabel("tranche", labels);
4170
4929
  }
4171
- function checkTrancheLabelPresence(_body, _labels) {
4172
- return { status: "pass", errors: [] };
4173
- }
4174
4930
  function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
4175
4931
  if (!isTaskIssueLabelSet(labels))
4176
4932
  return { status: "pass", errors: [] };
@@ -4186,6 +4942,7 @@ function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTi
4186
4942
  };
4187
4943
  }
4188
4944
  var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
4945
+ var PATH_TEXT = (body) => stripCode(body, { inlineSpans: "keep" });
4189
4946
  function isControlCodePoint(codePoint) {
4190
4947
  return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
4191
4948
  }
@@ -4246,8 +5003,14 @@ function checkProjectsRegistered(body, _labels, registeredNames) {
4246
5003
  }
4247
5004
  return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
4248
5005
  }
5006
+ function rationaleFieldText(text, labelPattern) {
5007
+ const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})[^\\n]*\\n?([\\s\\S]*?)(?=\\n\\s*(?:\\*\\*[A-Z]|#{1,4}\\s)|(?![\\s\\S]))`, "im");
5008
+ const m = re.exec(text);
5009
+ return m ? m[0] : "";
5010
+ }
4249
5011
  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;
4250
5012
  var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
5013
+ var RATIONALE_PATH_RE_GLOBAL = /`([\w.@-]+(?:\/[\w.@-]+)+)`/g;
4251
5014
  function normalizeEdgeId(s) {
4252
5015
  const qualified = splitSlugQualifiedEdge(s);
4253
5016
  return (qualified ? qualified.bareId : s).replace(/^#/, "").trim();
@@ -4255,6 +5018,15 @@ function normalizeEdgeId(s) {
4255
5018
  function edgesNameEachOther(a, b) {
4256
5019
  return a.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(b.ref)) || b.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(a.ref));
4257
5020
  }
5021
+ var BOUNDARY_OUT_RE = /\bOut\s*:\s*([\s\S]*)$/im;
5022
+ function boundaryOutText(body) {
5023
+ const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
5024
+ const m = BOUNDARY_OUT_RE.exec(boundary);
5025
+ return m ? m[1] : "";
5026
+ }
5027
+ function namedPathsIn(text) {
5028
+ return [...new Set([...text.matchAll(RATIONALE_PATH_RE_GLOBAL)].map((m) => m[1]))].filter((p) => !/^https?:\/\//i.test(p));
5029
+ }
4258
5030
  var FILE_EXTENSIONS = new Set([
4259
5031
  "ts",
4260
5032
  "tsx",
@@ -4276,6 +5048,11 @@ var FILE_EXTENSIONS = new Set([
4276
5048
  "html",
4277
5049
  "css"
4278
5050
  ]);
5051
+ function boundaryPinnedFiles(body) {
5052
+ const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
5053
+ const excluded = new Set(namedPathsIn(boundaryOutText(body)));
5054
+ return namedPathsIn(boundary).filter((p) => looksLikeFilePath(p) && !excluded.has(p));
5055
+ }
4279
5056
  var CI_SHARD_DIR = "apps/cli/tests/ci-shards";
4280
5057
  var CI_SHARD_PROBE = `${CI_SHARD_DIR}/shard-1.txt`;
4281
5058
 
@@ -4300,7 +5077,7 @@ function isGrandfathered(isoDate) {
4300
5077
  return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
4301
5078
  }
4302
5079
  var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
4303
- function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
5080
+ function checkA1(entries, principalAllowlist) {
4304
5081
  const failures = [];
4305
5082
  for (const e of entries) {
4306
5083
  if (!e.facts)
@@ -4330,6 +5107,37 @@ function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
4330
5107
  note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4331
5108
  };
4332
5109
  }
5110
+ function checkA2(entries, hasProvenanceByKey) {
5111
+ const failures = [];
5112
+ for (const e of entries) {
5113
+ if (!e.facts)
5114
+ continue;
5115
+ if (e.facts.issueState !== "closed" || e.facts.prState !== "merged")
5116
+ continue;
5117
+ const key = `${e.trancheSlug}/${e.task.id}`;
5118
+ const hasProvenance = hasProvenanceByKey.get(key);
5119
+ if (hasProvenance === undefined)
5120
+ continue;
5121
+ if (!hasProvenance) {
5122
+ failures.push({
5123
+ code: "archived-without-provenance",
5124
+ issue: e.task.issue,
5125
+ tranche: e.trancheSlug,
5126
+ task: e.task.id,
5127
+ reason: "Closing PR has no `### AEG provenance` comment (Archivist close-out missing)",
5128
+ grandfathered: isGrandfathered(e.facts.mergedAt)
5129
+ });
5130
+ }
5131
+ }
5132
+ const activeFails = failures.filter((f) => !f.grandfathered);
5133
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
5134
+ return {
5135
+ check: "A2",
5136
+ status,
5137
+ failures,
5138
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
5139
+ };
5140
+ }
4333
5141
  function checkA3(entries) {
4334
5142
  const failures = [];
4335
5143
  for (const e of entries) {
@@ -4545,6 +5353,33 @@ function checkL1(files, entriesBySlug) {
4545
5353
  note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
4546
5354
  };
4547
5355
  }
5356
+ function checkL2(files, entriesBySlug) {
5357
+ const failures = [];
5358
+ for (const f of files) {
5359
+ if (!f.archived)
5360
+ continue;
5361
+ const entries = entriesBySlug.get(f.slug) ?? [];
5362
+ for (const e of entries) {
5363
+ if (!e.facts)
5364
+ continue;
5365
+ if (e.facts.issueState === "open") {
5366
+ failures.push({
5367
+ code: "premature-archive",
5368
+ issue: e.task.issue,
5369
+ tranche: f.slug,
5370
+ task: e.task.id,
5371
+ reason: `Archived tranche has open task-Issue #${e.task.issue ?? "?"} (premature archive)`
5372
+ });
5373
+ }
5374
+ }
5375
+ }
5376
+ return {
5377
+ check: "L2",
5378
+ status: "info",
5379
+ failures,
5380
+ note: failures.length > 0 ? `${failures.length} archived tranche(s) with an open task-Issue — investigate (advisory)` : undefined
5381
+ };
5382
+ }
4548
5383
  function checkL3(files) {
4549
5384
  const active = files.filter((f) => !f.archived);
4550
5385
  return {
@@ -4554,6 +5389,51 @@ function checkL3(files) {
4554
5389
  note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
4555
5390
  };
4556
5391
  }
5392
+ function checkL4(activeTrancheSlugs, issueMilestones) {
5393
+ const activeSet = new Set(activeTrancheSlugs);
5394
+ const failures = [];
5395
+ for (const f of issueMilestones) {
5396
+ if (!activeSet.has(f.tranche))
5397
+ continue;
5398
+ if (f.milestoneTitle === f.tranche)
5399
+ continue;
5400
+ failures.push({
5401
+ code: "milestone-drift",
5402
+ issue: f.issue,
5403
+ tranche: f.tranche,
5404
+ 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`
5405
+ });
5406
+ }
5407
+ return {
5408
+ check: "L4",
5409
+ status: "info",
5410
+ failures,
5411
+ 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
5412
+ };
5413
+ }
5414
+ function checkL5(activeTrancheSlugs, entriesBySlug) {
5415
+ const failures = [];
5416
+ for (const slug of activeTrancheSlugs) {
5417
+ const entries = entriesBySlug.get(slug) ?? [];
5418
+ const withFacts = entries.filter((e) => e.facts !== undefined);
5419
+ if (withFacts.length === 0)
5420
+ continue;
5421
+ const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
5422
+ if (allClosed) {
5423
+ failures.push({
5424
+ code: "tranche-not-archived",
5425
+ tranche: slug,
5426
+ reason: "Every task Issue is closed but the tranche is not recorded as complete — archive it"
5427
+ });
5428
+ }
5429
+ }
5430
+ return {
5431
+ check: "L5",
5432
+ status: failures.length > 0 ? "fail" : "pass",
5433
+ failures,
5434
+ note: failures.length > 0 ? `${failures.length} tranche(s) whose task Issues are all closed but were never archived` : undefined
5435
+ };
5436
+ }
4557
5437
  function extractClosesReferences(prBody) {
4558
5438
  const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
4559
5439
  const stripped = stripCode(prBody);
@@ -4649,6 +5529,58 @@ function extractIssue(body) {
4649
5529
  }
4650
5530
  // ../../packages/aeg-core/src/review-input-manifest.ts
4651
5531
  import { createHash as createHash4 } from "node:crypto";
5532
+
5533
+ // ../../packages/aeg-core/src/ruling-ordinal.ts
5534
+ var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
5535
+ function newestPrincipalRulingOrdinal(comments, allowlist) {
5536
+ let best = 0;
5537
+ for (const c of comments) {
5538
+ if (!isPrincipal(c.author, allowlist))
5539
+ continue;
5540
+ const firstLine = (c.body.split(`
5541
+ `)[0] ?? "").trim();
5542
+ const m = RULING_MARKER_ORDINAL.exec(firstLine);
5543
+ if (!m)
5544
+ continue;
5545
+ const k = Number.parseInt(m[1], 10);
5546
+ if (k > best)
5547
+ best = k;
5548
+ }
5549
+ return best;
5550
+ }
5551
+ function parseRulingIdentity(rulingId) {
5552
+ const m = /^(issue-)?(\d+)-(\d+)$/.exec(rulingId);
5553
+ if (!m)
5554
+ return null;
5555
+ const ref = Number.parseInt(m[2], 10);
5556
+ const ordinal = Number.parseInt(m[3], 10);
5557
+ if (ref <= 0 || ordinal <= 0)
5558
+ return null;
5559
+ return { target: m[1] ? "issue" : "pr", ref, ordinal };
5560
+ }
5561
+ function principalRulingTextById(comments, allowlist, rulingId) {
5562
+ const identity = parseRulingIdentity(rulingId);
5563
+ if (identity === null)
5564
+ return null;
5565
+ const matches = comments.filter((c) => {
5566
+ if (!isPrincipal(c.author, allowlist))
5567
+ return false;
5568
+ const m = RULING_MARKER_ORDINAL.exec((c.body.split(`
5569
+ `)[0] ?? "").trim());
5570
+ return m !== null && Number.parseInt(m[1], 10) === identity.ordinal;
5571
+ });
5572
+ if (matches.length !== 1)
5573
+ return null;
5574
+ const body = matches[0].body;
5575
+ const idx = body.indexOf(`
5576
+ `);
5577
+ return idx === -1 ? "" : body.slice(idx + 1).trim();
5578
+ }
5579
+
5580
+ // ../../packages/aeg-core/src/review-input-manifest.ts
5581
+ function pauseBoundRulingDigest(rulingText) {
5582
+ return createHash4("sha256").update(rulingText).digest("hex");
5583
+ }
4652
5584
  function briefHash(brief) {
4653
5585
  return createHash4("sha256").update(`${brief}
4654
5586
  `).digest("hex");
@@ -4709,14 +5641,19 @@ function compareManifest(echoed, current, patchIdOf) {
4709
5641
  const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4710
5642
  const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4711
5643
  const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
5644
+ const legacyCurrent = current.manifestVersion === undefined;
5645
+ const manifestVersion = legacyCurrent ? echoed.manifestVersion === undefined || echoed.manifestVersion === null : echoed.manifestVersion === current.manifestVersion;
5646
+ const pauseBoundRuling = legacyCurrent ? true : Object.hasOwn(echoed, "pauseBoundRuling") && JSON.stringify(echoed.pauseBoundRuling) === JSON.stringify(current.pauseBoundRuling);
4712
5647
  const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4713
5648
  return {
4714
- bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
5649
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && pauseBoundRuling && manifestVersion && policyDigestBound,
4715
5650
  head,
4716
5651
  base,
4717
5652
  briefHash: briefHashBound,
4718
5653
  objectivesVersion,
4719
5654
  rulingOrdinal,
5655
+ pauseBoundRuling,
5656
+ manifestVersion,
4720
5657
  policyDigest: policyDigestBound
4721
5658
  };
4722
5659
  }
@@ -4732,7 +5669,7 @@ function renderGateDeferred(deferred) {
4732
5669
  return ` ${deferred.length} finding(s) deferred, not blocking this round: ${items}.`;
4733
5670
  }
4734
5671
  function checkReviewGate(input) {
4735
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
5672
+ const { principalAllowlist } = input;
4736
5673
  const waived = isWaiverLabelActorVerified({
4737
5674
  label: WAIVER_LABEL_REVIEW,
4738
5675
  labels: input.labels,
@@ -4771,27 +5708,33 @@ function checkReviewGate(input) {
4771
5708
  const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4772
5709
  const securityClean = securityTextClean && securityPolicyClean;
4773
5710
  const currentManifest = {
5711
+ ...input.manifestVersion === undefined ? {} : { manifestVersion: input.manifestVersion },
4774
5712
  headSha: input.headSha,
4775
5713
  baseSha: input.baseSha ?? null,
4776
5714
  briefHash: input.briefHash ?? null,
4777
5715
  objectivesVersion: input.objectivesVersion,
4778
5716
  rulingOrdinal: input.rulingOrdinal,
5717
+ pauseBoundRuling: input.pauseBoundRuling ?? null,
4779
5718
  policyDigest: policyDigest(policy)
4780
5719
  };
4781
5720
  const codeReviewEchoed = {
5721
+ manifestVersion: codeReview.manifestVersion,
4782
5722
  headSha: codeReview.headSha,
4783
5723
  baseSha: codeReview.baseSha,
4784
5724
  briefHash: codeReview.briefHash,
4785
5725
  objectivesVersion: codeReview.objectivesVersion,
4786
5726
  rulingOrdinal: codeReview.rulingOrdinal,
5727
+ pauseBoundRuling: codeReview.pauseBoundRuling,
4787
5728
  policyDigest: codeReview.policyDigest
4788
5729
  };
4789
5730
  const securityEchoed = {
5731
+ manifestVersion: security.manifestVersion,
4790
5732
  headSha: security.headSha,
4791
5733
  baseSha: security.baseSha,
4792
5734
  briefHash: security.briefHash,
4793
5735
  objectivesVersion: security.objectivesVersion,
4794
5736
  rulingOrdinal: security.rulingOrdinal,
5737
+ pauseBoundRuling: security.pauseBoundRuling,
4795
5738
  policyDigest: security.policyDigest
4796
5739
  };
4797
5740
  const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
@@ -4830,6 +5773,10 @@ function checkReviewGate(input) {
4830
5773
  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"}`);
4831
5774
  } else if (!codeReviewBinding.policyDigest) {
4832
5775
  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}`);
5776
+ } else if (!codeReviewBinding.manifestVersion) {
5777
+ problems.push(`the newest code-review verdict echoes manifest version ${codeReview.manifestVersion ?? "none"}, the frozen review-input manifest is version ${currentManifest.manifestVersion ?? "unversioned"}`);
5778
+ } else if (!codeReviewBinding.pauseBoundRuling) {
5779
+ problems.push(`the newest code-review verdict echoes pauseBoundRuling ${renderBinding(codeReview.pauseBoundRuling)}, the frozen review-input manifest binds ${renderBinding(currentManifest.pauseBoundRuling)}`);
4833
5780
  }
4834
5781
  if (!securityTextClean) {
4835
5782
  problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
@@ -4847,6 +5794,10 @@ function checkReviewGate(input) {
4847
5794
  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"}`);
4848
5795
  } else if (!securityBinding.policyDigest) {
4849
5796
  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}`);
5797
+ } else if (!securityBinding.manifestVersion) {
5798
+ problems.push(`the newest security-review verdict echoes manifest version ${security.manifestVersion ?? "none"}, the frozen review-input manifest is version ${currentManifest.manifestVersion ?? "unversioned"}`);
5799
+ } else if (!securityBinding.pauseBoundRuling) {
5800
+ problems.push(`the newest security-review verdict echoes pauseBoundRuling ${renderBinding(security.pauseBoundRuling)}, the frozen review-input manifest binds ${renderBinding(currentManifest.pauseBoundRuling)}`);
4850
5801
  }
4851
5802
  const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4852
5803
  return {
@@ -4855,29 +5806,16 @@ function checkReviewGate(input) {
4855
5806
  waived: false
4856
5807
  };
4857
5808
  }
5809
+ function renderBinding(binding) {
5810
+ if (binding === undefined)
5811
+ return "(absent)";
5812
+ return binding === null ? "(none)" : `${binding.rulingId}|${binding.pauseId}|${binding.contentDigest}`;
5813
+ }
4858
5814
  var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4859
5815
  var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4860
5816
  function isChangesetsReleasePr(branch, author, expectedAuthor) {
4861
5817
  return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4862
5818
  }
4863
- // ../../packages/aeg-core/src/ruling-ordinal.ts
4864
- var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4865
- function newestPrincipalRulingOrdinal(comments, allowlist) {
4866
- let best = 0;
4867
- for (const c of comments) {
4868
- if (!isPrincipal(c.author, allowlist))
4869
- continue;
4870
- const firstLine = (c.body.split(`
4871
- `)[0] ?? "").trim();
4872
- const m = RULING_MARKER_ORDINAL.exec(firstLine);
4873
- if (!m)
4874
- continue;
4875
- const k = Number.parseInt(m[1], 10);
4876
- if (k > best)
4877
- best = k;
4878
- }
4879
- return best;
4880
- }
4881
5819
  // ../../packages/aeg-core/src/markdown-table.ts
4882
5820
  function splitRow(line) {
4883
5821
  const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
@@ -5029,7 +5967,6 @@ var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
5029
5967
  var NON_GATE_BIN_NAMES = NON_GATE_BINS;
5030
5968
  var TWIN_CANDIDATE_EXCEPTIONS = {
5031
5969
  "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)',
5032
- "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)`,
5033
5970
  "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
5034
5971
  };
5035
5972
  var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
@@ -5253,72 +6190,10 @@ function compareToBaseline(current, baseline) {
5253
6190
  };
5254
6191
  }
5255
6192
  // ../../packages/aeg-core/src/retired-vocabulary.ts
5256
- var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
5257
- var RETIRED_PATTERNS = [
5258
- String.raw`\bD-[0-9]{3}\b`,
5259
- "D-(###|NNN|nnn|xxx)",
5260
- "decision (entry|logged)",
5261
- "decision-log entry",
5262
- "decision log entry",
5263
- "decision log(s|ged|ging)?([^a-z]|$)",
5264
- "decision-log",
5265
- "decision entr",
5266
- "decisions? (are |is )?logged",
5267
- "log entries",
5268
- String.raw`decisions\.md`,
5269
- "decisions-legacy",
5270
- "CONTRADICTION",
5271
- "assumes Tier 3",
5272
- "Lock: ?YES",
5273
- "Lock: ?NO",
5274
- "lock approvals?",
5275
- "approves locks",
5276
- "Conforms to lock",
5277
- "Challenges lock",
5278
- "checkDecisionNumbersFresh",
5279
- String.raw`roles/team-leader\.md`,
5280
- String.raw`\(,`,
5281
- String.raw`,\)`,
5282
- String.raw`\(\.\)`,
5283
- ...PLAN_ON_DISK_PATTERNS
5284
- ];
5285
- var TRANCHE_MODEL_FILE = "/tranche-model.md";
5286
- var RETIRED_EXEMPT_SUBSTRINGS = [
5287
- "docs/decisions-legacy.md",
5288
- "apps/herald-ai/docs/",
5289
- "apps/vada-ai/docs/",
5290
- "aeg-root/tranches/completed/",
5291
- "packages/aeg-core/src/docs/published-prose",
5292
- "packages/aeg-core/src/retired-vocabulary.test.ts",
5293
- "packages/aeg-core/src/retired-vocabulary.ts",
5294
- "/fixtures/",
5295
- "/node_modules/",
5296
- "/.next/",
5297
- "/.turbo/"
5298
- ];
5299
- var PATTERN_EXEMPT = {
5300
- [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
5301
- [String.raw`decisions\.md`]: [
5302
- "docs-index.md",
5303
- "apps/vada-ai/specs/legacy/README.md",
5304
- "apps/vada-ai/specs/vada-product-spec.md",
5305
- "apps/vada-ai/web/CLAUDE.md",
5306
- "apps/vada-ai/CLAUDE.md"
5307
- ],
5308
- "decisions-legacy": [
5309
- "packages/aeg-core/src/file-classify.ts",
5310
- "packages/aeg-core/src/file-classify.test.ts",
5311
- "packages/aeg-core/src/pr-tier.test.ts",
5312
- "docs-index.md",
5313
- ".claude/skills/database/SKILL.md",
5314
- ".claude/skills/vada-architecture/SKILL.md",
5315
- "apps/vada-ai/specs/vada-byok-principles.md",
5316
- "apps/vada-ai/web/CLAUDE.md",
5317
- "apps/vada-ai/CLAUDE.md"
5318
- ],
5319
- CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
5320
- ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
5321
- };
6193
+ var retiredRules = rulesForGroup("retired-vocabulary");
6194
+ var RETIRED_PATTERNS = retiredRules.map((rule) => rule.patterns.repository);
6195
+ var PATTERN_EXEMPT = RETIRED_PATTERN_EXEMPTIONS;
6196
+ var DEFAULT_PATTERN_OF = new Map(retiredRules.map((rule) => [rule.id, rule.patterns.repository]));
5322
6197
  function lineNumbers(content, pattern) {
5323
6198
  const out = [];
5324
6199
  const lines = content.split(`
@@ -5329,22 +6204,29 @@ function lineNumbers(content, pattern) {
5329
6204
  }
5330
6205
  return out;
5331
6206
  }
5332
- function scanRetiredVocabulary(files) {
6207
+ function scanRetiredVocabulary(files, rules = DEFAULT_PROSE_RULE_SET) {
5333
6208
  const findings = [];
6209
+ const retired = rulesOfGroup(rules, "retired-vocabulary");
5334
6210
  for (const file of files) {
5335
- if (RETIRED_EXEMPT_SUBSTRINGS.some((e) => file.path.includes(e)))
5336
- continue;
5337
- for (const pattern of RETIRED_PATTERNS) {
5338
- const patternExempt = PATTERN_EXEMPT[pattern] ?? [];
5339
- if (patternExempt.some((e) => file.path.includes(e)))
6211
+ for (const rule of retired) {
6212
+ if (rule.substringExempt.some((e) => file.path.includes(e)))
6213
+ continue;
6214
+ if (!ruleReads(rules, rule, file.path))
6215
+ continue;
6216
+ const re = rule.patternFor("repository");
6217
+ if (!re)
6218
+ continue;
6219
+ const pattern = rule.custom ? re.source : DEFAULT_PATTERN_OF.get(rule.id) ?? re.source;
6220
+ if (!rule.custom && (PATTERN_EXEMPT[pattern] ?? []).some((e) => file.path.includes(e)))
5340
6221
  continue;
5341
- const re = new RegExp(pattern);
5342
6222
  for (const line of lineNumbers(file.content, re)) {
5343
6223
  findings.push({
5344
6224
  file: file.path,
5345
6225
  line,
5346
6226
  pattern,
5347
- message: `claims a retired AEG mechanism is still live (matches /${pattern}/)`
6227
+ message: rule.custom ? `${rule.id}: ${rule.message} (matches /${pattern}/)` : `claims a retired AEG mechanism is still live (matches /${pattern}/)`,
6228
+ rule: rule.id,
6229
+ blocking: rule.severity.repository === "error"
5348
6230
  });
5349
6231
  }
5350
6232
  }
@@ -5368,7 +6250,7 @@ function isSelfDependency(dep, task, issue) {
5368
6250
  function checkDispatchReadiness(input) {
5369
6251
  const { trancheSlug, task } = input;
5370
6252
  const taskLabel = `task ${task.id} (tranche ${trancheSlug})`;
5371
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
6253
+ const { principalAllowlist } = input;
5372
6254
  const blockerDetails = [];
5373
6255
  const push = (blockerClass, message) => {
5374
6256
  blockerDetails.push({ class: blockerClass, message });
@@ -5460,6 +6342,16 @@ function pushesAnyBranchRef(pushRefs) {
5460
6342
  return pushRefs.split(`
5461
6343
  `).map((line) => line.trim()).filter((line) => line.length > 0).some((line) => line.split(/\s+/)[2]?.startsWith("refs/heads/") === true);
5462
6344
  }
6345
+ function resolveDefaultBranch(facts) {
6346
+ const { originHead, hasOriginMain, hasOriginMaster } = facts;
6347
+ if (originHead !== null && originHead !== "")
6348
+ return originHead;
6349
+ if (hasOriginMain)
6350
+ return "main";
6351
+ if (hasOriginMaster)
6352
+ return "master";
6353
+ return null;
6354
+ }
5463
6355
  function checkMainBranchRefusal(facts) {
5464
6356
  const { currentSymbolicBranch, defaultBranch, pushRefs = null } = facts;
5465
6357
  if (currentSymbolicBranch === null)
@@ -5720,54 +6612,61 @@ function checkFirstPushDispatchGate(input) {
5720
6612
  reason: `verify-dispatch reports READY TO DISPATCH for \`${branch}\`.`
5721
6613
  };
5722
6614
  }
5723
- // ../../packages/aeg-core/src/issue-assignment.ts
5724
- function decideIssueAssignment(input) {
5725
- const { branch, remoteRefExists, issue, assignees, login } = input;
5726
- if (parseTaskBranch(branch) === null) {
5727
- return {
5728
- action: "skip",
5729
- reason: `Branch \`${branch}\` is not a task/<tranche>/<n> branch — Issue self-assignment only applies to task branches.`
5730
- };
5731
- }
5732
- if (remoteRefExists) {
5733
- return {
5734
- action: "skip",
5735
- reason: `Branch \`${branch}\` already exists on the remote — not its first push, nothing to assign.`
5736
- };
5737
- }
5738
- if (issue === null) {
5739
- return {
5740
- action: "skip",
5741
- reason: `No Issue resolved for \`${branch}\` from its topology row — skipping self-assignment (the gate owns refusing an unplanned branch).`
5742
- };
5743
- }
5744
- if (assignees === null) {
5745
- return {
5746
- action: "skip",
5747
- reason: `Could not read Issue #${issue}'s current assignees — skipping rather than risking a double-assign (fail-open, never a guess).`
5748
- };
5749
- }
5750
- if (assignees.length > 0) {
5751
- return {
5752
- action: "skip",
5753
- reason: `Issue #${issue} is already assigned (${assignees.join(", ")}) — no-op.`
5754
- };
5755
- }
5756
- if (login === null) {
5757
- return {
5758
- action: "skip",
5759
- reason: "Could not resolve the authenticated `gh` login — never assigning anyone other than the actual pusher, so skipping."
5760
- };
6615
+ // ../../packages/aeg-core/src/live-record.ts
6616
+ var RECORD_LINE_RE = /^-\s*\[([ xX])\]\s*\*\*\[live\]\*\*\s+(`+) ?(.+?) ?\2(?!`)\s+—\s+(passed|failed|unverified)\s+at\s+`([^`]+)`/;
6617
+ function liveMarkers(body) {
6618
+ const masked = maskCode(body);
6619
+ return [...masked.matchAll(/<!--\s*AEG:LIVE:(?:START|END)\s*-->/g)].map((m) => ({
6620
+ start: m.index,
6621
+ end: m.index + m[0].length
6622
+ }));
6623
+ }
6624
+ var AMBIGUOUS_RECORD_LINE = {
6625
+ line: "- [ ] **[live]** the pull request body carries more than one `AEG:LIVE` marker pair, so the driver's record cannot be told apart",
6626
+ ticked: false,
6627
+ command: "",
6628
+ outcome: "failed",
6629
+ head: ""
6630
+ };
6631
+ function readLiveRecord(body) {
6632
+ const markers = liveMarkers(body).length;
6633
+ if (markers === 0)
6634
+ return [];
6635
+ if (markers !== 2)
6636
+ return [AMBIGUOUS_RECORD_LINE];
6637
+ const region = anchoredRegion(body, "LIVE");
6638
+ if (region === null)
6639
+ return [];
6640
+ const lines = [];
6641
+ for (const raw of region.split(`
6642
+ `)) {
6643
+ const line = raw.trim();
6644
+ const m = RECORD_LINE_RE.exec(line);
6645
+ if (!m)
6646
+ continue;
6647
+ lines.push({
6648
+ line,
6649
+ ticked: m[1].toLowerCase() === "x",
6650
+ command: m[3],
6651
+ outcome: m[4],
6652
+ head: m[5]
6653
+ });
5761
6654
  }
5762
- return {
5763
- action: "assign",
5764
- issue,
5765
- login,
5766
- reason: `First push of \`${branch}\` — assigning Issue #${issue} to @${login} (the authenticated pusher).`
5767
- };
6655
+ return lines;
5768
6656
  }
5769
6657
  // ../../packages/aeg-core/src/test-plan-gate.ts
5770
- function evaluateTestPlanGate(body, branch) {
6658
+ function gradedLiveLines(record, live) {
6659
+ if (live === undefined)
6660
+ return record.map((entry) => entry.line);
6661
+ const commands = new Set(live.liveCommands);
6662
+ const others = record.filter((entry) => !commands.has(entry.command)).map((entry) => entry.line);
6663
+ const graded = live.liveCommands.map((command) => {
6664
+ const atHead = record.filter((entry) => entry.command === command && entry.head === live.head);
6665
+ return (atHead.find((entry) => entry.ticked) ?? atHead[0])?.line ?? `- [ ] **[live]** \`${command}\` — no passed run recorded at \`${live.head || "an unknown head"}\``;
6666
+ });
6667
+ return [...others, ...graded];
6668
+ }
6669
+ function evaluateTestPlanGate(body, branch, live) {
5771
6670
  if (!body) {
5772
6671
  return {
5773
6672
  verdict: "pass",
@@ -5778,7 +6677,9 @@ function evaluateTestPlanGate(body, branch) {
5778
6677
  };
5779
6678
  }
5780
6679
  const located = locateTestPlanSection(body);
5781
- if (!located.found) {
6680
+ const liveLines = gradedLiveLines(readLiveRecord(body), live);
6681
+ const liveUnticked = liveLines.some((line) => /^[-*]\s+\[\s\]/.test(line));
6682
+ if (!located.found && !liveUnticked) {
5782
6683
  if (parseTaskBranchIdentity(branch) !== null) {
5783
6684
  return {
5784
6685
  verdict: "fail",
@@ -5798,15 +6699,18 @@ function evaluateTestPlanGate(body, branch) {
5798
6699
  ]
5799
6700
  };
5800
6701
  }
5801
- const section = located.section;
5802
- if (/unit-tests-only/i.test(section)) {
6702
+ const section = located.found ? located.section : "";
6703
+ if (/unit-tests-only/i.test(section) && !liveUnticked) {
5803
6704
  return {
5804
6705
  verdict: "pass",
5805
6706
  messages: ["Test Plan: unit-tests-only — pure-logic brief, CI unit-tests are the proof.", "PASS."]
5806
6707
  };
5807
6708
  }
5808
- const checkboxLines = section.split(`
5809
- `).map((line) => line.trimStart()).filter((line) => /^[-*]\s+\[[ xX]\]\s*\*{0,2}\[principal\]\*{0,2}/i.test(line));
6709
+ const checkboxLines = [
6710
+ ...section.split(`
6711
+ `).map((line) => line.trimStart()).filter((line) => /^[-*]\s+\[[ xX]\]\s*\*{0,2}\[principal\]\*{0,2}/i.test(line)),
6712
+ ...liveLines
6713
+ ];
5810
6714
  if (checkboxLines.length === 0) {
5811
6715
  return {
5812
6716
  verdict: "pass",
@@ -5823,7 +6727,9 @@ function evaluateTestPlanGate(body, branch) {
5823
6727
  messages.push("", "FAIL — the following [principal] Test Plan items are unticked:");
5824
6728
  for (const line of unchecked)
5825
6729
  messages.push(` ${line}`);
5826
- 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.");
6730
+ 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 ? [
6731
+ "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."
6732
+ ] : [], "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.");
5827
6733
  return { verdict: "fail", messages };
5828
6734
  }
5829
6735
  messages.push("All [principal] Test Plan items ticked — runtime verification complete.", "PASS.");
@@ -6012,9 +6918,11 @@ var LineageSchema = z3.object({
6012
6918
  parent: z3.string().nullable()
6013
6919
  }).strict();
6014
6920
  var InputVersionsSchema = z3.object({
6921
+ manifest_version: z3.literal(2).nullable().optional(),
6015
6922
  objectives_version: z3.string().nullable(),
6016
6923
  brief_hash: z3.string().nullable(),
6017
6924
  ruling_ordinal: z3.number().int().nullable(),
6925
+ pause_bound_ruling: z3.object({ rulingId: z3.string().min(1), pauseId: z3.string().min(1), contentDigest: z3.string().min(1) }).strict().nullable().optional(),
6018
6926
  policy_digest: z3.string().nullable()
6019
6927
  }).strict();
6020
6928
  var ProvenanceSchema = z3.enum(["parent_attributed", "env_correlated", "self_reported", "unavailable"]);
@@ -6562,17 +7470,19 @@ function buildHeader(input) {
6562
7470
  parent: lineageFieldFromEnv(input.env.parent)
6563
7471
  },
6564
7472
  input_versions: {
7473
+ manifest_version: input.inputVersions?.manifestVersion ?? null,
6565
7474
  objectives_version: input.inputVersions?.objectivesVersion ?? null,
6566
7475
  brief_hash: input.inputVersions?.briefHash ?? null,
6567
7476
  ruling_ordinal: input.inputVersions?.rulingOrdinal ?? null,
7477
+ pause_bound_ruling: input.inputVersions?.pauseBoundRuling ?? null,
6568
7478
  policy_digest: input.inputVersions?.policyDigest ?? null
6569
7479
  },
6570
7480
  provenance: provenanceFor(input),
6571
7481
  work: {
6572
7482
  ref: lineageFieldFromEnv(input.env.workRef) ?? (issue === null ? null : String(issue)),
6573
7483
  repo: input.repo,
6574
- change: null,
6575
- revision: null
7484
+ change: pr === undefined ? null : String(pr),
7485
+ revision: input.revision ?? null
6576
7486
  },
6577
7487
  flow: {
6578
7488
  id: lineageFieldFromEnv(input.env.flow) ?? "vinaya",
@@ -6760,6 +7670,12 @@ var ManifestRecordSchema = z4.object({
6760
7670
  briefHash: z4.string().min(1).nullable(),
6761
7671
  objectivesVersion: z4.string().min(1).nullable(),
6762
7672
  rulingOrdinal: epochNumber,
7673
+ manifestVersion: z4.literal(2).optional(),
7674
+ pauseBoundRuling: z4.object({
7675
+ rulingId: z4.string().min(1),
7676
+ pauseId: z4.string().min(1),
7677
+ contentDigest: z4.string().min(1)
7678
+ }).strict().nullable().optional(),
6763
7679
  policyDigest: z4.string().min(1),
6764
7680
  recordedAt: isoTimestamp
6765
7681
  }).strict();
@@ -6781,7 +7697,11 @@ var LoopStateRecordSchema = z4.object({
6781
7697
  deliveredFindings: roundHeadIdentity.nullable(),
6782
7698
  repeatMemory: z4.object({
6783
7699
  blockingFindings: z4.array(z4.string()),
6784
- lastFailure: z4.object({ signature: z4.string(), message: z4.string() }).nullable()
7700
+ lastFailure: z4.object({ signature: z4.string(), message: z4.string(), developerAttemptedSince: z4.boolean().optional() }).nullable()
7701
+ }).strict().optional(),
7702
+ developerHandoff: z4.object({
7703
+ findings: z4.array(z4.object({ id: z4.string().min(1), description: z4.string().min(1) }).strict()),
7704
+ failingChecks: z4.array(z4.string().min(1))
6785
7705
  }).strict().optional(),
6786
7706
  publicationExpectedBase: z4.string().regex(/^[0-9a-f]{40}$/).nullable().optional(),
6787
7707
  taskStartedAt: isoTimestamp.optional(),
@@ -6839,8 +7759,8 @@ var ResolutionRecordSchema = z4.object({
6839
7759
  // ../../packages/aeg-core/src/control-store/local.ts
6840
7760
  var CONTROL_AREA_DIRNAME = "control";
6841
7761
  // src/lib/diff-evidence.ts
6842
- import { execFileSync as execFileSync8 } from "node:child_process";
6843
- import { join as join9, relative as relative2, resolve as resolve2 } from "node:path";
7762
+ import { execFileSync as execFileSync9 } from "node:child_process";
7763
+ import { join as join10, relative as relative2, resolve as resolve2 } from "node:path";
6844
7764
 
6845
7765
  // src/lib/config.ts
6846
7766
  import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
@@ -6848,30 +7768,321 @@ import { promisify as promisify4 } from "node:util";
6848
7768
  import { existsSync, mkdirSync, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync } from "node:fs";
6849
7769
  import { homedir } from "node:os";
6850
7770
  import { dirname, isAbsolute, join, resolve } from "node:path";
6851
- import { z as z5 } from "zod";
7771
+ import { z as z6 } from "zod";
7772
+
7773
+ // src/checks/contract.ts
7774
+ var CHECK_SCHEMA_VERSION = 1;
7775
+ function emitCheckError(error) {
7776
+ process.stderr.write(`${JSON.stringify(error)}
7777
+ `);
7778
+ }
6852
7779
 
6853
7780
  // src/lib/agent-vendors.ts
6854
7781
  var AGENT_VENDORS = ["skills", "claude", "gemini"];
6855
7782
 
6856
- // src/lib/config.ts
6857
- var EnvEntrySchema = z5.union([
6858
- z5.literal(true),
6859
- z5.object({ optional: z5.literal(true) }),
6860
- z5.object({ anyOf: z5.array(z5.string()).min(2) }),
6861
- z5.string()
6862
- ]);
6863
- var CheckEntrySchema = z5.object({
6864
- run: z5.string(),
6865
- scope: z5.enum(["diff", "full"]),
6866
- include: z5.array(z5.string()).optional(),
6867
- args: z5.array(z5.string()).optional(),
6868
- timeoutMs: z5.number().optional(),
6869
- env: z5.record(z5.string(), EnvEntrySchema).optional(),
6870
- requiresOpenPr: z5.boolean().optional(),
6871
- ownWorkflow: z5.boolean().optional(),
6872
- principalOwed: z5.literal(true).optional(),
6873
- validates: z5.enum(["body", "issue"]).optional()
6874
- }).superRefine((entry, ctx) => {
7783
+ // src/lib/prose-rules-config.ts
7784
+ import safeRegex from "safe-regex2";
7785
+ import { z as z5 } from "zod";
7786
+ var SEVERITIES = ["error", "warning"];
7787
+ var OVERRIDE_KEYS = ["scopes", "severity", "exempt"];
7788
+ var FIXED_DEFAULT_KEYS = ["pattern", "patterns", "flags", "means", "message", "id"];
7789
+ var CUSTOM_KEYS = ["id", "pattern", "patterns", "flags", "means", "scopes", "severity", "exempt"];
7790
+ var DEFAULT_IDS = new Set([...DEFAULT_PROSE_RULES.map((rule) => rule.id), DECISION_RECORD_CITATION_ID]);
7791
+ function isPlainObject3(value) {
7792
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7793
+ }
7794
+ function outsideRepositoryReason(entry) {
7795
+ if (entry.startsWith("/") || /^[A-Za-z]:/.test(entry))
7796
+ return "must be a repository-relative path, not an absolute one";
7797
+ if (entry.split(/[\\/]/).includes(".."))
7798
+ return "must stay inside the repository — no `..` segment";
7799
+ return null;
7800
+ }
7801
+ var RepoRelativePathSchema = z5.string().min(1).superRefine((entry, ctx) => {
7802
+ const reason = outsideRepositoryReason(entry);
7803
+ if (reason)
7804
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, message: reason });
7805
+ });
7806
+ function pathListIssues(value, path, issues) {
7807
+ if (!Array.isArray(value)) {
7808
+ issues.push({ path, message: "must be a list of repository-relative paths" });
7809
+ return;
7810
+ }
7811
+ value.forEach((entry, index) => {
7812
+ if (typeof entry !== "string" || entry.length === 0) {
7813
+ issues.push({ path: [...path, index], message: "must be a non-empty repository-relative path" });
7814
+ return;
7815
+ }
7816
+ const reason = outsideRepositoryReason(entry);
7817
+ if (reason)
7818
+ issues.push({ path: [...path, index], message: reason });
7819
+ });
7820
+ }
7821
+ function scopeListIssues(value, path, allowed, issues) {
7822
+ if (!Array.isArray(value) || value.length === 0) {
7823
+ issues.push({ path, message: "must name at least one scope" });
7824
+ return null;
7825
+ }
7826
+ const scopes = [];
7827
+ value.forEach((scope, index) => {
7828
+ if (typeof scope !== "string" || !CONFIGURABLE_PROSE_SCOPES.includes(scope)) {
7829
+ issues.push({
7830
+ path: [...path, index],
7831
+ 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(", ")}`
7832
+ });
7833
+ return;
7834
+ }
7835
+ if (!allowed.includes(scope)) {
7836
+ issues.push({
7837
+ path: [...path, index],
7838
+ message: `scope "${scope}" is not one this rule can run in — it can run in: ${allowed.join(", ")}`
7839
+ });
7840
+ return;
7841
+ }
7842
+ scopes.push(scope);
7843
+ });
7844
+ return scopes;
7845
+ }
7846
+ function severityIssues(value, path, scopes, issues) {
7847
+ if (typeof value === "string") {
7848
+ if (!SEVERITIES.includes(value)) {
7849
+ issues.push({ path, message: `unknown severity ${JSON.stringify(value)} — use "error" or "warning"` });
7850
+ }
7851
+ return;
7852
+ }
7853
+ if (!isPlainObject3(value)) {
7854
+ issues.push({ path, message: 'must be "error", "warning", or a map from scope to one of them' });
7855
+ return;
7856
+ }
7857
+ for (const [scope, severity] of Object.entries(value)) {
7858
+ if (!scopes.includes(scope)) {
7859
+ issues.push({ path: [...path, scope], message: `names scope "${scope}", which this rule's scopes do not cover` });
7860
+ }
7861
+ if (typeof severity !== "string" || !SEVERITIES.includes(severity)) {
7862
+ issues.push({
7863
+ path: [...path, scope],
7864
+ message: `unknown severity ${JSON.stringify(severity)} — use "error" or "warning"`
7865
+ });
7866
+ }
7867
+ }
7868
+ }
7869
+ function patternIssues(source, flags, path, issues) {
7870
+ if (typeof source !== "string" || source.length === 0) {
7871
+ issues.push({ path, message: "must be a non-empty regular expression" });
7872
+ return;
7873
+ }
7874
+ if (source.length > CONFIGURED_PATTERN_MAX_LENGTH) {
7875
+ issues.push({
7876
+ path,
7877
+ message: `is ${source.length} characters, over the ${CONFIGURED_PATTERN_MAX_LENGTH}-character limit for a configured pattern`
7878
+ });
7879
+ return;
7880
+ }
7881
+ try {
7882
+ new RegExp(source, flags);
7883
+ } catch (err) {
7884
+ issues.push({ path, message: `does not compile: ${err.message}` });
7885
+ return;
7886
+ }
7887
+ if (!safeRegex(source, { limit: Number.MAX_SAFE_INTEGER })) {
7888
+ issues.push({
7889
+ path,
7890
+ 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."
7891
+ });
7892
+ }
7893
+ }
7894
+ function flagIssues(value, path, issues) {
7895
+ if (value === undefined)
7896
+ return "";
7897
+ if (typeof value !== "string") {
7898
+ issues.push({ path, message: 'must be a string of flags, e.g. "i"' });
7899
+ return "";
7900
+ }
7901
+ const seen = new Set;
7902
+ for (const flag of value) {
7903
+ if (!CONFIGURED_PROSE_FLAGS.includes(flag)) {
7904
+ issues.push({
7905
+ path,
7906
+ message: `unknown flag ${JSON.stringify(flag)} — only ${CONFIGURED_PROSE_FLAGS.map((f) => `"${f}"`).join(" and ")} are allowed`
7907
+ });
7908
+ return "";
7909
+ }
7910
+ if (seen.has(flag)) {
7911
+ issues.push({ path, message: `repeats the flag "${flag}"` });
7912
+ return "";
7913
+ }
7914
+ seen.add(flag);
7915
+ }
7916
+ return value;
7917
+ }
7918
+ function defaultsIssues(value, issues) {
7919
+ const base = ["defaults"];
7920
+ if (!isPlainObject3(value)) {
7921
+ issues.push({ path: base, message: 'must map a default rule id to "off" or an override' });
7922
+ return;
7923
+ }
7924
+ for (const [id, override] of Object.entries(value)) {
7925
+ const path = [...base, id];
7926
+ const rule = CONFIGURABLE_DEFAULT_RULES.find((candidate) => candidate.id === id);
7927
+ if (!rule) {
7928
+ issues.push({
7929
+ path,
7930
+ message: `unknown default rule id "${id}" — \`vinaya check --plan\` lists the rules each prose check runs`
7931
+ });
7932
+ continue;
7933
+ }
7934
+ if (override === "off")
7935
+ continue;
7936
+ if (!isPlainObject3(override)) {
7937
+ issues.push({ path, message: 'must be "off" or an object with any of scopes, severity, exempt' });
7938
+ continue;
7939
+ }
7940
+ for (const key of Object.keys(override)) {
7941
+ if (OVERRIDE_KEYS.includes(key))
7942
+ continue;
7943
+ issues.push({
7944
+ path: [...path, key],
7945
+ 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`
7946
+ });
7947
+ }
7948
+ const scopes = override.scopes === undefined ? [...rule.scopes] : scopeListIssues(override.scopes, [...path, "scopes"], allowedScopesFor(rule), issues);
7949
+ if (override.severity !== undefined && scopes)
7950
+ severityIssues(override.severity, [...path, "severity"], scopes, issues);
7951
+ if (override.exempt !== undefined)
7952
+ pathListIssues(override.exempt, [...path, "exempt"], issues);
7953
+ }
7954
+ }
7955
+ function customIssues(value, issues) {
7956
+ if (!Array.isArray(value)) {
7957
+ issues.push({ path: ["custom"], message: "must be a list of rules" });
7958
+ return;
7959
+ }
7960
+ const ids = new Set;
7961
+ value.forEach((rule, index) => {
7962
+ const path = ["custom", index];
7963
+ if (!isPlainObject3(rule)) {
7964
+ issues.push({ path, message: "must be a rule object" });
7965
+ return;
7966
+ }
7967
+ for (const key of Object.keys(rule)) {
7968
+ if (!CUSTOM_KEYS.includes(key)) {
7969
+ issues.push({ path: [...path, key], message: `unknown key "${key}" — a rule takes ${CUSTOM_KEYS.join(", ")}` });
7970
+ }
7971
+ }
7972
+ if (typeof rule.id !== "string" || rule.id.length === 0) {
7973
+ issues.push({ path: [...path, "id"], message: "a custom rule needs an id" });
7974
+ } else if (DEFAULT_IDS.has(rule.id)) {
7975
+ issues.push({
7976
+ path: [...path, "id"],
7977
+ message: `"${rule.id}" is a default rule id — a custom rule needs its own id; retune the default under proseGates.rules.defaults instead`
7978
+ });
7979
+ } else if (ids.has(rule.id)) {
7980
+ issues.push({ path: [...path, "id"], message: `"${rule.id}" is used by an earlier custom rule` });
7981
+ } else {
7982
+ ids.add(rule.id);
7983
+ }
7984
+ if (typeof rule.means !== "string" || rule.means.trim().length === 0) {
7985
+ issues.push({ path: [...path, "means"], message: "a custom rule needs a message (`means`)" });
7986
+ }
7987
+ let scopes = null;
7988
+ if (rule.scopes === undefined) {
7989
+ issues.push({ path: [...path, "scopes"], message: "a custom rule needs at least one scope (`scopes`)" });
7990
+ } else {
7991
+ scopes = scopeListIssues(rule.scopes, [...path, "scopes"], CONFIGURABLE_PROSE_SCOPES, issues);
7992
+ }
7993
+ if (scopes && new Set(scopes.map(groupOfScope)).size > 1) {
7994
+ issues.push({
7995
+ path: [...path, "scopes"],
7996
+ 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'
7997
+ });
7998
+ }
7999
+ const flags = flagIssues(rule.flags, [...path, "flags"], issues);
8000
+ if (rule.pattern === undefined && rule.patterns === undefined) {
8001
+ issues.push({
8002
+ path: [...path, "pattern"],
8003
+ message: "a custom rule needs a `pattern` or a per-scope `patterns` map"
8004
+ });
8005
+ }
8006
+ if (rule.pattern !== undefined)
8007
+ patternIssues(rule.pattern, flags, [...path, "pattern"], issues);
8008
+ if (rule.patterns !== undefined) {
8009
+ if (!isPlainObject3(rule.patterns)) {
8010
+ issues.push({ path: [...path, "patterns"], message: "must map a scope to a regular expression" });
8011
+ } else {
8012
+ for (const [scope, source] of Object.entries(rule.patterns)) {
8013
+ if (scopes && !scopes.includes(scope)) {
8014
+ issues.push({
8015
+ path: [...path, "patterns", scope],
8016
+ message: `names scope "${scope}", which this rule's scopes do not cover`
8017
+ });
8018
+ continue;
8019
+ }
8020
+ patternIssues(source, flags, [...path, "patterns", scope], issues);
8021
+ }
8022
+ if (rule.pattern === undefined && scopes) {
8023
+ for (const scope of scopes) {
8024
+ if (!(scope in rule.patterns)) {
8025
+ issues.push({
8026
+ path: [...path, "patterns"],
8027
+ message: `has no pattern for scope "${scope}" — add one, or a \`pattern\` every other scope uses`
8028
+ });
8029
+ }
8030
+ }
8031
+ }
8032
+ }
8033
+ }
8034
+ if (rule.severity !== undefined && scopes)
8035
+ severityIssues(rule.severity, [...path, "severity"], scopes, issues);
8036
+ if (rule.exempt !== undefined)
8037
+ pathListIssues(rule.exempt, [...path, "exempt"], issues);
8038
+ });
8039
+ }
8040
+ function proseRulesIssues(value) {
8041
+ const issues = [];
8042
+ if (!isPlainObject3(value))
8043
+ return [{ path: [], message: "must be an object with any of exempt, defaults, custom" }];
8044
+ for (const key of Object.keys(value)) {
8045
+ if (!["exempt", "defaults", "custom"].includes(key)) {
8046
+ issues.push({ path: [key], message: `unknown key "${key}" — proseGates.rules takes exempt, defaults and custom` });
8047
+ }
8048
+ }
8049
+ if (value.exempt !== undefined)
8050
+ pathListIssues(value.exempt, ["exempt"], issues);
8051
+ if (value.defaults !== undefined)
8052
+ defaultsIssues(value.defaults, issues);
8053
+ if (value.custom !== undefined)
8054
+ customIssues(value.custom, issues);
8055
+ return issues;
8056
+ }
8057
+ var ProseRulesSchema = z5.unknown().superRefine((value, ctx) => {
8058
+ for (const issue of proseRulesIssues(value)) {
8059
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, path: issue.path, message: issue.message });
8060
+ }
8061
+ }).transform((value) => value);
8062
+ var PublishedProseSchema = z5.object({
8063
+ allow: z5.array(z5.string().min(1)).optional()
8064
+ }).strict();
8065
+
8066
+ // src/lib/config.ts
8067
+ var EnvEntrySchema = z6.union([
8068
+ z6.literal(true),
8069
+ z6.object({ optional: z6.literal(true) }),
8070
+ z6.object({ anyOf: z6.array(z6.string()).min(2) }),
8071
+ z6.string()
8072
+ ]);
8073
+ var CheckEntrySchema = z6.object({
8074
+ run: z6.string(),
8075
+ scope: z6.enum(["diff", "full"]),
8076
+ include: z6.array(z6.string()).optional(),
8077
+ args: z6.array(z6.string()).optional(),
8078
+ timeoutMs: z6.number().optional(),
8079
+ env: z6.record(z6.string(), EnvEntrySchema).optional(),
8080
+ requiresOpenPr: z6.boolean().optional(),
8081
+ ownWorkflow: z6.boolean().optional(),
8082
+ principalOwed: z6.literal(true).optional(),
8083
+ validates: z6.enum(["body", "issue"]).optional(),
8084
+ advisory: z6.literal(true).optional()
8085
+ }).superRefine((entry, ctx) => {
6875
8086
  if (!entry.env)
6876
8087
  return;
6877
8088
  for (const [key, value] of Object.entries(entry.env)) {
@@ -6880,22 +8091,22 @@ var CheckEntrySchema = z5.object({
6880
8091
  const members = value.anyOf;
6881
8092
  if (new Set(members).size !== members.length) {
6882
8093
  ctx.addIssue({
6883
- code: z5.ZodIssueCode.custom,
8094
+ code: z6.ZodIssueCode.custom,
6884
8095
  message: `env.${key}.anyOf has duplicate members`,
6885
8096
  path: ["env", key, "anyOf"]
6886
8097
  });
6887
8098
  }
6888
8099
  if (!members.includes(key)) {
6889
8100
  ctx.addIssue({
6890
- code: z5.ZodIssueCode.custom,
8101
+ code: z6.ZodIssueCode.custom,
6891
8102
  message: `env.${key}.anyOf must include "${key}" itself as a member`,
6892
8103
  path: ["env", key, "anyOf"]
6893
8104
  });
6894
8105
  }
6895
8106
  }
6896
8107
  });
6897
- var RoleEntrySchema = z5.object({
6898
- contract: z5.string().refine((p) => p.includes("/"), {
8108
+ var RoleEntrySchema = z6.object({
8109
+ contract: z6.string().refine((p) => p.includes("/"), {
6899
8110
  message: 'must be a path (contain at least one "/"), not a bare filename'
6900
8111
  })
6901
8112
  });
@@ -6919,17 +8130,17 @@ var BRIEF_BUILTINS = [
6919
8130
  "briefSections",
6920
8131
  "milestoneShape"
6921
8132
  ];
6922
- var BriefSectionSchema = z5.union([
6923
- z5.object({ builtin: z5.enum(BRIEF_BUILTINS) }),
6924
- z5.object({ heading: z5.string().min(1), name: z5.string().optional() }),
6925
- z5.object({ field: z5.string().min(1), name: z5.string().optional() }),
6926
- z5.object({ phrase: z5.string().min(1), name: z5.string().optional() })
8133
+ var BriefSectionSchema = z6.union([
8134
+ z6.object({ builtin: z6.enum(BRIEF_BUILTINS) }),
8135
+ z6.object({ heading: z6.string().min(1), name: z6.string().optional() }),
8136
+ z6.object({ field: z6.string().min(1), name: z6.string().optional() }),
8137
+ z6.object({ phrase: z6.string().min(1), name: z6.string().optional() })
6927
8138
  ]);
6928
- var BriefSchemaSchema = z5.object({
6929
- pr: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6930
- issue: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6931
- milestone: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6932
- ack: z5.array(z5.enum(BRIEF_BUILTINS)).optional()
8139
+ var BriefSchemaSchema = z6.object({
8140
+ pr: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8141
+ issue: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8142
+ milestone: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8143
+ ack: z6.array(z6.enum(BRIEF_BUILTINS)).optional()
6933
8144
  });
6934
8145
  function isSafeRepoRelPath(p) {
6935
8146
  if (p.length === 0)
@@ -6938,7 +8149,7 @@ function isSafeRepoRelPath(p) {
6938
8149
  return false;
6939
8150
  return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
6940
8151
  }
6941
- var SafeRepoRelPath = z5.string().refine(isSafeRepoRelPath, {
8152
+ var SafeRepoRelPath = z6.string().refine(isSafeRepoRelPath, {
6942
8153
  message: "must be a repo-root-relative path with no `..` segment or absolute root"
6943
8154
  });
6944
8155
  var CANONICAL_HOOK_BLOCK_PREFIXES = [".git/", ".husky/", ".vinaya/hooks/", ".claude/hooks/"];
@@ -6948,22 +8159,22 @@ function isCanonicalHookBlockPath(p) {
6948
8159
  var ManagedHookBlockPath = SafeRepoRelPath.refine(isCanonicalHookBlockPath, {
6949
8160
  message: `must start with one of ${CANONICAL_HOOK_BLOCK_PREFIXES.join(", ")} (byte-exact, case-sensitive)`
6950
8161
  });
6951
- var ManagedBlockRecordSchema = z5.object({
8162
+ var ManagedBlockRecordSchema = z6.object({
6952
8163
  path: ManagedHookBlockPath,
6953
- marker: z5.string(),
6954
- comment: z5.enum(["hash", "html"])
8164
+ marker: z6.string(),
8165
+ comment: z6.enum(["hash", "html"])
6955
8166
  });
6956
- var ManagedManifestSchema = z5.object({
6957
- version: z5.number().int().positive(),
6958
- files: z5.array(SafeRepoRelPath),
6959
- blocks: z5.array(ManagedBlockRecordSchema),
6960
- labels: z5.array(z5.string()),
6961
- agents: z5.array(z5.enum(AGENT_VENDORS)).optional()
8167
+ var ManagedManifestSchema = z6.object({
8168
+ version: z6.number().int().positive(),
8169
+ files: z6.array(SafeRepoRelPath),
8170
+ blocks: z6.array(ManagedBlockRecordSchema),
8171
+ labels: z6.array(z6.string()),
8172
+ agents: z6.array(z6.enum(AGENT_VENDORS)).optional()
6962
8173
  });
6963
- var ProjectEntrySchema = z5.object({
6964
- name: z5.string().min(1),
6965
- description: z5.string().min(1).optional(),
6966
- path: z5.string().min(1).optional()
8174
+ var ProjectEntrySchema = z6.object({
8175
+ name: z6.string().min(1),
8176
+ description: z6.string().min(1).optional(),
8177
+ path: z6.string().min(1).optional()
6967
8178
  });
6968
8179
  function parseTokensCollectDeclaration(value) {
6969
8180
  const m = value.trim().match(/^(\S+)\s+(\S+)$/);
@@ -6974,90 +8185,90 @@ function parseTokensCollectDeclaration(value) {
6974
8185
  return null;
6975
8186
  return { interpreter, script };
6976
8187
  }
6977
- var VinayaConfigSchema = z5.object({
6978
- rings: z5.object({
6979
- ring1_forgeWriteInterception: z5.boolean(),
6980
- ring2_asyncAudits: z5.boolean()
8188
+ var VinayaConfigObjectSchema = z6.object({
8189
+ rings: z6.object({
8190
+ ring1_forgeWriteInterception: z6.boolean(),
8191
+ ring2_asyncAudits: z6.boolean()
6981
8192
  }).optional(),
6982
- checks: z5.record(z5.string(), CheckEntrySchema).optional(),
6983
- roles: z5.record(z5.string(), RoleEntrySchema).optional(),
8193
+ checks: z6.record(z6.string(), CheckEntrySchema).optional(),
8194
+ roles: z6.record(z6.string(), RoleEntrySchema).optional(),
6984
8195
  briefSchema: BriefSchemaSchema.optional(),
6985
8196
  managed: ManagedManifestSchema.optional(),
6986
- principals: z5.array(z5.string()).min(1).optional(),
6987
- releaseActor: z5.string().min(1).optional(),
6988
- ci: z5.object({ setup: z5.string().min(1) }).optional(),
6989
- tokens: z5.object({
6990
- collect: z5.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
8197
+ principals: z6.array(z6.string()).min(1).optional(),
8198
+ releaseActor: z6.string().min(1).optional(),
8199
+ ci: z6.object({ setup: z6.string().min(1) }).optional(),
8200
+ tokens: z6.object({
8201
+ collect: z6.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
6991
8202
  message: 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
6992
8203
  })
6993
8204
  }).optional(),
6994
- blastRadius: z5.object({ extraDomains: z5.array(z5.string()).optional() }).optional(),
6995
- proseGates: z5.object({
6996
- doctrineRoot: z5.string().min(1).optional(),
6997
- readerFacingPrefix: z5.string().min(1).optional(),
6998
- readerFacingSuffix: z5.string().min(1).optional(),
6999
- legacySlugDir: z5.string().min(1).optional(),
7000
- sourceComments: z5.object({
7001
- globs: z5.array(z5.string().min(1)).optional(),
7002
- allowlist: z5.array(z5.string().min(1)).optional(),
7003
- severity: z5.enum(["warning", "error"]).optional()
8205
+ blastRadius: z6.object({ extraDomains: z6.array(z6.string()).optional() }).optional(),
8206
+ proseGates: z6.object({
8207
+ doctrineRoot: z6.string().min(1).optional(),
8208
+ readerFacingPrefix: z6.string().min(1).optional(),
8209
+ readerFacingSuffix: z6.string().min(1).optional(),
8210
+ legacySlugDir: z6.string().min(1).optional(),
8211
+ sourceComments: z6.object({
8212
+ globs: z6.array(z6.string().min(1)).optional(),
8213
+ allowlist: z6.array(z6.string().min(1)).optional(),
8214
+ severity: z6.enum(["warning", "error"]).optional()
7004
8215
  }).optional(),
7005
- specGrandfather: z5.union([z5.array(z5.string().min(1)), z5.record(z5.string().min(1), z5.number().int().min(0))]).optional(),
7006
- specPaths: z5.array(z5.string().min(1).refine((entry) => !entry.startsWith("/") && !/^[A-Za-z]:/.test(entry), {
7007
- message: "must be a repository-relative path, not an absolute one"
7008
- }).refine((entry) => !entry.split(/[\\/]/).includes(".."), {
7009
- message: "must stay inside the repository — no `..` segment"
7010
- })).optional()
8216
+ specGrandfather: z6.union([z6.array(z6.string().min(1)), z6.record(z6.string().min(1), z6.number().int().min(0))]).optional(),
8217
+ specPaths: z6.array(RepoRelativePathSchema).optional(),
8218
+ productPaths: z6.array(RepoRelativePathSchema).optional(),
8219
+ published: PublishedProseSchema.optional(),
8220
+ rules: ProseRulesSchema.optional()
7011
8221
  }).optional(),
7012
- projects: z5.array(ProjectEntrySchema).optional(),
7013
- dispatch: z5.object({
7014
- timeoutMs: z5.number().int().positive().optional(),
7015
- killGraceMs: z5.number().int().positive().optional(),
7016
- agent: z5.enum(["claude", "codex", "gemini"]).optional()
8222
+ projects: z6.array(ProjectEntrySchema).optional(),
8223
+ dispatch: z6.object({
8224
+ timeoutMs: z6.number().int().positive().optional(),
8225
+ reviewerTimeoutMs: z6.number().int().positive().optional(),
8226
+ killGraceMs: z6.number().int().positive().optional(),
8227
+ agent: z6.enum(["claude", "codex"]).optional()
7017
8228
  }).optional(),
7018
- reviewPolicy: z5.object({
7019
- codeReviewThreshold: z5.string().min(1).optional(),
7020
- securityThreshold: z5.string().min(1).optional(),
7021
- maxRounds: z5.number().optional(),
7022
- maxTaskMinutes: z5.number().optional()
8229
+ reviewPolicy: z6.object({
8230
+ codeReviewThreshold: z6.string().min(1).optional(),
8231
+ securityThreshold: z6.string().min(1).optional(),
8232
+ maxRounds: z6.number().optional(),
8233
+ maxTaskMinutes: z6.number().optional()
7023
8234
  }).optional(),
7024
- securityScan: z5.object({
7025
- command: z5.array(z5.string().min(1)).min(1)
8235
+ securityScan: z6.object({
8236
+ command: z6.array(z6.string().min(1)).min(1)
7026
8237
  }).optional(),
7027
- gateCutovers: z5.object({
7028
- objectivesSinceIssue: z5.number().int().nonnegative().optional(),
7029
- briefSectionsSinceIssue: z5.number().int().nonnegative().optional(),
7030
- documentationSinceIssue: z5.number().int().nonnegative().optional(),
7031
- briefRulesSincePr: z5.number().int().nonnegative().optional(),
7032
- agentBoxesRefusedSincePr: z5.number().int().nonnegative().optional()
8238
+ gateCutovers: z6.object({
8239
+ objectivesSinceIssue: z6.number().int().nonnegative().optional(),
8240
+ briefSectionsSinceIssue: z6.number().int().nonnegative().optional(),
8241
+ documentationSinceIssue: z6.number().int().nonnegative().optional(),
8242
+ briefRulesSincePr: z6.number().int().nonnegative().optional(),
8243
+ agentBoxesRefusedSincePr: z6.number().int().nonnegative().optional()
7033
8244
  }).optional(),
7034
- planning: z5.object({
7035
- collisionThreshold: z5.number().int().nonnegative().optional()
8245
+ planning: z6.object({
8246
+ collisionThreshold: z6.number().int().nonnegative().optional()
7036
8247
  }).optional(),
7037
- prePush: z5.object({
7038
- alwaysRun: z5.array(z5.string()).optional()
8248
+ prePush: z6.object({
8249
+ alwaysRun: z6.array(z6.string()).optional()
7039
8250
  }).optional(),
7040
- report: z5.object({
7041
- commandTimeoutMs: z5.number().int().positive().optional()
8251
+ report: z6.object({
8252
+ commandTimeoutMs: z6.number().int().positive().optional()
7042
8253
  }).superRefine((report, ctx) => {
7043
8254
  const commandTimeoutMs = report.commandTimeoutMs;
7044
8255
  if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
7045
8256
  ctx.addIssue({
7046
- code: z5.ZodIssueCode.custom,
8257
+ code: z6.ZodIssueCode.custom,
7047
8258
  path: ["commandTimeoutMs"],
7048
8259
  message: "must be at most 3600000 (1 hour)"
7049
8260
  });
7050
8261
  }
7051
8262
  }).optional(),
7052
- logPublish: z5.unknown().refine((v) => v === undefined, {
8263
+ logPublish: z6.unknown().refine((v) => v === undefined, {
7053
8264
  message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
7054
8265
  }),
7055
- runtimeDir: z5.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
7056
- logs: z5.object({
7057
- folder: z5.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
7058
- url: z5.string().url().optional(),
7059
- headers: z5.record(z5.string()).optional(),
7060
- readHeaders: z5.record(z5.string()).optional(),
8266
+ runtimeDir: z6.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
8267
+ logs: z6.object({
8268
+ folder: z6.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
8269
+ url: z6.string().url().optional(),
8270
+ headers: z6.record(z6.string()).optional(),
8271
+ readHeaders: z6.record(z6.string()).optional(),
7061
8272
  events: CustomEventDeclarationsSchema.optional()
7062
8273
  }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
7063
8274
  message: "logs: set at most one of folder/url"
@@ -7065,8 +8276,33 @@ var VinayaConfigSchema = z5.object({
7065
8276
  message: "logs: headers requires url"
7066
8277
  }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
7067
8278
  message: "logs: readHeaders requires url"
7068
- }).optional()
8279
+ }).optional(),
8280
+ decisionRecords: z6.object({
8281
+ path: RepoRelativePathSchema
8282
+ }).strict().optional()
7069
8283
  });
8284
+ function decisionRecordsPathIssue(path, doctrineRoot) {
8285
+ const reason = outsideRepositoryReason(path);
8286
+ if (reason)
8287
+ return reason;
8288
+ const folder = normalizeSpecPath(path);
8289
+ if (folder === "" || folder === ".")
8290
+ return "must name a folder, not the repository root";
8291
+ const root = normalizeSpecPath(doctrineRoot ?? "aeg-root");
8292
+ if (folder === root || folder.startsWith(`${root}/`)) {
8293
+ return `must be outside the doctrine tree "${root}" — decision records belong to this repository, not to the doctrine it ships`;
8294
+ }
8295
+ return null;
8296
+ }
8297
+ var VinayaConfigSchema = VinayaConfigObjectSchema.superRefine((config, ctx) => {
8298
+ const path = config.decisionRecords?.path;
8299
+ if (path === undefined || outsideRepositoryReason(path))
8300
+ return;
8301
+ const issue = decisionRecordsPathIssue(path, config.proseGates?.doctrineRoot);
8302
+ if (issue)
8303
+ ctx.addIssue({ code: z6.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
8304
+ });
8305
+ var VinayaConfigShape = VinayaConfigObjectSchema.shape;
7070
8306
  var GLOBAL_VINAYA_HOME = join(homedir(), ".vinaya");
7071
8307
  var GLOBAL_CONFIG_PATH = join(GLOBAL_VINAYA_HOME, "config.json");
7072
8308
  var LOCAL_CONFIG_FILENAME = "vinaya.config.json";
@@ -7147,9 +8383,6 @@ function stripGlobalOnlyKeys(config, path) {
7147
8383
  }
7148
8384
  return result;
7149
8385
  }
7150
- function resolvePrincipalAllowlist(config) {
7151
- return config?.principals ?? PRINCIPAL_ALLOWLIST;
7152
- }
7153
8386
  function resolveReleaseActor(config) {
7154
8387
  return config?.releaseActor ?? DEFAULT_RELEASE_ACTOR;
7155
8388
  }
@@ -7285,13 +8518,14 @@ function readTrustAnchorConfigAtRef(ref) {
7285
8518
  });
7286
8519
  return Buffer.from(raw, "utf-8").toString("base64");
7287
8520
  }
8521
+ var NO_TRUST_ANCHOR_REPO_MESSAGE = "could not resolve repo identity for the trust-anchor read";
7288
8522
  function ghFetchTrustAnchorConfig() {
7289
8523
  const probeRef = resolveCiTrustAnchorProbeRef();
7290
8524
  if (probeRef)
7291
8525
  return readTrustAnchorConfigAtRef(probeRef);
7292
8526
  const repo = trustAnchorRepo();
7293
8527
  if (!repo)
7294
- throw new Error("could not resolve repo identity for the trust-anchor read");
8528
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
7295
8529
  return execFileSync2("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
7296
8530
  encoding: "utf-8",
7297
8531
  stdio: ["ignore", "pipe", "pipe"]
@@ -7308,7 +8542,7 @@ async function ghFetchTrustAnchorConfigAsync() {
7308
8542
  }
7309
8543
  const repo = await trustAnchorRepoAsync();
7310
8544
  if (!repo)
7311
- throw new Error("could not resolve repo identity for the trust-anchor read");
8545
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
7312
8546
  const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4, killSignal: "SIGKILL" });
7313
8547
  return stdout;
7314
8548
  }
@@ -7334,6 +8568,47 @@ function loadTrustAnchorConfig(fetcher = ghFetchTrustAnchorConfig) {
7334
8568
  }
7335
8569
  return parseTrustAnchorContent(base64);
7336
8570
  }
8571
+ class PrincipalsUnresolvedError extends Error {
8572
+ kind;
8573
+ constructor(kind, message) {
8574
+ super(message);
8575
+ this.name = "PrincipalsUnresolvedError";
8576
+ this.kind = kind;
8577
+ }
8578
+ }
8579
+ var PRINCIPALS_FIX = 'add "principals": [...] to vinaya.config.json on the default branch';
8580
+ function fetchFailureReason(err) {
8581
+ const stderr = err?.stderr;
8582
+ const text = (typeof stderr === "string" ? stderr : stderr?.toString() ?? "").trim();
8583
+ return text.split(`
8584
+ `)[0]?.trim() || firstLine(err);
8585
+ }
8586
+ function principalsNotConfigured(why) {
8587
+ return new PrincipalsUnresolvedError("not-configured", `no Principal is configured (${why}) — ${PRINCIPALS_FIX}.`);
8588
+ }
8589
+ function resolveTrustedPrincipals(fetcher = ghFetchTrustAnchorConfig) {
8590
+ let content;
8591
+ try {
8592
+ content = fetcher();
8593
+ } catch (err) {
8594
+ if (err?.message === NO_TRUST_ANCHOR_REPO_MESSAGE) {
8595
+ throw principalsNotConfigured("no repository resolves for the read");
8596
+ }
8597
+ if (isMissingFileError(err))
8598
+ throw principalsNotConfigured("the default branch has no vinaya.config.json");
8599
+ throw new PrincipalsUnresolvedError("read-failed", `could not read "principals" from vinaya.config.json on the default branch: ${fetchFailureReason(err)}`);
8600
+ }
8601
+ const unusable = { why: "" };
8602
+ const config = parseTrustAnchorContent(content, (why) => {
8603
+ unusable.why = why;
8604
+ });
8605
+ if (config === null) {
8606
+ throw principalsNotConfigured(`vinaya.config.json on the default branch ${unusable.why ? `is unusable: ${unusable.why}` : "is empty"}`);
8607
+ }
8608
+ if (!config.principals)
8609
+ throw principalsNotConfigured('vinaya.config.json on the default branch sets no "principals"');
8610
+ return config.principals;
8611
+ }
7337
8612
  async function loadTrustAnchorConfigAsync(fetcher = ghFetchTrustAnchorConfigAsync, options = {}) {
7338
8613
  const warn = options.quiet ? () => {} : warnTrustAnchorFallback;
7339
8614
  let base64;
@@ -7373,17 +8648,183 @@ function loadConfig() {
7373
8648
  const path = configPath();
7374
8649
  if (!path)
7375
8650
  return null;
8651
+ let text;
7376
8652
  try {
7377
- const raw = JSON.parse(readFileSync2(path, "utf-8"));
7378
- return stripGlobalOnlyKeys(VinayaConfigSchema.parse(raw), path);
7379
- } catch {
8653
+ text = readFileSync2(path, "utf-8");
8654
+ } catch (err) {
8655
+ reportInvalidConfigOnce(path, `unreadable: ${err.message}`);
7380
8656
  return null;
7381
8657
  }
8658
+ let raw;
8659
+ try {
8660
+ raw = JSON.parse(text);
8661
+ } catch (err) {
8662
+ reportInvalidConfigOnce(path, `invalid JSON: ${err.message}`);
8663
+ return null;
8664
+ }
8665
+ const parsed = VinayaConfigSchema.safeParse(raw);
8666
+ if (!parsed.success) {
8667
+ reportInvalidConfigOnce(path, schemaIssueDetail(parsed.error));
8668
+ return null;
8669
+ }
8670
+ return stripGlobalOnlyKeys(parsed.data, path);
8671
+ }
8672
+ function schemaIssueDetail(error) {
8673
+ return error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
8674
+ }
8675
+ var emittedInvalidConfigReports = new Set;
8676
+ function reportInvalidConfigOnce(path, detail) {
8677
+ const key = `${path}
8678
+ ${detail}`;
8679
+ if (emittedInvalidConfigReports.has(key))
8680
+ return;
8681
+ emittedInvalidConfigReports.add(key);
8682
+ const message = `${path} is not a valid Vinaya configuration (${detail}) — falling back to built-in defaults.`;
8683
+ const checkName = process.env.VINAYA_CHECK_NAME;
8684
+ if (checkName) {
8685
+ emitCheckError({
8686
+ schema: CHECK_SCHEMA_VERSION,
8687
+ check: checkName,
8688
+ severity: "warning",
8689
+ message,
8690
+ agent_recovery_prompt: `Fix the failing keys in ${path} (${detail}) so the file parses and satisfies the configuration schema, then re-run.`,
8691
+ file: path
8692
+ });
8693
+ return;
8694
+ }
8695
+ console.error(`⚠ ${message}`);
8696
+ }
8697
+ function loadConfigChecked() {
8698
+ const path = configPath();
8699
+ if (!path)
8700
+ return { ok: true, config: null };
8701
+ let raw;
8702
+ try {
8703
+ raw = JSON.parse(readFileSync2(path, "utf-8"));
8704
+ } catch (err) {
8705
+ return { ok: false, path, error: `invalid JSON: ${err.message}` };
8706
+ }
8707
+ const parsed = VinayaConfigSchema.safeParse(raw);
8708
+ if (!parsed.success) {
8709
+ return { ok: false, path, error: schemaIssueDetail(parsed.error) };
8710
+ }
8711
+ return { ok: true, config: stripGlobalOnlyKeys(parsed.data, path) };
7382
8712
  }
7383
8713
  var TOKENS_COLLECT_TRUST_PATH = join(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
7384
8714
 
7385
8715
  // src/lib/forge-read.ts
7386
8716
  import { execFileSync as execFileSync3 } from "node:child_process";
8717
+
8718
+ // src/lib/forge-snapshot.ts
8719
+ import { existsSync as existsSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
8720
+ import { join as join2 } from "node:path";
8721
+ var FORGE_SNAPSHOT_DIR_ENV = "VINAYA_FORGE_SNAPSHOT_DIR";
8722
+ var PULL_FILE = "pull.json";
8723
+ var PULL_COMMENTS_FILE = "pull-comments.json";
8724
+ var ISSUE_FILE = "issue.json";
8725
+ var ISSUE_COMMENTS_FILE = "issue-comments.json";
8726
+ function forgeSnapshotDir(env = process.env) {
8727
+ if (env.GITHUB_ACTIONS !== "true")
8728
+ return null;
8729
+ const dir = env[FORGE_SNAPSHOT_DIR_ENV];
8730
+ return dir ? dir : null;
8731
+ }
8732
+
8733
+ class ForgeSnapshotIncompleteError extends Error {
8734
+ constructor(dir, file) {
8735
+ 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.`);
8736
+ this.name = "ForgeSnapshotIncompleteError";
8737
+ }
8738
+ }
8739
+
8740
+ class ForgeSnapshotIssueNotFoundError extends Error {
8741
+ constructor(issue) {
8742
+ super(`Issue #${issue} did not resolve (HTTP 404) when this run's forge snapshot was read.`);
8743
+ this.name = "ForgeSnapshotIssueNotFoundError";
8744
+ }
8745
+ }
8746
+ function readSnapshotFile(dir, file) {
8747
+ let text;
8748
+ try {
8749
+ text = readFileSync3(join2(dir, file), "utf8");
8750
+ } catch {
8751
+ throw new ForgeSnapshotIncompleteError(dir, file);
8752
+ }
8753
+ return JSON.parse(text);
8754
+ }
8755
+ function readComments(dir, file, number) {
8756
+ const parsed = readSnapshotFile(dir, file);
8757
+ if (parsed.number !== number)
8758
+ throw new ForgeSnapshotIncompleteError(dir, `${file} for #${number}`);
8759
+ return parsed.comments;
8760
+ }
8761
+ function snapshotPullRequest(number, env = process.env) {
8762
+ const dir = forgeSnapshotDir(env);
8763
+ if (dir === null)
8764
+ return null;
8765
+ const pull = readSnapshotFile(dir, PULL_FILE);
8766
+ return pull.number === number ? pull : null;
8767
+ }
8768
+ function snapshotIssue(number, env = process.env) {
8769
+ const dir = forgeSnapshotDir(env);
8770
+ if (dir === null)
8771
+ return null;
8772
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
8773
+ if (issue.number !== number)
8774
+ return null;
8775
+ if ("notFound" in issue)
8776
+ throw new ForgeSnapshotIssueNotFoundError(number);
8777
+ return issue;
8778
+ }
8779
+ function snapshotComments(number, env = process.env) {
8780
+ const dir = forgeSnapshotDir(env);
8781
+ if (dir === null)
8782
+ return null;
8783
+ if (snapshotPullRequest(number, env) !== null)
8784
+ return readComments(dir, PULL_COMMENTS_FILE, number);
8785
+ if (snapshotIssue(number, env) !== null)
8786
+ return readComments(dir, ISSUE_COMMENTS_FILE, number);
8787
+ return null;
8788
+ }
8789
+ function snapshotBody(number, env = process.env) {
8790
+ const pull = snapshotPullRequest(number, env);
8791
+ if (pull !== null)
8792
+ return pull.body;
8793
+ return snapshotIssue(number, env)?.body ?? null;
8794
+ }
8795
+ function incompleteForgeSnapshot(env = process.env) {
8796
+ const dir = forgeSnapshotDir(env);
8797
+ if (dir === null)
8798
+ return null;
8799
+ for (const file of [PULL_FILE, PULL_COMMENTS_FILE, ISSUE_FILE]) {
8800
+ if (!existsSync2(join2(dir, file)))
8801
+ return new ForgeSnapshotIncompleteError(dir, file).message;
8802
+ }
8803
+ try {
8804
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
8805
+ if (typeof issue.number === "number" && !("notFound" in issue) && !existsSync2(join2(dir, ISSUE_COMMENTS_FILE))) {
8806
+ return new ForgeSnapshotIncompleteError(dir, ISSUE_COMMENTS_FILE).message;
8807
+ }
8808
+ } catch (err) {
8809
+ return `the forge snapshot ${dir} has an unreadable ${ISSUE_FILE}: ${err.message}`;
8810
+ }
8811
+ return null;
8812
+ }
8813
+ function exitOnIncompleteForgeSnapshot(checkName, env = process.env) {
8814
+ const reason = incompleteForgeSnapshot(env);
8815
+ if (reason === null)
8816
+ return;
8817
+ emitCheckError({
8818
+ schema: CHECK_SCHEMA_VERSION,
8819
+ check: checkName,
8820
+ severity: "error",
8821
+ message: `${checkName}: ${reason}`,
8822
+ 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.`
8823
+ });
8824
+ process.exit(1);
8825
+ }
8826
+
8827
+ // src/lib/forge-read.ts
7387
8828
  var FORGE_READ_CEILING_BYTES = 64 * 1024 * 1024;
7388
8829
  var PAGE_SIZE = 100;
7389
8830
  var ghRunner = (args, maxBuffer) => execFileSync3("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer });
@@ -7406,7 +8847,7 @@ function isForgeReadOversize(err) {
7406
8847
  function isBufferOverflow(err) {
7407
8848
  return err?.code === "ENOBUFS";
7408
8849
  }
7409
- function run2(runner, args, subject, usedBytes) {
8850
+ function runBounded(runner, args, subject, usedBytes) {
7410
8851
  const remaining = FORGE_READ_CEILING_BYTES - usedBytes;
7411
8852
  let out;
7412
8853
  try {
@@ -7421,31 +8862,40 @@ function run2(runner, args, subject, usedBytes) {
7421
8862
  throw new ForgeReadOversizeError(subject, usedBytes + size);
7422
8863
  return out;
7423
8864
  }
7424
- function readIssueComments(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
7425
- const number = resolveNumber(issue, subjectLabel, runner);
7426
- const comments = [];
8865
+ function readRestCommentRows(number, subjectLabel = `Issue ${number}`, runner = ghRunner) {
8866
+ const rows = [];
7427
8867
  let used = 0;
7428
8868
  for (let page = 1;; page++) {
7429
- const out = run2(runner, ["api", `repos/{owner}/{repo}/issues/${number}/comments?per_page=${PAGE_SIZE}&page=${page}`], subjectLabel, used);
8869
+ const out = runBounded(runner, ["api", `repos/{owner}/{repo}/issues/${number}/comments?per_page=${PAGE_SIZE}&page=${page}`], subjectLabel, used);
7430
8870
  used += Buffer.byteLength(out, "utf8");
7431
- const rows = JSON.parse(out);
7432
- for (const r of rows) {
7433
- comments.push({
7434
- body: r.body ?? "",
7435
- url: r.html_url ?? "",
7436
- author: r.user?.login ? { login: r.user.login } : null
7437
- });
7438
- }
7439
- if (rows.length < PAGE_SIZE)
7440
- return comments;
8871
+ const pageRows = JSON.parse(out);
8872
+ rows.push(...pageRows);
8873
+ if (pageRows.length < PAGE_SIZE)
8874
+ return rows;
7441
8875
  }
7442
8876
  }
8877
+ function readIssueComments(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
8878
+ const number = resolveNumber(issue, subjectLabel, runner);
8879
+ const fromSnapshot = snapshotComments(number);
8880
+ if (fromSnapshot !== null)
8881
+ return fromSnapshot;
8882
+ return readRestCommentRows(number, subjectLabel, runner).map((r) => ({
8883
+ body: r.body ?? "",
8884
+ url: r.html_url ?? "",
8885
+ author: r.user?.login ? { login: r.user.login } : null
8886
+ }));
8887
+ }
7443
8888
  function readIssueBody(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
7444
- const out = run2(runner, ["issue", "view", String(issue), "--json", "body"], subjectLabel, 0);
8889
+ if (forgeSnapshotDir() !== null) {
8890
+ const fromSnapshot = snapshotBody(resolveNumber(issue, subjectLabel, runner));
8891
+ if (fromSnapshot !== null)
8892
+ return fromSnapshot;
8893
+ }
8894
+ const out = runBounded(runner, ["issue", "view", String(issue), "--json", "body"], subjectLabel, 0);
7445
8895
  return JSON.parse(out).body ?? "";
7446
8896
  }
7447
8897
  function readIssueFields(issue, fields, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
7448
- return JSON.parse(run2(runner, ["issue", "view", String(issue), "--json", fields], subjectLabel, 0));
8898
+ return JSON.parse(runBounded(runner, ["issue", "view", String(issue), "--json", fields], subjectLabel, 0));
7449
8899
  }
7450
8900
  function resolveNumber(issue, subjectLabel, runner) {
7451
8901
  if (typeof issue === "number")
@@ -7456,9 +8906,9 @@ function resolveNumber(issue, subjectLabel, runner) {
7456
8906
  }
7457
8907
 
7458
8908
  // src/lib/brief-assembly.ts
7459
- import { execFileSync as execFileSync6 } from "node:child_process";
7460
- import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2 } from "node:fs";
7461
- import { join as join4 } from "node:path";
8909
+ import { execFileSync as execFileSync7 } from "node:child_process";
8910
+ import { existsSync as existsSync5, readFileSync as readFileSync5, readdirSync as readdirSync2 } from "node:fs";
8911
+ import { join as join5 } from "node:path";
7462
8912
 
7463
8913
  // ../../packages/sources/src/commands.ts
7464
8914
  var COMMANDS = [
@@ -7574,6 +9024,16 @@ var COMMANDS = [
7574
9024
  ],
7575
9025
  status: "shipped"
7576
9026
  },
9027
+ {
9028
+ name: "new adr",
9029
+ needs: [],
9030
+ description: "Write the next numbered decision record into the folder decisionRecords.path names",
9031
+ details: [
9032
+ "`vinaya new adr <title>` writes `<decisionRecords.path>/NNNN-<kebab-title>.md` from the shipped decision-record template (`vinaya doctrine --template decision-record`), with status Proposed and today's date, and adds a row for it to the folder's `README.md` index page, creating that page on the first record. Numbers start at `0001` and are one past the highest number any file in the folder or any row of the index carries, so a number is never reused, even after its file is removed.",
9033
+ "Refuses, naming the key, while `decisionRecords.path` is unset: decision records are opt-in. The same key switches on the `decision-record-citation` writing rule — see `decisionRecords.path` in the configuration reference."
9034
+ ],
9035
+ status: "shipped"
9036
+ },
7577
9037
  {
7578
9038
  name: "brief render",
7579
9039
  needs: ["forge", "default-branch"],
@@ -7592,9 +9052,7 @@ var COMMANDS = [
7592
9052
  name: "task dispatch",
7593
9053
  needs: ["forge", "operator-seat"],
7594
9054
  description: "Deprecated — render, pin, and post the brief on the Issue as the frozen original; start the developer",
7595
- flags: [
7596
- { flag: "--agent <claude|codex|gemini>", description: "Start the developer through dispatchRole once posted" }
7597
- ],
9055
+ flags: [{ flag: "--agent <claude|codex>", description: "Start the developer through dispatchRole once posted" }],
7598
9056
  details: [
7599
9057
  "Renders the brief from the Issue and the tree (the same assembly `brief render` uses) and posts it once as an Issue comment whose first line is `<!-- aeg:brief:v1 -->` and whose second line is `Brief hash: <sha256>` — the hash covers only the body below those two lines, so any reader recomputes it. Refuses outright, naming the existing comment's URL, when a `v1` comment already exists on the Issue — the brief is frozen by design, never overwritten or silently reissued.",
7600
9058
  "With `--agent`, starts the Developer through `dispatchRole` when `apps/cli/src/lib/dispatch.ts` exports it; otherwise prints the rendered brief and the manual dispatch instruction and exits `0` — a soft dependency, never a hard block.",
@@ -7619,7 +9077,7 @@ var COMMANDS = [
7619
9077
  description: "One command from a planned Issue to a reviewed pull request — exactly one developer started",
7620
9078
  flags: [
7621
9079
  {
7622
- flag: "--agent <claude|codex|gemini>",
9080
+ flag: "--agent <claude|codex>",
7623
9081
  description: "Vendor for the developer and both reviewers this run dispatches"
7624
9082
  },
7625
9083
  {
@@ -7794,6 +9252,22 @@ var COMMANDS = [
7794
9252
  ],
7795
9253
  status: "shipped"
7796
9254
  },
9255
+ {
9256
+ name: "pr snapshot",
9257
+ needs: ["forge"],
9258
+ description: "CI plumbing: write a run's forge snapshot of the pull request and its task Issue, read over REST",
9259
+ flags: [
9260
+ {
9261
+ flag: "--dir",
9262
+ description: "The snapshot directory; its `raw/` holds the REST pull request and comment pages the read step wrote"
9263
+ }
9264
+ ],
9265
+ details: [
9266
+ "Run by the generated workflows' read step, never by hand. Maps the REST pull request and its comments to the shape `gh pr view --json` prints, resolves the task Issue from the body's `Closes #N`, and reads that Issue and its comments over REST — never GraphQL.",
9267
+ "A check reads the snapshot only when `GITHUB_ACTIONS` is `true` and the step running it sets `VINAYA_FORGE_SNAPSHOT_DIR`; anywhere else every read goes to the forge as before. Exits 1, naming what it could not read and both token budgets, on a failed read; 2 on a usage error."
9268
+ ],
9269
+ status: "shipped"
9270
+ },
7797
9271
  {
7798
9272
  name: "issue create",
7799
9273
  needs: ["forge"],
@@ -7914,14 +9388,14 @@ var COMMANDS = [
7914
9388
  {
7915
9389
  name: "milestone close",
7916
9390
  needs: ["forge"],
7917
- description: "Close a tranche's Milestone after verifying every labeled Issue is actually attached",
9391
+ description: "Close a tranche's Milestone after verifying every labeled Issue is attached and every tranche it declares is complete",
7918
9392
  flags: [
7919
9393
  { flag: "--slug", description: "The tranche whose Milestone is being closed" },
7920
9394
  { flag: "--validate-only", description: "Run every gate and report PASS without closing the Milestone" },
7921
9395
  { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
7922
9396
  ],
7923
9397
  details: [
7924
- "Resolves the target Milestone the same legacy-or-intent-declared way Issue create auto-attach does, then refuses to close on any mismatch between the label's Issues and the Milestone's natively attached Issues — naming each unattached or foreign Issue and its repair path (`gh issue edit <n> --milestone <title>`, or `vinaya milestone adopt`) — before the PATCH ever reaches the forge."
9398
+ "Resolves the target Milestone the same legacy-or-intent-declared way Issue create auto-attach does, then refuses to close on any mismatch between the label's Issues and the Milestone's natively attached Issues — naming each unattached or foreign Issue and its repair path (`gh issue edit <n> --milestone <title>`, or `vinaya milestone adopt`) — before the PATCH ever reaches the forge. It also holds the Milestone open while a tranche its `### Tranche intents` section declares is not complete — naming each unfinished tranche and its lifecycle — or while that section carries no readable tranche line; a Milestone with no such section closes on attachment alone. `--validate-only` refuses with the same reasons."
7925
9399
  ],
7926
9400
  status: "shipped"
7927
9401
  },
@@ -8210,7 +9684,7 @@ var COMMANDS = [
8210
9684
  }
8211
9685
  ],
8212
9686
  details: [
8213
- "Refuses unless HEAD is the default branch, the working tree is clean, HEAD equals `origin/<default>` (after `git fetch origin`), HEAD's commit subject starts with `Chore(release): Version packages` (unless `--allow-any-commit`), and `npm whoami` exits `0` — each its own refusal naming the fix.",
9687
+ "Refuses unless HEAD is the default branch, the working tree is clean, HEAD equals `origin/<default>` (after `git fetch origin`), HEAD's commit subject starts with `Chore(release): Version packages` (unless `--allow-any-commit`), and `npm whoami` exits `0`. Before any plan step, including under `--dry-run`, every package in `.changeset/config.json` fixed groups must have an unpublished working-tree version. Exact-version registry queries refuse with every already-published package and version; workspace read failures and registry errors other than E404 also refuse with their reason. E404 for a missing package or version counts as unpublished.",
8214
9688
  "Then streams `bun install --frozen-lockfile`, `bun run build`, `bun run changeset:publish`, and `git push origin --tags` — a real push, so the repo's own generated pre-push hook sees it exactly as any other push would. After it, prints `npm view <pkg> version` for every tag now on HEAD, noting registry lag on `@attalabs/vinaya` (observed ~20 minutes) when it still shows the previous version.",
8215
9689
  'This is the one procedure named in `apps/cli/specs/self-hosting.md`, "How the published version is produced" — publishing itself stays manual and human-triggered; this command only removes the hand-typed four-step recipe.'
8216
9690
  ],
@@ -8219,11 +9693,11 @@ var COMMANDS = [
8219
9693
  {
8220
9694
  name: "dispatch",
8221
9695
  needs: ["operator-seat"],
8222
- description: "Start a role's headless agent session (claude/codex/gemini) with attribution set on its environment, recording the outcome through the Vinaya Log",
9696
+ description: "Start a role's headless agent session (claude/codex) with attribution set on its environment, recording the outcome through the Vinaya Log",
8223
9697
  flags: [
8224
9698
  {
8225
9699
  flag: "--agent",
8226
- description: "Vendor to start: `claude`, `codex`, or `gemini` (falls back to `dispatch.agent` in config)"
9700
+ description: "Vendor to start: `claude` or `codex` (falls back to `dispatch.agent` in config)"
8227
9701
  },
8228
9702
  { flag: "--prompt-file", description: "Path to the prompt text sent to the agent (never on argv)" },
8229
9703
  { flag: "--task", description: "This dispatch's task Issue number — mutually exclusive with `--pr`" },
@@ -8240,9 +9714,9 @@ var COMMANDS = [
8240
9714
  ],
8241
9715
  details: [
8242
9716
  "Sets `VINAYA_RUN_ID`/`VINAYA_ROLE`/`VINAYA_TASK`/`VINAYA_ROUND` on the child only — never on this process's own environment — and refuses by name, before any spawn attempt, when the named vendor binary is absent from `PATH` or present but not executable.",
8243
- "Records `dispatched` (with the prompt's sha256), `outcome_received` (duration, the vendor's own usage when its stdout prints a recognizable shape), or `dispatch_failed` (`timeout`, `crash`, or `refused`) through the Vinaya Log's one `dispatch` family writer, `dispatchRole`. A wall-time ceiling (`dispatch.timeoutMs` in config, default one hour) sends `SIGTERM` then, after a grace window, `SIGKILL`.",
9717
+ "Records `dispatched` (with the prompt's sha256), `outcome_received` (duration, the vendor's own usage when its stdout prints a recognizable shape), or `dispatch_failed` (`timeout`, `crash`, `refused`, or `usage_limit`) through the Vinaya Log's one `dispatch` family writer, `dispatchRole`. A wall-time ceiling (`dispatch.timeoutMs` in config, default one hour) sends `SIGTERM` then, after a grace window, `SIGKILL`.",
8244
9718
  "Runs no flush of its own after the dispatch returns: every log line `dispatchRole` emits reaches its configured `logs` destination live, as it is emitted, so there is nothing left to ship in a trailing step. `--task`/`--pr` are attribution only, and remain mutually exclusive.",
8245
- "A successful dispatch's `DispatchHandle` carries `resumeId` — the vendor's own session/thread identifier (claude/gemini: `session_id`; codex: `thread_id`), parsed from its stdout, `null` on any failure. Passing that value as `--resume <id>` on a later call swaps in that vendor's own resume invocation (`claude -p -r <id> ...`; `codex exec resume <id> ...`; `gemini ... --resume <id> ...`) in place of its first-dispatch args."
9719
+ "A successful dispatch's `DispatchHandle` carries `resumeId` — the vendor's own session/thread identifier (claude: `session_id`; codex: `thread_id`), parsed from its stdout, `null` on any failure. Passing that value as `--resume <id>` on a later call swaps in that vendor's own resume invocation (`claude -p -r <id> ...`; `codex exec resume <id> ...`) in place of its first-dispatch args."
8246
9720
  ],
8247
9721
  status: "shipped"
8248
9722
  },
@@ -8253,7 +9727,7 @@ var COMMANDS = [
8253
9727
  flags: [
8254
9728
  { flag: "--task <n>", description: "This task's Issue number — its frozen `aeg:brief:v1` comment is the brief" },
8255
9729
  {
8256
- flag: "--agent <claude|codex|gemini>",
9730
+ flag: "--agent <claude|codex>",
8257
9731
  description: "Vendor for every dispatch this loop makes (falls back to `dispatch.agent` in config)"
8258
9732
  },
8259
9733
  { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
@@ -8332,22 +9806,72 @@ function createForgeSource(config) {
8332
9806
  };
8333
9807
  }
8334
9808
  // ../../packages/sources/src/select-source.ts
8335
- import { z as z6 } from "zod";
8336
- var StateSourceConfigSchema = z6.discriminatedUnion("kind", [
8337
- z6.object({ kind: z6.literal("forge"), owner: z6.string(), repo: z6.string() }),
8338
- z6.object({ kind: z6.literal("file"), root: z6.string().optional() })
9809
+ import { z as z7 } from "zod";
9810
+ var StateSourceConfigSchema = z7.discriminatedUnion("kind", [
9811
+ z7.object({ kind: z7.literal("forge"), owner: z7.string(), repo: z7.string() }),
9812
+ z7.object({ kind: z7.literal("file"), root: z7.string().optional() })
8339
9813
  ]);
8340
9814
  // src/checks/edge-resolve.ts
9815
+ import { execFileSync as execFileSync5 } from "node:child_process";
9816
+
9817
+ // src/lib/github-rate-limit.ts
8341
9818
  import { execFileSync as execFileSync4 } from "node:child_process";
9819
+ var GITHUB_RATE_LIMIT_WORDING = /api rate limit (?:already )?exceeded|secondary rate limit|rate limit exceeded/i;
9820
+ var SECONDARY_RATE_LIMIT_WORDING = /secondary rate limit/i;
9821
+ function isGithubRateLimitError(text) {
9822
+ return GITHUB_RATE_LIMIT_WORDING.test(text);
9823
+ }
9824
+ function rateLimitBudget(errorText) {
9825
+ return errorText.trimStart().startsWith("GraphQL:") ? "GraphQL" : "REST";
9826
+ }
9827
+ var defaultReader = () => execFileSync4("gh", ["api", "rate_limit"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
9828
+ function readRateLimitReset(budget, read = defaultReader) {
9829
+ let parsed;
9830
+ try {
9831
+ parsed = JSON.parse(read());
9832
+ } catch {
9833
+ return null;
9834
+ }
9835
+ const resources = parsed.resources;
9836
+ const entry = resources?.[budget === "GraphQL" ? "graphql" : "core"];
9837
+ if (!entry || typeof entry.reset !== "number" || !Number.isFinite(entry.reset) || entry.reset <= 0)
9838
+ return null;
9839
+ if (typeof entry.remaining === "number" && entry.remaining > 0)
9840
+ return null;
9841
+ return entry.reset;
9842
+ }
9843
+ function formatResetUtc(epochSeconds) {
9844
+ const d = new Date(epochSeconds * 1000);
9845
+ const hh = String(d.getUTCHours()).padStart(2, "0");
9846
+ const mm = String(d.getUTCMinutes()).padStart(2, "0");
9847
+ return `${hh}:${mm} UTC`;
9848
+ }
9849
+ function rateLimitMessage(errorText, read = defaultReader) {
9850
+ const budget = rateLimitBudget(errorText);
9851
+ const reset = SECONDARY_RATE_LIMIT_WORDING.test(errorText) ? null : readRateLimitReset(budget, read);
9852
+ const when = reset === null ? "resets in a few minutes" : `resets at ${formatResetUtc(reset)}`;
9853
+ return `GitHub rate limit (${budget}), ${when}`;
9854
+ }
9855
+ function execErrorText(err) {
9856
+ const e = err;
9857
+ const stderr = e?.stderr === undefined || e.stderr === null ? "" : String(e.stderr);
9858
+ const message = typeof e?.message === "string" ? e.message : "";
9859
+ return stderr.trim() !== "" ? `${stderr}
9860
+ ${message}` : message;
9861
+ }
9862
+
9863
+ // src/checks/edge-resolve.ts
8342
9864
  var DIRECT_ISSUE_REF = /#(\d+)/;
8343
9865
  var issueCache = new Map;
9866
+ var ISSUE_NOT_FOUND = /could not resolve to an issue/i;
8344
9867
  function fetchIssueState(num, repo) {
8345
9868
  const key = `${repo.owner}/${repo.repo}#${num}`;
8346
- if (issueCache.has(key))
8347
- return issueCache.get(key) ?? null;
8348
- let out = null;
9869
+ const cached = issueCache.get(key);
9870
+ if (cached)
9871
+ return cached;
9872
+ let out;
8349
9873
  try {
8350
- const raw = execFileSync4("gh", [
9874
+ const raw = execFileSync5("gh", [
8351
9875
  "issue",
8352
9876
  "view",
8353
9877
  String(num),
@@ -8356,9 +9880,9 @@ function fetchIssueState(num, repo) {
8356
9880
  "--json",
8357
9881
  "state,stateReason,closedByPullRequestsReferences"
8358
9882
  ], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
8359
- out = JSON.parse(raw);
8360
- } catch {
8361
- out = null;
9883
+ out = { json: JSON.parse(raw), readFailed: false };
9884
+ } catch (err) {
9885
+ out = { json: null, readFailed: !ISSUE_NOT_FOUND.test(execErrorText(err)) };
8362
9886
  }
8363
9887
  issueCache.set(key, out);
8364
9888
  return out;
@@ -8378,7 +9902,7 @@ var defaultResolveSiblingTranche = async (slug, repo) => {
8378
9902
  };
8379
9903
  };
8380
9904
  var siblingTrancheCache = new Map;
8381
- function edgeFromIssueJson(num, json) {
9905
+ function edgeFromIssueJson(num, json, readFailed = false) {
8382
9906
  if (json === null) {
8383
9907
  return {
8384
9908
  issue: num,
@@ -8387,7 +9911,8 @@ function edgeFromIssueJson(num, json) {
8387
9911
  issueState: null,
8388
9912
  stateReason: null,
8389
9913
  closedByActor: null,
8390
- resolved: true
9914
+ resolved: true,
9915
+ ...readFailed ? { readFailed: true } : {}
8391
9916
  };
8392
9917
  }
8393
9918
  const state = json.state === "CLOSED" ? "closed" : json.state === "OPEN" ? "open" : null;
@@ -8420,7 +9945,8 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
8420
9945
  const direct = id.match(DIRECT_ISSUE_REF);
8421
9946
  if (direct) {
8422
9947
  const num = Number(direct[1]);
8423
- return edgeFromIssueJson(num, fetchIssueState(num, repo));
9948
+ const read = fetchIssueState(num, repo);
9949
+ return edgeFromIssueJson(num, read.json, read.readFailed);
8424
9950
  }
8425
9951
  const qualified = splitSlugQualifiedEdge(id);
8426
9952
  if (qualified) {
@@ -8454,15 +9980,27 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
8454
9980
  resolved: false
8455
9981
  };
8456
9982
  }
9983
+ function dependsOnFactFromEdge(id, r) {
9984
+ return {
9985
+ id,
9986
+ issue: r.issue,
9987
+ merged: r.merged,
9988
+ resolved: r.resolved,
9989
+ issueState: r.issueState,
9990
+ stateReason: r.stateReason,
9991
+ closedByActor: r.closedByActor,
9992
+ ...r.readFailed ? { readFailed: true } : {}
9993
+ };
9994
+ }
8457
9995
 
8458
9996
  // src/lib/package-root.ts
8459
- import { existsSync as existsSync2 } from "node:fs";
8460
- import { dirname as dirname2, join as join2 } from "node:path";
9997
+ import { existsSync as existsSync3 } from "node:fs";
9998
+ import { dirname as dirname2, join as join3 } from "node:path";
8461
9999
  import { fileURLToPath as fileURLToPath2 } from "node:url";
8462
10000
  function packageRoot(moduleUrl) {
8463
10001
  let dir = dirname2(fileURLToPath2(moduleUrl));
8464
- while (!existsSync2(join2(dir, "package.json"))) {
8465
- if (existsSync2(join2(dir, ".git")))
10002
+ while (!existsSync3(join3(dir, "package.json"))) {
10003
+ if (existsSync3(join3(dir, ".git")))
8466
10004
  break;
8467
10005
  const parent = dirname2(dir);
8468
10006
  if (parent === dir)
@@ -8473,15 +10011,22 @@ function packageRoot(moduleUrl) {
8473
10011
  }
8474
10012
 
8475
10013
  // src/commands/doctrine.ts
8476
- import { execFileSync as execFileSync5 } from "node:child_process";
8477
- import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync3 } from "node:fs";
8478
- import { dirname as dirname3, join as join3, sep } from "node:path";
10014
+ import { execFileSync as execFileSync6 } from "node:child_process";
10015
+ import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync4 } from "node:fs";
10016
+ import { dirname as dirname3, join as join4, sep } from "node:path";
8479
10017
  import matter4 from "gray-matter";
8480
10018
 
8481
10019
  // ../../packages/aeg-core/src/docs/parse-doc.ts
8482
10020
  import matter2 from "gray-matter";
8483
10021
  // ../../packages/aeg-core/src/docs/surfaced-manifest.ts
8484
10022
  var NO_MODEL_BACKED_PATHS = new Set;
10023
+ // ../../packages/aeg-core/src/docs/published-prose.ts
10024
+ var ALLOWED_MECHANICS = rulesForGroup("published-prose")[0]?.exemptions ?? [];
10025
+ var PROSE_RULES = rulesForGroup("published-prose").map((rule) => ({
10026
+ id: rule.id,
10027
+ what: rule.message,
10028
+ pattern: rule.patterns.published
10029
+ }));
8485
10030
  // src/roles/contract.ts
8486
10031
  import matter3 from "gray-matter";
8487
10032
 
@@ -8492,7 +10037,7 @@ function resolveDoctrineRoot(pkg = packageRoot(import.meta.url), cwd = process.c
8492
10037
  }
8493
10038
  function gitToplevel(cwd) {
8494
10039
  try {
8495
- return execFileSync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
10040
+ return execFileSync6("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
8496
10041
  encoding: "utf8",
8497
10042
  stdio: ["ignore", "pipe", "pipe"]
8498
10043
  }).trim();
@@ -8503,25 +10048,25 @@ function gitToplevel(cwd) {
8503
10048
  function resolveDoctrineRootInfo(pkg = packageRoot(import.meta.url), cwd = process.cwd()) {
8504
10049
  const toplevel = gitToplevel(cwd);
8505
10050
  if (toplevel !== null) {
8506
- const treeRoot = join3(toplevel, "aeg-root");
8507
- if (existsSync3(join3(treeRoot, "roles")))
10051
+ const treeRoot = join4(toplevel, "aeg-root");
10052
+ if (existsSync4(join4(treeRoot, "roles")))
8508
10053
  return { root: treeRoot, source: "tree" };
8509
10054
  }
8510
10055
  const fromSource = !pkg.split(sep).includes("node_modules");
8511
- const bundleRoot = fromSource ? join3(dirname3(dirname3(pkg)), "aeg-root") : join3(pkg, "aeg-root");
10056
+ const bundleRoot = fromSource ? join4(dirname3(dirname3(pkg)), "aeg-root") : join4(pkg, "aeg-root");
8512
10057
  return hasDoctrineEntry(bundleRoot) ? { root: bundleRoot, source: "bundle" } : null;
8513
10058
  }
8514
10059
  function hasDoctrineEntry(root) {
8515
- return existsSync3(join3(root, ...ENTRY_SEGMENTS));
10060
+ return existsSync4(join4(root, ...ENTRY_SEGMENTS));
8516
10061
  }
8517
10062
 
8518
10063
  // src/lib/brief-assembly.ts
8519
10064
  var PACKAGE_ROOT = packageRoot(import.meta.url);
8520
- var PACKAGED_TEMPLATE_PATH = join4(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
8521
- var TEMPLATE_PATH = existsSync4(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join4(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
10065
+ var PACKAGED_TEMPLATE_PATH = join5(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
10066
+ var TEMPLATE_PATH = existsSync5(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join5(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
8522
10067
  function git(args) {
8523
10068
  try {
8524
- return execFileSync6("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
10069
+ return execFileSync7("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
8525
10070
  } catch {
8526
10071
  return "";
8527
10072
  }
@@ -8534,24 +10079,25 @@ function expandGlob(glob) {
8534
10079
  var DRAFT_ISSUE_SENTINEL = Number.MAX_SAFE_INTEGER;
8535
10080
 
8536
10081
  // src/checks/registry.ts
8537
- import { join as join5, relative, sep as sep2 } from "node:path";
10082
+ import { join as join6, relative, sep as sep2 } from "node:path";
8538
10083
  import { fileURLToPath as fileURLToPath3 } from "node:url";
8539
10084
  function resolveCheckBin(packageDir, moduleUrl) {
8540
10085
  const fromPackage = relative(packageDir, fileURLToPath3(moduleUrl));
8541
10086
  const bundled = fromPackage === "dist" || fromPackage.startsWith(`dist${sep2}`);
8542
- return bundled ? { dir: join5(packageDir, "dist", "checks", "bin"), ext: ".js" } : { dir: join5(packageDir, "src", "checks", "bin"), ext: ".ts" };
10087
+ return bundled ? { dir: join6(packageDir, "dist", "checks", "bin"), ext: ".js" } : { dir: join6(packageDir, "src", "checks", "bin"), ext: ".ts" };
8543
10088
  }
8544
10089
  var CHECK_BIN = resolveCheckBin(packageRoot(import.meta.url), import.meta.url);
8545
10090
  var BIN_DIR = CHECK_BIN.dir;
8546
10091
  var BIN_EXT = CHECK_BIN.ext;
8547
10092
  function bin(name) {
8548
- return join5(BIN_DIR, `${name}${BIN_EXT}`);
10093
+ return join6(BIN_DIR, `${name}${BIN_EXT}`);
8549
10094
  }
8550
10095
  var REGISTRY = [
8551
10096
  [
8552
10097
  {
8553
10098
  name: "brief-shape",
8554
10099
  validates: "body",
10100
+ requiresOpenPr: true,
8555
10101
  run: bin("check-brief-shape"),
8556
10102
  scope: "diff",
8557
10103
  timeoutMs: 15000,
@@ -8560,7 +10106,9 @@ var REGISTRY = [
8560
10106
  BRANCH: { optional: true },
8561
10107
  PR_NUMBER: { optional: true },
8562
10108
  GITHUB_TOKEN: { optional: true },
8563
- GH_TOKEN: { optional: true }
10109
+ GH_TOKEN: { optional: true },
10110
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10111
+ GITHUB_ACTIONS: { optional: true }
8564
10112
  }
8565
10113
  },
8566
10114
  0
@@ -8569,6 +10117,7 @@ var REGISTRY = [
8569
10117
  {
8570
10118
  name: "pr-report-density",
8571
10119
  validates: "body",
10120
+ requiresOpenPr: true,
8572
10121
  run: bin("check-pr-report-density"),
8573
10122
  scope: "diff",
8574
10123
  timeoutMs: 15000,
@@ -8594,7 +10143,9 @@ var REGISTRY = [
8594
10143
  PR_NUMBER: { optional: true },
8595
10144
  GITHUB_REPOSITORY: { optional: true },
8596
10145
  GITHUB_TOKEN: { optional: true },
8597
- GH_TOKEN: { optional: true }
10146
+ GH_TOKEN: { optional: true },
10147
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10148
+ GITHUB_ACTIONS: { optional: true }
8598
10149
  }
8599
10150
  },
8600
10151
  0
@@ -8618,6 +10169,7 @@ var REGISTRY = [
8618
10169
  {
8619
10170
  name: "pr-premise-reassert",
8620
10171
  validates: "body",
10172
+ requiresOpenPr: true,
8621
10173
  run: bin("check-pr-premise-reassert"),
8622
10174
  scope: "diff",
8623
10175
  timeoutMs: 15000,
@@ -8638,7 +10190,9 @@ var REGISTRY = [
8638
10190
  BRANCH: { optional: true },
8639
10191
  GITHUB_TOKEN: { optional: true },
8640
10192
  GH_TOKEN: { optional: true },
8641
- PREMISE_FILE: { optional: true }
10193
+ PREMISE_FILE: { optional: true },
10194
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10195
+ GITHUB_ACTIONS: { optional: true }
8642
10196
  }
8643
10197
  },
8644
10198
  0
@@ -8690,7 +10244,9 @@ var REGISTRY = [
8690
10244
  PR_BODY: { optional: true },
8691
10245
  PR_BODY_FILE: { optional: true },
8692
10246
  GITHUB_TOKEN: { optional: true },
8693
- GH_TOKEN: { optional: true }
10247
+ GH_TOKEN: { optional: true },
10248
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10249
+ GITHUB_ACTIONS: { optional: true }
8694
10250
  }
8695
10251
  },
8696
10252
  1
@@ -8706,7 +10262,13 @@ var REGISTRY = [
8706
10262
  principalOwed: true,
8707
10263
  env: {
8708
10264
  PR_BODY: { optional: true },
8709
- BRANCH: { optional: true }
10265
+ BRANCH: { optional: true },
10266
+ PULL_REQUEST_HEAD_SHA: { optional: true },
10267
+ GITHUB_REPOSITORY: { optional: true },
10268
+ GITHUB_TOKEN: { optional: true },
10269
+ GH_TOKEN: { optional: true },
10270
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10271
+ GITHUB_ACTIONS: { optional: true }
8710
10272
  }
8711
10273
  },
8712
10274
  1
@@ -8722,7 +10284,13 @@ var REGISTRY = [
8722
10284
  ownWorkflow: true,
8723
10285
  env: {
8724
10286
  PR_BODY: { optional: true },
8725
- BRANCH: { optional: true }
10287
+ BRANCH: { optional: true },
10288
+ PULL_REQUEST_HEAD_SHA: { optional: true },
10289
+ GITHUB_REPOSITORY: { optional: true },
10290
+ GITHUB_TOKEN: { optional: true },
10291
+ GH_TOKEN: { optional: true },
10292
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10293
+ GITHUB_ACTIONS: { optional: true }
8726
10294
  }
8727
10295
  },
8728
10296
  1
@@ -8741,7 +10309,9 @@ var REGISTRY = [
8741
10309
  PR_NUMBER: { optional: true },
8742
10310
  GITHUB_REPOSITORY: { optional: true },
8743
10311
  GITHUB_TOKEN: { optional: true },
8744
- GH_TOKEN: { optional: true }
10312
+ GH_TOKEN: { optional: true },
10313
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10314
+ GITHUB_ACTIONS: { optional: true }
8745
10315
  }
8746
10316
  },
8747
10317
  1
@@ -8781,7 +10351,9 @@ var REGISTRY = [
8781
10351
  PR_NUMBER: { optional: true },
8782
10352
  GITHUB_REPOSITORY: { optional: true },
8783
10353
  GITHUB_TOKEN: { optional: true },
8784
- GH_TOKEN: { optional: true }
10354
+ GH_TOKEN: { optional: true },
10355
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10356
+ GITHUB_ACTIONS: { optional: true }
8785
10357
  }
8786
10358
  },
8787
10359
  1
@@ -8834,12 +10406,15 @@ var REGISTRY = [
8834
10406
  {
8835
10407
  name: "doc-coverage-push",
8836
10408
  validates: "body",
10409
+ advisory: true,
8837
10410
  run: bin("check-doc-coverage-push"),
8838
10411
  scope: "diff",
8839
10412
  timeoutMs: 15000,
8840
10413
  env: {
8841
10414
  OVERRIDE_DOCS: { optional: true },
8842
10415
  BASE_SHA: { optional: true },
10416
+ GIT_INDEX_FILE: { optional: true },
10417
+ VINAYA_COMMIT_HOOK: { optional: true },
8843
10418
  PR_BODY: { optional: true },
8844
10419
  PR_BODY_FILE: { optional: true },
8845
10420
  PR_LABELS: { optional: true },
@@ -8851,21 +10426,6 @@ var REGISTRY = [
8851
10426
  },
8852
10427
  0
8853
10428
  ],
8854
- [
8855
- {
8856
- name: "issue-assignment",
8857
- run: bin("check-issue-assignment"),
8858
- scope: "full",
8859
- timeoutMs: 30000,
8860
- env: {
8861
- AEG_REPO: { optional: true },
8862
- BRANCH: { optional: true },
8863
- GITHUB_TOKEN: { optional: true },
8864
- GH_TOKEN: { optional: true }
8865
- }
8866
- },
8867
- 0
8868
- ],
8869
10429
  [
8870
10430
  {
8871
10431
  name: "evidence-fresh",
@@ -8879,7 +10439,9 @@ var REGISTRY = [
8879
10439
  PR_BODY: { optional: true },
8880
10440
  BASE_SHA: { optional: true },
8881
10441
  GITHUB_TOKEN: { optional: true },
8882
- GH_TOKEN: { optional: true }
10442
+ GH_TOKEN: { optional: true },
10443
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10444
+ GITHUB_ACTIONS: { optional: true }
8883
10445
  }
8884
10446
  },
8885
10447
  1
@@ -8890,7 +10452,11 @@ var REGISTRY = [
8890
10452
  run: bin("check-reader-resolvable-prose"),
8891
10453
  scope: "full",
8892
10454
  timeoutMs: 30000,
8893
- env: {},
10455
+ env: {
10456
+ BASE_SHA: { optional: true },
10457
+ GIT_INDEX_FILE: { optional: true },
10458
+ VINAYA_COMMIT_HOOK: { optional: true }
10459
+ },
8894
10460
  include: [
8895
10461
  "aeg-root/**/*.md",
8896
10462
  "apps/cli/src/**",
@@ -8908,7 +10474,11 @@ var REGISTRY = [
8908
10474
  run: bin("check-retired-vocabulary"),
8909
10475
  scope: "full",
8910
10476
  timeoutMs: 30000,
8911
- env: {},
10477
+ env: {
10478
+ BASE_SHA: { optional: true },
10479
+ GIT_INDEX_FILE: { optional: true },
10480
+ VINAYA_COMMIT_HOOK: { optional: true }
10481
+ },
8912
10482
  include: ["aeg-root/**/*.md"]
8913
10483
  },
8914
10484
  0
@@ -8916,10 +10486,15 @@ var REGISTRY = [
8916
10486
  [
8917
10487
  {
8918
10488
  name: "doctrine-portability",
10489
+ advisory: true,
8919
10490
  run: bin("check-doctrine-portability"),
8920
10491
  scope: "full",
8921
10492
  timeoutMs: 30000,
8922
- env: { BASE_SHA: { optional: true } },
10493
+ env: {
10494
+ BASE_SHA: { optional: true },
10495
+ GIT_INDEX_FILE: { optional: true },
10496
+ VINAYA_COMMIT_HOOK: { optional: true }
10497
+ },
8923
10498
  include: ["aeg-root/**/*.md"]
8924
10499
  },
8925
10500
  0
@@ -8952,7 +10527,11 @@ var REGISTRY = [
8952
10527
  run: bin("check-exec-bits"),
8953
10528
  scope: "diff",
8954
10529
  timeoutMs: 30000,
8955
- env: {}
10530
+ env: {
10531
+ BASE_SHA: { optional: true },
10532
+ GIT_INDEX_FILE: { optional: true },
10533
+ VINAYA_COMMIT_HOOK: { optional: true }
10534
+ }
8956
10535
  },
8957
10536
  0
8958
10537
  ],
@@ -8962,17 +10541,26 @@ var REGISTRY = [
8962
10541
  run: bin("check-ci-shard-coverage"),
8963
10542
  scope: "diff",
8964
10543
  timeoutMs: 15000,
8965
- env: {}
10544
+ env: {
10545
+ BASE_SHA: { optional: true },
10546
+ GIT_INDEX_FILE: { optional: true },
10547
+ VINAYA_COMMIT_HOOK: { optional: true }
10548
+ }
8966
10549
  },
8967
10550
  0
8968
10551
  ],
8969
10552
  [
8970
10553
  {
8971
10554
  name: "workspace-escape",
10555
+ advisory: true,
8972
10556
  run: bin("check-workspace-escape"),
8973
10557
  scope: "full",
8974
10558
  timeoutMs: 30000,
8975
- env: {},
10559
+ env: {
10560
+ BASE_SHA: { optional: true },
10561
+ GIT_INDEX_FILE: { optional: true },
10562
+ VINAYA_COMMIT_HOOK: { optional: true }
10563
+ },
8976
10564
  include: ["aeg-root/**/*.md"]
8977
10565
  },
8978
10566
  0
@@ -8983,17 +10571,23 @@ var REGISTRY = [
8983
10571
  run: bin("check-changeset-coverage"),
8984
10572
  scope: "diff",
8985
10573
  timeoutMs: 15000,
8986
- env: {}
10574
+ env: {
10575
+ BASE_SHA: { optional: true },
10576
+ GIT_INDEX_FILE: { optional: true },
10577
+ VINAYA_COMMIT_HOOK: { optional: true }
10578
+ }
8987
10579
  },
8988
10580
  0
8989
10581
  ],
8990
10582
  [
8991
10583
  {
8992
10584
  name: "quoted-command",
10585
+ advisory: true,
8993
10586
  run: bin("check-quoted-command"),
8994
- scope: "diff",
10587
+ scope: "full",
8995
10588
  timeoutMs: 15000,
8996
- env: {}
10589
+ env: {},
10590
+ include: ["aeg-root/**/*.md"]
8997
10591
  },
8998
10592
  0
8999
10593
  ],
@@ -9001,7 +10595,7 @@ var REGISTRY = [
9001
10595
  {
9002
10596
  name: "main-branch-refusal",
9003
10597
  run: bin("check-main-branch-refusal"),
9004
- scope: "full",
10598
+ scope: "diff",
9005
10599
  timeoutMs: 15000,
9006
10600
  env: { VINAYA_PUSH_REFS: { optional: true } }
9007
10601
  },
@@ -9068,18 +10662,6 @@ var REGISTRY = [
9068
10662
  },
9069
10663
  1
9070
10664
  ],
9071
- [
9072
- {
9073
- name: "issue-tranche-label",
9074
- run: bin("check-issue-tranche-label"),
9075
- validates: "issue",
9076
- scope: "full",
9077
- ownWorkflow: true,
9078
- timeoutMs: 15000,
9079
- env: { ISSUE_BODY: { optional: true }, ISSUE_LABELS: { optional: true } }
9080
- },
9081
- 1
9082
- ],
9083
10665
  [
9084
10666
  {
9085
10667
  name: "issue-milestone-attach",
@@ -9109,24 +10691,24 @@ import {
9109
10691
  appendFileSync,
9110
10692
  closeSync as closeSync4,
9111
10693
  constants as fsConstants4,
9112
- existsSync as existsSync7,
10694
+ existsSync as existsSync8,
9113
10695
  fstatSync as fstatSync3,
9114
10696
  mkdirSync as mkdirSync4,
9115
10697
  lstatSync as lstatSync2,
9116
10698
  openSync as openSync4,
9117
- readFileSync as readFileSync7,
10699
+ readFileSync as readFileSync8,
9118
10700
  renameSync as renameSync2,
9119
- writeFileSync as writeFileSync3,
10701
+ writeFileSync as writeFileSync4,
9120
10702
  writeSync as writeSync3
9121
10703
  } from "node:fs";
9122
10704
  import { hostname as osHostname, homedir as homedir3 } from "node:os";
9123
- import { dirname as dirname7, join as join8 } from "node:path";
10705
+ import { dirname as dirname7, join as join9 } from "node:path";
9124
10706
  import { promisify as promisify5 } from "node:util";
9125
10707
 
9126
10708
  // src/lib/run-paths.ts
9127
- import { execFileSync as execFileSync7 } from "node:child_process";
9128
- import { chmodSync, existsSync as existsSync5, realpathSync as realpathSync3 } from "node:fs";
9129
- import { dirname as dirname4, join as join6, resolve as resolvePath } from "node:path";
10709
+ import { execFileSync as execFileSync8 } from "node:child_process";
10710
+ import { chmodSync, existsSync as existsSync6, realpathSync as realpathSync3 } from "node:fs";
10711
+ import { dirname as dirname4, join as join7, resolve as resolvePath } from "node:path";
9130
10712
  var TASKS_EXECUTION_DIRNAME = "tasks-execution";
9131
10713
  var RUN_AREA_DIRNAMES = {
9132
10714
  control: CONTROL_AREA_DIRNAME,
@@ -9145,7 +10727,7 @@ function repoSegment(repo) {
9145
10727
  return `${repo.owner}-${repo.repo}`;
9146
10728
  }
9147
10729
  function defaultRuntimeDir(repo, home = GLOBAL_VINAYA_HOME) {
9148
- return join6(home, "runtime", repoSegment(repo));
10730
+ return join7(home, "runtime", repoSegment(repo));
9149
10731
  }
9150
10732
  function resolveRuntimeDir(input) {
9151
10733
  const local = resolveRuntimeDirSetting(input.localConfig);
@@ -9166,27 +10748,27 @@ function isInsideRepo(candidate, repoRoot) {
9166
10748
  return target === root || target.startsWith(`${root}/`);
9167
10749
  }
9168
10750
  function runPath(runtimeDir, scope, location) {
9169
- const dir = join6(runtimeDir, TASKS_EXECUTION_DIRNAME, scopeSegment(scope));
10751
+ const dir = join7(runtimeDir, TASKS_EXECUTION_DIRNAME, scopeSegment(scope));
9170
10752
  switch (location.area) {
9171
10753
  case "task":
9172
- return location.file ? join6(dir, location.file) : dir;
10754
+ return location.file ? join7(dir, location.file) : dir;
9173
10755
  case "control": {
9174
- const controlDir = join6(dir, RUN_AREA_DIRNAMES.control);
9175
- return location.file ? join6(controlDir, location.file) : controlDir;
10756
+ const controlDir = join7(dir, RUN_AREA_DIRNAMES.control);
10757
+ return location.file ? join7(controlDir, location.file) : controlDir;
9176
10758
  }
9177
10759
  case "rounds":
9178
- return join6(dir, RUN_AREA_DIRNAMES.rounds);
10760
+ return join7(dir, RUN_AREA_DIRNAMES.rounds);
9179
10761
  case "round": {
9180
- const roundDir = join6(dir, RUN_AREA_DIRNAMES.rounds, String(location.round));
9181
- return location.file ? join6(roundDir, location.file) : roundDir;
10762
+ const roundDir = join7(dir, RUN_AREA_DIRNAMES.rounds, String(location.round));
10763
+ return location.file ? join7(roundDir, location.file) : roundDir;
9182
10764
  }
9183
10765
  case "developer": {
9184
- const developerDir = join6(dir, RUN_AREA_DIRNAMES.rounds, String(location.round), "developer");
9185
- return location.file ? join6(developerDir, location.file) : developerDir;
10766
+ const developerDir = join7(dir, RUN_AREA_DIRNAMES.rounds, String(location.round), "developer");
10767
+ return location.file ? join7(developerDir, location.file) : developerDir;
9186
10768
  }
9187
10769
  default: {
9188
- const areaDir = join6(dir, RUN_AREA_DIRNAMES[location.area]);
9189
- return location.file ? join6(areaDir, location.file) : areaDir;
10770
+ const areaDir = join7(dir, RUN_AREA_DIRNAMES[location.area]);
10771
+ return location.file ? join7(areaDir, location.file) : areaDir;
9190
10772
  }
9191
10773
  }
9192
10774
  }
@@ -9255,7 +10837,7 @@ function repoRootSync(start = process.cwd()) {
9255
10837
  return null;
9256
10838
  }
9257
10839
  for (;; ) {
9258
- if (existsSync5(join6(dir, ".git")))
10840
+ if (existsSync6(join7(dir, ".git")))
9259
10841
  return dir;
9260
10842
  const parent = dirname4(dir);
9261
10843
  if (parent === dir)
@@ -9272,7 +10854,7 @@ function resolveRepoSync() {
9272
10854
  }
9273
10855
  let url;
9274
10856
  try {
9275
- url = execFileSync7("git", ["remote", "get-url", "origin"], {
10857
+ url = execFileSync8("git", ["remote", "get-url", "origin"], {
9276
10858
  encoding: "utf-8",
9277
10859
  stdio: ["ignore", "pipe", "pipe"]
9278
10860
  }).trim();
@@ -9299,11 +10881,11 @@ function runtimeDirForThisRepo() {
9299
10881
  import {
9300
10882
  closeSync as closeSync2,
9301
10883
  constants as fsConstants2,
9302
- existsSync as existsSync6,
10884
+ existsSync as existsSync7,
9303
10885
  fstatSync as fstatSync2,
9304
10886
  mkdirSync as mkdirSync2,
9305
10887
  openSync as openSync2,
9306
- readFileSync as readFileSync5,
10888
+ readFileSync as readFileSync6,
9307
10889
  readSync,
9308
10890
  statSync,
9309
10891
  writeSync
@@ -9340,17 +10922,17 @@ import {
9340
10922
  mkdirSync as mkdirSync3,
9341
10923
  openSync as openSync3,
9342
10924
  linkSync,
9343
- readFileSync as readFileSync6,
10925
+ readFileSync as readFileSync7,
9344
10926
  renameSync,
9345
10927
  statSync as statSync2,
9346
10928
  unlinkSync,
9347
10929
  utimesSync,
9348
- writeFileSync as writeFileSync2,
10930
+ writeFileSync as writeFileSync3,
9349
10931
  writeSync as writeSync2
9350
10932
  } from "node:fs";
9351
10933
  import { randomUUID } from "node:crypto";
9352
10934
  import { homedir as homedir2 } from "node:os";
9353
- import { dirname as dirname6, join as join7 } from "node:path";
10935
+ import { dirname as dirname6, join as join8 } from "node:path";
9354
10936
  var MAX_WEBHOOK_BODY_BYTES = 5 * 1024 * 1024;
9355
10937
  var WEBHOOK_FETCH_TIMEOUT_MS = 30000;
9356
10938
  var SAFE_PATH_SEGMENT2 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
@@ -9431,7 +11013,7 @@ function acquireDrainLock(lockPath) {
9431
11013
  function renewDrainLock(lockPath, token) {
9432
11014
  let holder;
9433
11015
  try {
9434
- holder = readFileSync6(lockPath, "utf8").trim();
11016
+ holder = readFileSync7(lockPath, "utf8").trim();
9435
11017
  } catch (err) {
9436
11018
  if (!isEnoent(err))
9437
11019
  throw err;
@@ -9451,7 +11033,7 @@ function renewDrainLock(lockPath, token) {
9451
11033
  }
9452
11034
  function releaseDrainLock(lockPath, token) {
9453
11035
  try {
9454
- const holder = readFileSync6(lockPath, "utf8").trim();
11036
+ const holder = readFileSync7(lockPath, "utf8").trim();
9455
11037
  if (holder !== token)
9456
11038
  return;
9457
11039
  unlinkSync(lockPath);
@@ -9501,8 +11083,8 @@ function queueLines(buf) {
9501
11083
  return lines;
9502
11084
  }
9503
11085
  function removeQueueHead(path, cut) {
9504
- const remaining = readFileSync6(path);
9505
- writeFileSync2(path, remaining.subarray(Math.min(cut, remaining.byteLength)));
11086
+ const remaining = readFileSync7(path);
11087
+ writeFileSync3(path, remaining.subarray(Math.min(cut, remaining.byteLength)));
9506
11088
  }
9507
11089
  function queueBucketSize(path) {
9508
11090
  let lstat;
@@ -9522,7 +11104,7 @@ function queueBucketSize(path) {
9522
11104
  function readQueueFile(path) {
9523
11105
  if (queueBucketSize(path) === null)
9524
11106
  return null;
9525
- return readFileSync6(path);
11107
+ return readFileSync7(path);
9526
11108
  }
9527
11109
  function rejectLine(rejectedPath, reason, status, identity, raw) {
9528
11110
  const record = JSON.stringify({
@@ -9637,7 +11219,7 @@ async function drainRenamedAside(args, livePath, source) {
9637
11219
  async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeoutMs = WEBHOOK_FETCH_TIMEOUT_MS) {
9638
11220
  const resolved = await resolveRepo();
9639
11221
  const repo = resolved && isSafeRepoSegment2(resolved.owner) && isSafeRepoSegment2(resolved.repo) ? resolved : null;
9640
- const outboxRoot = () => join7(GLOBAL_VINAYA_HOME, "outbox");
11222
+ const outboxRoot = () => join8(GLOBAL_VINAYA_HOME, "outbox");
9641
11223
  const path = outboxPathFor({ outboxRoot }, repo, outboxTask);
9642
11224
  const lockPath = `${path}.flush-lock`;
9643
11225
  const lockToken = acquireDrainLock(lockPath);
@@ -9774,7 +11356,7 @@ async function defaultResolveLogDestination(repo, env) {
9774
11356
  trustAnchorConfig: unattended ? await processTrustAnchor(repoRoot) : null,
9775
11357
  unattended,
9776
11358
  env,
9777
- defaultFolder: join8(await runtimeDirForRepoAsync(repo), "logs"),
11359
+ defaultFolder: join9(await runtimeDirForRepoAsync(repo), "logs"),
9778
11360
  repoRoot
9779
11361
  });
9780
11362
  }
@@ -9790,7 +11372,7 @@ function unresolvedLogDestination(env) {
9790
11372
  const unattended = isUnattendedProcess(process.env);
9791
11373
  const repoRoot = repoRootSync();
9792
11374
  const runtimeDir = process.env[RUNTIME_DIR_ENV_KEY] || resolveRuntimeDir({ repo: null, localConfig, trustAnchorConfig: null, unattended, repoRoot });
9793
- const defaultFolder = join8(runtimeDir, "logs");
11375
+ const defaultFolder = join9(runtimeDir, "logs");
9794
11376
  const resolved = resolveLogDestinationFrom({
9795
11377
  localConfig,
9796
11378
  trustAnchorConfig: null,
@@ -9803,7 +11385,7 @@ function unresolvedLogDestination(env) {
9803
11385
  }
9804
11386
  function folderFallbackStatePath(repo, stateRoot = GLOBAL_VINAYA_HOME) {
9805
11387
  const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
9806
- return join8(stateRoot, "fallback", `${dirName}.json`);
11388
+ return join9(stateRoot, "fallback", `${dirName}.json`);
9807
11389
  }
9808
11390
  function recordFolderFallback(repo, issue, reason, now, runtimeDir, stateRoot = GLOBAL_VINAYA_HOME) {
9809
11391
  const message = describeFolderFallback(reason);
@@ -9819,7 +11401,7 @@ function recordFolderFallback(repo, issue, reason, now, runtimeDir, stateRoot =
9819
11401
  };
9820
11402
  const path = folderFallbackStatePath(repo, stateRoot);
9821
11403
  mkdirSync4(dirname7(path), { recursive: true, mode: 448 });
9822
- writeFileSync3(path, `${JSON.stringify(record)}
11404
+ writeFileSync4(path, `${JSON.stringify(record)}
9823
11405
  `, { mode: 384 });
9824
11406
  } catch {}
9825
11407
  }
@@ -9834,7 +11416,7 @@ async function resolveDoctrine(cwd, vinayaVersion) {
9834
11416
  } catch (err) {
9835
11417
  return isEnoent2(err) ? "unknown" : vinayaVersion;
9836
11418
  }
9837
- if (!existsSync7(join8(toplevel, "aeg-root", "roles")))
11419
+ if (!existsSync8(join9(toplevel, "aeg-root", "roles")))
9838
11420
  return vinayaVersion;
9839
11421
  try {
9840
11422
  const sha = (await execFileAsync5("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], { encoding: "utf8" })).stdout.trim();
@@ -9935,7 +11517,7 @@ async function resolveBranchIssue(cwd, env = process.env, repo = null) {
9935
11517
  }
9936
11518
  function readVinayaVersion() {
9937
11519
  try {
9938
- const pkg = JSON.parse(readFileSync7(join8(packageRoot(import.meta.url), "package.json"), "utf8"));
11520
+ const pkg = JSON.parse(readFileSync8(join9(packageRoot(import.meta.url), "package.json"), "utf8"));
9939
11521
  return pkg.version ?? "unknown";
9940
11522
  } catch {
9941
11523
  return "unknown";
@@ -9953,7 +11535,7 @@ function safeRepoSlug(repo) {
9953
11535
  function outboxPathFor(deps, repo, issue) {
9954
11536
  const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
9955
11537
  const fileName = `${issue ?? "none"}.ndjson`;
9956
- return join8(deps.outboxRoot(), dirName, fileName);
11538
+ return join9(deps.outboxRoot(), dirName, fileName);
9957
11539
  }
9958
11540
  function hostFromEnv(env) {
9959
11541
  if (env.GITHUB_ACTIONS)
@@ -10008,7 +11590,7 @@ async function resolveHeadSha(cwd) {
10008
11590
  }
10009
11591
  function defaultDeps() {
10010
11592
  return {
10011
- outboxRoot: () => join8(GLOBAL_VINAYA_HOME, "outbox"),
11593
+ outboxRoot: () => join9(GLOBAL_VINAYA_HOME, "outbox"),
10012
11594
  home: () => homedir3(),
10013
11595
  hostname: () => osHostname(),
10014
11596
  cwd: () => process.cwd(),
@@ -10053,7 +11635,7 @@ function appendHardenedLine(path, line) {
10053
11635
  function reportRotationOverflow(backupPath, warn) {
10054
11636
  let raw;
10055
11637
  try {
10056
- raw = readFileSync7(backupPath, "utf8");
11638
+ raw = readFileSync8(backupPath, "utf8");
10057
11639
  } catch {
10058
11640
  return;
10059
11641
  }
@@ -10266,12 +11848,14 @@ function createLogSink(overrides = {}) {
10266
11848
  branchIssue,
10267
11849
  eventId: randomUUID2(),
10268
11850
  processId,
11851
+ revision: headSha,
11852
+ provenance: deps.provenance,
10269
11853
  inputVersions: deps.inputVersions()
10270
11854
  });
10271
11855
  const header = headSha === null ? built : { ...built, subject: { ...built.subject, sha: headSha } };
10272
11856
  if (destination.kind === "folder" && destination.fallbackReason && !folderFallbackRecorded) {
10273
11857
  folderFallbackRecorded = true;
10274
- recordFolderFallback(repo, header.subject.issue, destination.fallbackReason, call.now, dirname7(destination.folder), join8(deps.home(), ".vinaya"));
11858
+ recordFolderFallback(repo, header.subject.issue, destination.fallbackReason, call.now, dirname7(destination.folder), join9(deps.home(), ".vinaya"));
10275
11859
  }
10276
11860
  const full = { ...e, ...header };
10277
11861
  const parsed = LogEventSchema.safeParse(full);
@@ -10356,13 +11940,6 @@ function createLogSink(overrides = {}) {
10356
11940
  }
10357
11941
  var defaultSink = createLogSink();
10358
11942
 
10359
- // src/checks/contract.ts
10360
- var CHECK_SCHEMA_VERSION = 1;
10361
- function emitCheckError(error) {
10362
- process.stderr.write(`${JSON.stringify(error)}
10363
- `);
10364
- }
10365
-
10366
11943
  // src/checks/runner.ts
10367
11944
  var activeChecks = new Map;
10368
11945
 
@@ -10403,20 +11980,40 @@ function parseChangedLineRanges(diffOutput) {
10403
11980
 
10404
11981
  // src/lib/diff-evidence.ts
10405
11982
  function fileDiffAgainst(ref, path) {
10406
- let out;
11983
+ let committed;
10407
11984
  try {
10408
- out = execFileSync8("git", ["diff", `${ref}...HEAD`, "--", path], {
11985
+ committed = execFileSync9("git", ["diff", `${ref}...HEAD`, "--", path], {
10409
11986
  encoding: "utf8",
10410
11987
  stdio: ["ignore", "pipe", "pipe"]
10411
11988
  }).trim();
10412
11989
  } catch {
10413
11990
  return null;
10414
11991
  }
11992
+ const staged = stagedDiff(["--", path]);
11993
+ if (staged === null)
11994
+ return null;
11995
+ const out = [committed, staged].filter(Boolean).join(`
11996
+ `);
10415
11997
  return out === "" ? null : out;
10416
11998
  }
11999
+ function readsStagedDiff() {
12000
+ return process.env.VINAYA_COMMIT_HOOK === "1" && Boolean(process.env.GIT_INDEX_FILE);
12001
+ }
12002
+ function stagedDiff(args) {
12003
+ if (!readsStagedDiff())
12004
+ return "";
12005
+ try {
12006
+ return execFileSync9("git", ["diff", "--cached", ...args], {
12007
+ encoding: "utf8",
12008
+ stdio: ["ignore", "pipe", "pipe"]
12009
+ }).trim();
12010
+ } catch {
12011
+ return null;
12012
+ }
12013
+ }
10417
12014
  function revParse(ref) {
10418
12015
  try {
10419
- return execFileSync8("git", ["rev-parse", "--verify", ref], {
12016
+ return execFileSync9("git", ["rev-parse", "--verify", ref], {
10420
12017
  encoding: "utf8",
10421
12018
  stdio: ["ignore", "pipe", "pipe"]
10422
12019
  }).trim();
@@ -10426,7 +12023,7 @@ function revParse(ref) {
10426
12023
  }
10427
12024
  function repoRoot() {
10428
12025
  try {
10429
- return execFileSync8("git", ["rev-parse", "--show-toplevel"], {
12026
+ return execFileSync9("git", ["rev-parse", "--show-toplevel"], {
10430
12027
  encoding: "utf8",
10431
12028
  stdio: ["ignore", "pipe", "pipe"]
10432
12029
  }).trim();
@@ -10437,7 +12034,7 @@ function repoRoot() {
10437
12034
  function changedFiles(base) {
10438
12035
  let out;
10439
12036
  try {
10440
- out = execFileSync8("git", ["diff", "--name-only", `${base}...HEAD`], {
12037
+ out = execFileSync9("git", ["diff", "--name-only", `${base}...HEAD`], {
10441
12038
  encoding: "utf8",
10442
12039
  stdio: ["ignore", "pipe", "pipe"]
10443
12040
  }).trim();
@@ -10447,6 +12044,13 @@ function changedFiles(base) {
10447
12044
  return out === "" ? [] : out.split(`
10448
12045
  `).map((s) => s.trim()).filter(Boolean);
10449
12046
  }
12047
+ function stagedChangedFiles() {
12048
+ const out = stagedDiff(["--name-only"]);
12049
+ if (out === null)
12050
+ return null;
12051
+ return out === "" ? [] : out.split(`
12052
+ `).map((s) => s.trim()).filter(Boolean);
12053
+ }
10450
12054
  function resolveChangedFiles(base = process.env.BASE_SHA || "origin/main") {
10451
12055
  return resolveDiff(base)?.files ?? null;
10452
12056
  }
@@ -10462,7 +12066,30 @@ function resolveDiff(base = process.env.BASE_SHA || "origin/main") {
10462
12066
  const relPaths = changedFiles(ref);
10463
12067
  if (relPaths === null)
10464
12068
  continue;
10465
- return { base: ref, root, files: relPaths.map((p) => join9(root, p)) };
12069
+ const stagedPaths = stagedChangedFiles();
12070
+ if (stagedPaths === null)
12071
+ return null;
12072
+ const paths = [...new Set([...relPaths, ...stagedPaths])];
12073
+ return { base: ref, root, files: paths.map((p) => join10(root, p)) };
12074
+ }
12075
+ return null;
12076
+ }
12077
+ function resolveAddedFiles(base = process.env.BASE_SHA || "origin/main") {
12078
+ if (repoRoot() === null)
12079
+ return null;
12080
+ const head = revParse("HEAD");
12081
+ for (const ref of new Set([base, "origin/main", "main"])) {
12082
+ const resolved = revParse(ref);
12083
+ if (resolved === null || resolved === head)
12084
+ continue;
12085
+ try {
12086
+ const out = execFileSync9("git", ["diff", "--name-only", "--diff-filter=A", `${ref}...HEAD`], {
12087
+ encoding: "utf8",
12088
+ stdio: ["ignore", "pipe", "pipe"]
12089
+ }).trim();
12090
+ return out === "" ? [] : out.split(`
12091
+ `).map((p) => p.trim()).filter(Boolean);
12092
+ } catch {}
10466
12093
  }
10467
12094
  return null;
10468
12095
  }
@@ -10563,7 +12190,7 @@ function evaluateChangesetCoverage(fixedGroup, changedFiles, isReleaseBranch) {
10563
12190
  var CHECK_NAME = "changeset-coverage";
10564
12191
  function git2(args) {
10565
12192
  try {
10566
- return execFileSync9("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
12193
+ return execFileSync10("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
10567
12194
  } catch {
10568
12195
  return "";
10569
12196
  }
@@ -10580,7 +12207,7 @@ function toPosix(p) {
10580
12207
  }
10581
12208
  function readPackageJson(path) {
10582
12209
  try {
10583
- const parsed = JSON.parse(readFileSync8(path, "utf8"));
12210
+ const parsed = JSON.parse(readFileSync9(path, "utf8"));
10584
12211
  return parsed && typeof parsed === "object" ? parsed : null;
10585
12212
  } catch {
10586
12213
  return null;
@@ -10601,18 +12228,18 @@ function childDirs(absoluteDir) {
10601
12228
  function candidateMemberDirs(root, pattern) {
10602
12229
  if (pattern.endsWith("/*")) {
10603
12230
  const prefix = pattern.slice(0, -2);
10604
- return childDirs(join10(root, prefix)).map((name) => `${prefix}/${name}`);
12231
+ return childDirs(join11(root, prefix)).map((name) => `${prefix}/${name}`);
10605
12232
  }
10606
12233
  if (!pattern.includes("*"))
10607
12234
  return [pattern];
10608
12235
  return [];
10609
12236
  }
10610
12237
  function resolveWorkspaceMembers(root) {
10611
- const rootPkg = readPackageJson(join10(root, "package.json"));
12238
+ const rootPkg = readPackageJson(join11(root, "package.json"));
10612
12239
  const members = new Map;
10613
12240
  for (const pattern of workspacePatterns(rootPkg)) {
10614
12241
  for (const dir of candidateMemberDirs(root, pattern)) {
10615
- const pkg = readPackageJson(join10(root, dir, "package.json"));
12242
+ const pkg = readPackageJson(join11(root, dir, "package.json"));
10616
12243
  const name = pkg?.name;
10617
12244
  const files = pkg?.files;
10618
12245
  if (typeof name !== "string" || !Array.isArray(files))
@@ -10623,7 +12250,7 @@ function resolveWorkspaceMembers(root) {
10623
12250
  return members;
10624
12251
  }
10625
12252
  function fixedGroupNames(root) {
10626
- const pkg = readPackageJson(join10(root, ".changeset", "config.json"));
12253
+ const pkg = readPackageJson(join11(root, ".changeset", "config.json"));
10627
12254
  const fixed = pkg?.fixed;
10628
12255
  if (!Array.isArray(fixed))
10629
12256
  return [];