@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,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/checks/bin/check-exec-bits.ts
4
- import { execFileSync as execFileSync9 } from "node:child_process";
5
- import { readFileSync as readFileSync8 } from "node:fs";
4
+ import { execFileSync as execFileSync10 } from "node:child_process";
5
+ import { readFileSync as readFileSync9 } from "node:fs";
6
6
 
7
7
  // src/checks/contract.ts
8
8
  var CHECK_SCHEMA_VERSION = 1;
@@ -12,8 +12,8 @@ function emitCheckError(error) {
12
12
  }
13
13
 
14
14
  // src/lib/diff-evidence.ts
15
- import { execFileSync as execFileSync8 } from "node:child_process";
16
- import { join as join9, relative as relative2, resolve as resolve2 } from "node:path";
15
+ import { execFileSync as execFileSync9 } from "node:child_process";
16
+ import { join as join10, relative as relative2, resolve as resolve2 } from "node:path";
17
17
 
18
18
  // ../../packages/aeg-core/src/entry-point.ts
19
19
  import { realpathSync } from "node:fs";
@@ -54,7 +54,6 @@ var GATE_AUDIENCE = {
54
54
  };
55
55
  var NON_GATE_BINS = [
56
56
  "archive-task",
57
- "assign-task-issue",
58
57
  "dead-branch-audit",
59
58
  "eval-agent-compliance",
60
59
  "open-issue",
@@ -317,6 +316,25 @@ async function runAsync(args) {
317
316
  function ghApiGet(path) {
318
317
  return JSON.parse(run(["api", path]));
319
318
  }
319
+ var MAX_PER_PAGE = 100;
320
+ var MAX_PAGES = 100;
321
+ async function ghApiGetAllPagesAsync(pathWithoutPage, opts) {
322
+ const [base = pathWithoutPage, query = ""] = pathWithoutPage.split("?");
323
+ const params = new URLSearchParams(query);
324
+ params.set("per_page", String(MAX_PER_PAGE));
325
+ const all = [];
326
+ for (let page = 1;page <= MAX_PAGES; page++) {
327
+ params.set("page", String(page));
328
+ const args = ["api", `${base}?${params.toString()}`];
329
+ if (opts?.jq)
330
+ args.push("-q", opts.jq);
331
+ const batch = JSON.parse(await runAsync(args));
332
+ all.push(...batch);
333
+ if (batch.length < MAX_PER_PAGE)
334
+ return all;
335
+ }
336
+ throw new Error(`ghApiGetAllPagesAsync: "${pathWithoutPage}" did not terminate within ${MAX_PAGES} pages (${MAX_PAGES * MAX_PER_PAGE} items) — refusing to keep walking.`);
337
+ }
320
338
  function issueListByLabelArgs(owner, repo, label) {
321
339
  return [
322
340
  "issue",
@@ -728,6 +746,10 @@ function intentGoalForSlug(description, slug) {
728
746
  function matchesLegacyMilestone(milestones, slug) {
729
747
  return milestones.find((m) => m.title === slug) ?? null;
730
748
  }
749
+ var TRANCHE_SLUG_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*-v\d+$/;
750
+ function slugShapedTitles(milestones) {
751
+ return milestones.map((m) => m.title).filter((t) => TRANCHE_SLUG_SHAPE.test(t));
752
+ }
731
753
  function factsFromLegacyMilestone(milestone) {
732
754
  return {
733
755
  goal: milestone.description ?? "",
@@ -761,6 +783,90 @@ function findMilestoneForSlug(owner, repo, slug) {
761
783
  return resolveLegacyFacts(legacy, issues);
762
784
  return { goal: goalFromMilestones(milestones, slug), lifecycle: lifecycleFromIssues(issues) };
763
785
  }
786
+ function trancheSlugsFromLabels(labels) {
787
+ const slugs = [];
788
+ for (const l of labels) {
789
+ const slug = trancheSlugOf(l.name);
790
+ if (slug !== null)
791
+ slugs.push(slug);
792
+ }
793
+ return slugs;
794
+ }
795
+ async function indexTrancheMilestonesAsync(owner, repo) {
796
+ const [milestones, labels] = await Promise.all([
797
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`),
798
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`)
799
+ ]);
800
+ const active = [];
801
+ const archived = [];
802
+ const facts = new Map;
803
+ const legacySlugs = new Set(slugShapedTitles(milestones));
804
+ const legacyMilestoneBySlug = new Map(milestones.filter((m) => legacySlugs.has(m.title)).map((m) => [m.title, m]));
805
+ const newPathSlugs = trancheSlugsFromLabels(labels).filter((slug) => !legacySlugs.has(slug));
806
+ const uniqueNewPathSlugs = [...new Set(newPathSlugs)];
807
+ const uniqueLegacySlugs = [...legacySlugs];
808
+ const [legacyIssuesBySlug, newPathIssuesBySlug] = await Promise.all([
809
+ Promise.all(uniqueLegacySlugs.map((slug) => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug)))),
810
+ Promise.all(uniqueNewPathSlugs.map((slug) => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))))
811
+ ]);
812
+ uniqueLegacySlugs.forEach((slug, i) => {
813
+ const m = legacyMilestoneBySlug.get(slug);
814
+ if (!m)
815
+ return;
816
+ const ref = { slug, goal: m.description ?? "" };
817
+ const f = resolveLegacyFacts(m, legacyIssuesBySlug[i] ?? []);
818
+ if (f.lifecycle === "complete")
819
+ archived.push(ref);
820
+ else if (f.lifecycle === "active")
821
+ active.push(ref);
822
+ facts.set(slug, f);
823
+ });
824
+ uniqueNewPathSlugs.forEach((slug, i) => {
825
+ const issues = newPathIssuesBySlug[i] ?? [];
826
+ const lifecycle = lifecycleFromIssues(issues);
827
+ const goal = goalFromMilestones(milestones, slug);
828
+ const f = { goal, lifecycle };
829
+ facts.set(slug, f);
830
+ if (lifecycle === "active")
831
+ active.push({ slug, goal });
832
+ else if (lifecycle === "complete")
833
+ archived.push({ slug, goal });
834
+ });
835
+ return { active, archived, facts, legacySlugs };
836
+ }
837
+ async function indexTrancheMilestonesForSlugAsync(owner, repo, slug) {
838
+ const [milestones, labels, issues] = await Promise.all([
839
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`),
840
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`),
841
+ ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))
842
+ ]);
843
+ const active = [];
844
+ const archived = [];
845
+ const facts = new Map;
846
+ const legacySlugs = new Set;
847
+ const legacyMilestone = slugShapedTitles(milestones).includes(slug) ? matchesLegacyMilestone(milestones, slug) : null;
848
+ if (legacyMilestone) {
849
+ legacySlugs.add(slug);
850
+ const ref = { slug, goal: legacyMilestone.description ?? "" };
851
+ const f = resolveLegacyFacts(legacyMilestone, issues);
852
+ if (f.lifecycle === "complete")
853
+ archived.push(ref);
854
+ else if (f.lifecycle === "active")
855
+ active.push(ref);
856
+ facts.set(slug, f);
857
+ } else if (trancheSlugsFromLabels(labels).includes(slug)) {
858
+ const lifecycle = lifecycleFromIssues(issues);
859
+ const goal = goalFromMilestones(milestones, slug);
860
+ facts.set(slug, { goal, lifecycle });
861
+ if (lifecycle === "active")
862
+ active.push({ slug, goal });
863
+ else if (lifecycle === "complete")
864
+ archived.push({ slug, goal });
865
+ }
866
+ const openLegacyTitles = new Set(slugShapedTitles(milestones.filter((m) => m.state === "open")));
867
+ const otherOpenLegacySlugs = [...openLegacyTitles].filter((t) => t !== slug);
868
+ return { active, archived, facts, legacySlugs, otherOpenLegacySlugs };
869
+ }
764
870
 
765
871
  // ../../packages/aeg-forge-state/src/derive-from-forge.ts
766
872
  function trancheFromIssues(slug, issues, known) {
@@ -1421,6 +1527,125 @@ var graphql2 = withDefaults3(request, {
1421
1527
  method: "POST",
1422
1528
  url: "/graphql"
1423
1529
  });
1530
+
1531
+ // ../../packages/aeg-forge-state/src/fetch-provenance.ts
1532
+ var PROVENANCE_PATTERN = /^###\s+AEG provenance\b/im;
1533
+ function provenanceMatchesIssue(text, issueNum) {
1534
+ if (!PROVENANCE_PATTERN.test(text))
1535
+ return false;
1536
+ const m = text.match(/^-\s*Issue:\s*#(\d+)/im);
1537
+ return m !== null && Number(m[1]) === issueNum;
1538
+ }
1539
+ function isPrCloser(closer) {
1540
+ return closer !== null && typeof closer.number === "number";
1541
+ }
1542
+ async function fetchProvenanceViaCrossReferences(issueNums, owner, repo, token) {
1543
+ const result = new Map;
1544
+ if (issueNums.length === 0)
1545
+ return result;
1546
+ const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
1547
+ const perIssue = issueNums.map((n) => `
1548
+ i_${n}: issue(number: ${n}) {
1549
+ timelineItems(first: 50, itemTypes: [CROSS_REFERENCED_EVENT]) {
1550
+ nodes {
1551
+ ... on CrossReferencedEvent {
1552
+ source {
1553
+ ... on PullRequest {
1554
+ number
1555
+ body
1556
+ comments(first: 50) { nodes { body } }
1557
+ }
1558
+ }
1559
+ }
1560
+ }
1561
+ }
1562
+ }`).join("");
1563
+ const query = `query ProvenanceCrossRef($owner: String!, $repo: String!) {
1564
+ repository(owner: $owner, name: $repo) {${perIssue}
1565
+ }
1566
+ }`;
1567
+ let response;
1568
+ try {
1569
+ response = await client(query, { owner, repo });
1570
+ } catch {
1571
+ return result;
1572
+ }
1573
+ if (!response.repository)
1574
+ return result;
1575
+ for (const n of issueNums) {
1576
+ const raw = response.repository[`i_${n}`];
1577
+ const nodes = raw?.timelineItems?.nodes ?? [];
1578
+ const found = nodes.some(({ source }) => {
1579
+ if (!source || typeof source.number !== "number")
1580
+ return false;
1581
+ const pr = source;
1582
+ if (provenanceMatchesIssue(pr.body ?? "", n))
1583
+ return true;
1584
+ return pr.comments.nodes.some((c) => provenanceMatchesIssue(c.body, n));
1585
+ });
1586
+ result.set(n, found);
1587
+ }
1588
+ return result;
1589
+ }
1590
+ async function fetchProvenance(issueNums, owner, repo, token) {
1591
+ const result = new Map;
1592
+ if (issueNums.length === 0)
1593
+ return result;
1594
+ const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
1595
+ const perIssue = issueNums.map((n) => `
1596
+ i_${n}: issue(number: ${n}) {
1597
+ timelineItems(last: 1, itemTypes: [CLOSED_EVENT]) {
1598
+ nodes {
1599
+ ... on ClosedEvent {
1600
+ closer {
1601
+ ... on PullRequest {
1602
+ number
1603
+ body
1604
+ comments(first: 50) {
1605
+ nodes { body }
1606
+ }
1607
+ }
1608
+ }
1609
+ }
1610
+ }
1611
+ }
1612
+ }`).join("");
1613
+ const query = `query Provenance($owner: String!, $repo: String!) {
1614
+ repository(owner: $owner, name: $repo) {${perIssue}
1615
+ }
1616
+ }`;
1617
+ let response;
1618
+ try {
1619
+ response = await client(query, { owner, repo });
1620
+ } catch {
1621
+ return result;
1622
+ }
1623
+ if (!response.repository)
1624
+ return result;
1625
+ const needsFallback = [];
1626
+ for (const n of issueNums) {
1627
+ const raw = response.repository[`i_${n}`];
1628
+ if (!raw) {
1629
+ result.set(n, false);
1630
+ continue;
1631
+ }
1632
+ const closer = raw.timelineItems?.nodes?.[0]?.closer;
1633
+ const c = closer ?? null;
1634
+ if (!isPrCloser(c)) {
1635
+ needsFallback.push(n);
1636
+ continue;
1637
+ }
1638
+ const bodyHas = PROVENANCE_PATTERN.test(c.body ?? "");
1639
+ const commentHas = c.comments.nodes.some((x) => PROVENANCE_PATTERN.test(x.body));
1640
+ result.set(n, bodyHas || commentHas);
1641
+ }
1642
+ if (needsFallback.length > 0) {
1643
+ const fallback = await fetchProvenanceViaCrossReferences(needsFallback, owner, repo, token);
1644
+ for (const [n, found] of fallback)
1645
+ result.set(n, found);
1646
+ }
1647
+ return result;
1648
+ }
1424
1649
  // ../../packages/aeg-forge-state/src/github-token.ts
1425
1650
  import { execFile as execFile2 } from "node:child_process";
1426
1651
  import { promisify as promisify2 } from "node:util";
@@ -1650,6 +1875,84 @@ function describeError(err) {
1650
1875
  return err;
1651
1876
  return "unknown error";
1652
1877
  }
1878
+ // ../../packages/aeg-forge-state/src/prior-tranche-archival.ts
1879
+ function defaultPriorTrancheArchivalDeps() {
1880
+ let facts = new Map;
1881
+ return {
1882
+ activeTrancheSlugs: async (excludeSlug, repo) => {
1883
+ const index = await indexTrancheMilestonesAsync(repo.owner, repo.repo);
1884
+ facts = index.facts;
1885
+ return index.active.map((m) => m.slug).filter((slug) => slug !== excludeSlug);
1886
+ },
1887
+ deriveTranche: (slug, repo) => deriveTrancheFromForge(repo.owner, repo.repo, slug, facts.get(slug)),
1888
+ openIssues: async (slug, repo) => (await fetchTrancheIssuesAsync(repo.owner, repo.repo, slug)).filter((issue) => issue.state === "OPEN").map((issue) => ({ number: issue.number }))
1889
+ };
1890
+ }
1891
+ function reason(err) {
1892
+ return err instanceof Error ? err.message.split(`
1893
+ `)[0] ?? "failed" : String(err);
1894
+ }
1895
+ async function resolvePriorTrancheArchival(projects, excludeSlug, repo, deps = defaultPriorTrancheArchivalDeps()) {
1896
+ if (projects.length === 0)
1897
+ return { facts: [], infraFailure: null };
1898
+ let candidates;
1899
+ try {
1900
+ candidates = await deps.activeTrancheSlugs(excludeSlug, repo);
1901
+ } catch (err) {
1902
+ return {
1903
+ facts: [],
1904
+ infraFailure: `severity:infra — could not read the active tranches (${reason(err)}); whether a prior tranche is archived is unknown.`
1905
+ };
1906
+ }
1907
+ const facts = [];
1908
+ const unreadable = [];
1909
+ const derived = new Map;
1910
+ const derive = (slug) => {
1911
+ let p = derived.get(slug);
1912
+ if (!p) {
1913
+ p = deps.deriveTranche(slug, repo);
1914
+ derived.set(slug, p);
1915
+ }
1916
+ return p;
1917
+ };
1918
+ for (const project of projects) {
1919
+ let found = null;
1920
+ let unknown = false;
1921
+ for (const slug of candidates) {
1922
+ let candidateTranche;
1923
+ try {
1924
+ candidateTranche = await derive(slug);
1925
+ } catch {
1926
+ unknown = true;
1927
+ unreadable.push(`the tasks of tranche \`${slug}\` (project \`${project}\`)`);
1928
+ break;
1929
+ }
1930
+ if (!candidateTranche.tasks.some((t) => t.projects.includes(project)))
1931
+ continue;
1932
+ let openIssues;
1933
+ try {
1934
+ openIssues = await deps.openIssues(slug, repo);
1935
+ } catch {
1936
+ openIssues = null;
1937
+ }
1938
+ if (openIssues === null) {
1939
+ unknown = true;
1940
+ unreadable.push(`the open Issues of tranche \`${slug}\` (project \`${project}\`)`);
1941
+ break;
1942
+ }
1943
+ if (openIssues.length === 0) {
1944
+ found = { project, priorTrancheSlug: slug, archived: false };
1945
+ break;
1946
+ }
1947
+ }
1948
+ if (!unknown)
1949
+ facts.push(found ?? { project, priorTrancheSlug: null, archived: false });
1950
+ }
1951
+ return {
1952
+ facts,
1953
+ infraFailure: unreadable.length === 0 ? null : `severity:infra — could not read ${unreadable.join(", ")}; whether a prior tranche is archived is unknown.`
1954
+ };
1955
+ }
1653
1956
  // ../../packages/aeg-forge-state/src/fetch-open-issues.ts
1654
1957
  async function fetchOpenIssuesByLabel(slugs, owner, repo, token) {
1655
1958
  const result = new Map;
@@ -1724,6 +2027,10 @@ function buildQuery(issueNumbers) {
1724
2027
  }
1725
2028
  }`;
1726
2029
  }
2030
+ // ../../packages/aeg-forge-state/src/list-issue-milestones.ts
2031
+ function issueMilestonesFromIssues(issues) {
2032
+ return issues.filter((i) => i.state === "OPEN").map((i) => ({ issue: i.number, milestoneTitle: i.milestone?.title ?? null }));
2033
+ }
1727
2034
  // ../../packages/aeg-forge-state/src/resolve-repo.ts
1728
2035
  import { execFile as execFile3 } from "node:child_process";
1729
2036
  import { promisify as promisify3 } from "node:util";
@@ -1786,7 +2093,8 @@ var ANCHOR_FIELDS = [
1786
2093
  "PREMISE",
1787
2094
  "TEST-PLAN",
1788
2095
  "EVIDENCE",
1789
- "BEYOND-SURFACE"
2096
+ "BEYOND-SURFACE",
2097
+ "LIVE"
1790
2098
  ];
1791
2099
  function anchoredRegionBounds(body, field) {
1792
2100
  const masked = maskCode(body);
@@ -1987,7 +2295,6 @@ var DERIVABLE_STATUSES = DERIVED_STATUSES.filter((s) => s !== "backlog");
1987
2295
  // ../../packages/aeg-core/src/waiver-label.ts
1988
2296
  var WAIVER_LABEL = label("waiver-docs");
1989
2297
  var WAIVER_LABEL_REVIEW = label("waiver-review");
1990
- var PRINCIPAL_ALLOWLIST = ["daniboomerang"];
1991
2298
  function isPrincipal(login, principalAllowlist) {
1992
2299
  if (login === null)
1993
2300
  return false;
@@ -2006,6 +2313,14 @@ var RULING_ORDINAL_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Ruling ordinal:\s*(\d+)(
2006
2313
  var BRIEF_HASH_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Brief hash:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
2007
2314
  var POLICY_DIGEST_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Policy digest:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
2008
2315
  var BASE_SHA_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Judged base:\s*([0-9a-f]{7,40})(?![A-Za-z0-9])/im;
2316
+ var MANIFEST_VERSION_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Manifest version:\s*(\d+)\s*$/im;
2317
+ var PAUSE_BOUND_RULING_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Pause-bound ruling:\s*(?:(\S+)\|(\S+)\|([0-9a-f]{64})|\(none\))\s*$/im;
2318
+ function extractPauseBoundRuling(comment) {
2319
+ const m = comment.match(PAUSE_BOUND_RULING_PATTERN);
2320
+ if (!m)
2321
+ return;
2322
+ return m[1] ? { rulingId: m[1], pauseId: m[2], contentDigest: m[3] } : null;
2323
+ }
2009
2324
  function firstFiveLines(comment) {
2010
2325
  return comment.split(`
2011
2326
  `).slice(0, 5).join(`
@@ -2099,6 +2414,8 @@ function extractVerdict(comments, valuePattern, missingLabel) {
2099
2414
  danglingNote: `the most recent ${missingLabel} verdict comment carries a VERDICT-shaped line outside the first-five-line read window`
2100
2415
  };
2101
2416
  }
2417
+ const versionMatch = latest.match(MANIFEST_VERSION_PATTERN);
2418
+ const pauseBoundRuling = extractPauseBoundRuling(latest);
2102
2419
  return {
2103
2420
  value: m[1].toUpperCase().replace(/[_-]/g, " "),
2104
2421
  headSha: extractHeadSha(latest),
@@ -2107,6 +2424,8 @@ function extractVerdict(comments, valuePattern, missingLabel) {
2107
2424
  briefHash: extractBriefHash(latest),
2108
2425
  policyDigest: extractPolicyDigest(latest),
2109
2426
  baseSha: extractBaseSha(latest),
2427
+ ...versionMatch ? { manifestVersion: Number.parseInt(versionMatch[1], 10) } : {},
2428
+ ...pauseBoundRuling === undefined ? {} : { pauseBoundRuling },
2110
2429
  findingSeverities: extractFindingSeverities(latest),
2111
2430
  danglingNote: null
2112
2431
  };
@@ -2117,6 +2436,16 @@ function extractCodeReviewVerdict(comments) {
2117
2436
  function extractSecurityReviewVerdict(comments) {
2118
2437
  return extractVerdict(comments, /^[ \t]*(?:\*{1,3}|_{1,3})?VERDICT:\s*(PASS|FAIL)(?![A-Za-z0-9])/im, "security-review");
2119
2438
  }
2439
+
2440
+ // ../../packages/aeg-core/src/review-status.ts
2441
+ var DEVELOPER_ROUND_MARKER = /<!--\s*aeg:developer:round-(\d+)\s*-->/i;
2442
+ function parseDeveloperRoundMarker(body) {
2443
+ const m = body.match(DEVELOPER_ROUND_MARKER);
2444
+ if (!m)
2445
+ return null;
2446
+ const n = Number(m[1]);
2447
+ return Number.isFinite(n) ? n : null;
2448
+ }
2120
2449
  // ../../packages/aeg-core/src/report-tokens.ts
2121
2450
  var DASH_LOOKALIKES = {
2122
2451
  "-": "‑",
@@ -2812,14 +3141,14 @@ function checkTestPlan(prBody) {
2812
3141
  const region = located.found ? located.section : prBody;
2813
3142
  if (TEST_PLAN_UNIT_TESTS_ONLY_RE.test(region))
2814
3143
  return { status: "pass", errors: [] };
2815
- if (/\*\*\[(?:agent|principal)\]\*\*/.test(region))
3144
+ if (/\*\*\[(?:agent|principal|live)\]\*\*/.test(region))
2816
3145
  return { status: "pass", errors: [] };
2817
3146
  if (located.found && extractFencedBlocks(region).length > 0)
2818
3147
  return { status: "pass", errors: [] };
2819
3148
  return {
2820
3149
  status: "fail",
2821
3150
  errors: [
2822
- "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."
3151
+ "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."
2823
3152
  ]
2824
3153
  };
2825
3154
  }
@@ -3441,6 +3770,375 @@ function checkPrReportDensity(prBody) {
3441
3770
  const results = [checkDecisionsDensity(prBody), checkScopeDensity(prBody)];
3442
3771
  return { errors: results.flatMap((r) => r.errors) };
3443
3772
  }
3773
+ // ../../packages/aeg-core/src/prose-rules.ts
3774
+ var RETIRED_GLOBAL_EXEMPTIONS = [
3775
+ "docs/decisions-legacy.md",
3776
+ "apps/herald-ai/docs/",
3777
+ "apps/vada-ai/docs/",
3778
+ "aeg-root/tranches/completed/",
3779
+ "packages/aeg-core/src/docs/published-prose",
3780
+ "packages/aeg-core/src/retired-vocabulary.test.ts",
3781
+ "packages/aeg-core/src/retired-vocabulary.ts",
3782
+ "/fixtures/",
3783
+ "/node_modules/",
3784
+ "/.next/",
3785
+ "/.turbo/"
3786
+ ];
3787
+ var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
3788
+ var TRANCHE_MODEL_FILE = "/tranche-model.md";
3789
+ var RETIRED_PATTERN_EXEMPTIONS = {
3790
+ [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
3791
+ [String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`]: [
3792
+ "docs-index.md",
3793
+ "apps/vada-ai/specs/legacy/README.md",
3794
+ "apps/vada-ai/specs/vada-product-spec.md",
3795
+ "apps/vada-ai/web/CLAUDE.md",
3796
+ "apps/vada-ai/CLAUDE.md"
3797
+ ],
3798
+ "decisions-legacy": [
3799
+ "packages/aeg-core/src/file-classify.ts",
3800
+ "packages/aeg-core/src/file-classify.test.ts",
3801
+ "packages/aeg-core/src/pr-tier.test.ts",
3802
+ "docs-index.md",
3803
+ ".claude/skills/database/SKILL.md",
3804
+ ".claude/skills/vada-architecture/SKILL.md",
3805
+ "apps/vada-ai/specs/vada-byok-principles.md",
3806
+ "apps/vada-ai/web/CLAUDE.md",
3807
+ "apps/vada-ai/CLAUDE.md"
3808
+ ],
3809
+ CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
3810
+ ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
3811
+ };
3812
+ var retiredPatterns = [
3813
+ String.raw`\bD-[0-9]{3}\b`,
3814
+ "D-(###|NNN|nnn|xxx)",
3815
+ "decision (entry|logged)",
3816
+ "decision-log entry",
3817
+ "decision log entry",
3818
+ "decision log(s|ged|ging)?([^a-z]|$)",
3819
+ "decision-log",
3820
+ "decision entr",
3821
+ "decisions? (are |is )?logged",
3822
+ "log entries",
3823
+ String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`,
3824
+ "decisions-legacy",
3825
+ "CONTRADICTION",
3826
+ "assumes Tier 3",
3827
+ "Lock: ?YES",
3828
+ "Lock: ?NO",
3829
+ "lock approvals?",
3830
+ "approves locks",
3831
+ "Conforms to lock",
3832
+ "Challenges lock",
3833
+ "checkDecisionNumbersFresh",
3834
+ String.raw`roles/team-leader\.md`,
3835
+ String.raw`\(,`,
3836
+ String.raw`,\)`,
3837
+ String.raw`\(\.\)`,
3838
+ ...PLAN_ON_DISK_PATTERNS
3839
+ ];
3840
+ var published = [
3841
+ ["decision-id", "a decision id", /\bD-\d{3,}\b/],
3842
+ ["section-ref", "a section reference", /§/],
3843
+ ["forge-number", "a forge number", /#\d+/],
3844
+ ["retired-name", "the retired public name", /\bAEG\b/],
3845
+ ["tranche-slug", "a tranche slug", /\b[a-z][a-z0-9]*(?:-[a-z0-9]+)+-v\d+\b/],
3846
+ [
3847
+ "label-vocabulary",
3848
+ "forge label vocabulary",
3849
+ /(?:vinaya\/)?\b(?:tranche|iteration|tier|needs|waiver|project|aeg):(?![/\s]|$)/
3850
+ ],
3851
+ ["internal-path", "a repo-internal path", /\b(?:packages|apps|aeg-root|tools|scripts)\//],
3852
+ ["internal-path", "a repo-internal path", /\.(?:claude|husky|github)\//],
3853
+ [
3854
+ "internal-path",
3855
+ "a repo-internal file",
3856
+ /(?:^|[\s(`"'[])[\w.-]+(?:\/[\w.-]+)*\.(?:ts|tsx|js|jsx|mjs|cjs|sh|ya?ml|json|md)\b/
3857
+ ]
3858
+ ];
3859
+ var DEFAULT_PROSE_RULES = [
3860
+ {
3861
+ id: "forge-number",
3862
+ group: "reader-resolvable",
3863
+ scopes: ["ships", "reader-facing", "spec"],
3864
+ patterns: { prose: /#[0-9]{2,4}/g },
3865
+ flags: ["global"],
3866
+ message: "a forge number",
3867
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
3868
+ exemptions: []
3869
+ },
3870
+ {
3871
+ id: "tranche-slug",
3872
+ group: "reader-resolvable",
3873
+ scopes: ["ships", "reader-facing", "product", "spec"],
3874
+ patterns: { prose: /[a-z][a-z-]+-v[0-9]/g },
3875
+ flags: ["global"],
3876
+ message: "an internal tranche slug",
3877
+ severity: { ships: "warning", "reader-facing": "warning", product: "error", spec: "error" },
3878
+ exemptions: []
3879
+ },
3880
+ {
3881
+ id: "task-number",
3882
+ group: "reader-resolvable",
3883
+ scopes: ["spec"],
3884
+ patterns: { prose: /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi },
3885
+ flags: ["global", "ignore-case"],
3886
+ message: "a task number",
3887
+ severity: { spec: "error" },
3888
+ exemptions: []
3889
+ },
3890
+ {
3891
+ id: "source-comment-tranche-slug",
3892
+ group: "reader-resolvable",
3893
+ scopes: ["source-comment"],
3894
+ patterns: { comment: /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g },
3895
+ flags: ["global"],
3896
+ message: "a tranche-slug citation",
3897
+ severity: { "source-comment": "warning" },
3898
+ exemptions: []
3899
+ },
3900
+ {
3901
+ id: "source-comment-forge-number",
3902
+ group: "reader-resolvable",
3903
+ scopes: ["source-comment"],
3904
+ patterns: { comment: /#[0-9]{2,}/g },
3905
+ flags: ["global"],
3906
+ message: "a forge-number citation",
3907
+ severity: { "source-comment": "warning" },
3908
+ exemptions: []
3909
+ },
3910
+ {
3911
+ id: "legacy-batch-name",
3912
+ group: "reader-resolvable",
3913
+ scopes: ["ships", "reader-facing", "spec"],
3914
+ patterns: {},
3915
+ flags: ["built-in"],
3916
+ message: "an internal tranche slug",
3917
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
3918
+ exemptions: [],
3919
+ builtIn: true
3920
+ },
3921
+ {
3922
+ id: "coined-term",
3923
+ group: "reader-resolvable",
3924
+ scopes: ["ships", "reader-facing"],
3925
+ patterns: {},
3926
+ flags: ["built-in"],
3927
+ message: "uses coined term without defining it inline or linking the glossary",
3928
+ severity: { ships: "warning", "reader-facing": "warning" },
3929
+ exemptions: [],
3930
+ builtIn: true
3931
+ },
3932
+ ...retiredPatterns.map((pattern, index) => ({
3933
+ id: `retired-vocabulary-${index + 1}`,
3934
+ group: "retired-vocabulary",
3935
+ scopes: ["repository"],
3936
+ patterns: { repository: pattern },
3937
+ flags: [],
3938
+ message: "retired vocabulary",
3939
+ severity: { repository: "error" },
3940
+ exemptions: RETIRED_GLOBAL_EXEMPTIONS,
3941
+ patternExemptions: RETIRED_PATTERN_EXEMPTIONS
3942
+ })),
3943
+ ...published.map(([id, message, pattern]) => ({
3944
+ id,
3945
+ group: "published-prose",
3946
+ scopes: ["published"],
3947
+ patterns: { published: pattern },
3948
+ flags: [],
3949
+ message,
3950
+ severity: { published: "error" },
3951
+ exemptions: [".worktrees/task/<tranche>/<n>", "task/<tranche>/<n>", ".worktrees/"]
3952
+ }))
3953
+ ];
3954
+ var rulesForGroup = (group) => DEFAULT_PROSE_RULES.filter((rule) => rule.group === group);
3955
+ var RESOLVABLE_SCOPES = ["ships", "reader-facing", "product", "spec", "source-comment"];
3956
+ var RETIRED_SCOPES = ["repository"];
3957
+ var CONFIGURABLE_PROSE_SCOPES = [...RESOLVABLE_SCOPES, ...RETIRED_SCOPES];
3958
+ function groupOfScope(scope) {
3959
+ if (RESOLVABLE_SCOPES.includes(scope))
3960
+ return "reader-resolvable";
3961
+ if (RETIRED_SCOPES.includes(scope))
3962
+ return "retired-vocabulary";
3963
+ return;
3964
+ }
3965
+ var CONFIGURED_PROSE_FLAGS = ["i", "u"];
3966
+ var CONFIGURED_PATTERN_MAX_LENGTH = 200;
3967
+ var CONFIGURABLE_DEFAULT_RULES = DEFAULT_PROSE_RULES.filter((rule) => rule.group !== "published-prose");
3968
+ function allowedScopesFor(rule) {
3969
+ if (rule.builtIn)
3970
+ return rule.scopes;
3971
+ return rule.group === "retired-vocabulary" ? RETIRED_SCOPES : RESOLVABLE_SCOPES;
3972
+ }
3973
+ function normalizeRepoPath(entry) {
3974
+ let out = entry.replace(/\\/g, "/");
3975
+ while (out.startsWith("./"))
3976
+ out = out.slice(2);
3977
+ out = out.replace(/\/{2,}/g, "/");
3978
+ while (out.endsWith("/"))
3979
+ out = out.slice(0, -1);
3980
+ return out;
3981
+ }
3982
+ function isConfiguredExempt(path, exempt, repoRoot) {
3983
+ if (exempt.length === 0)
3984
+ return false;
3985
+ const root = repoRoot === undefined ? undefined : normalizeRepoPath(repoRoot);
3986
+ let rel = normalizeRepoPath(path);
3987
+ if (root && rel.startsWith(`${root}/`))
3988
+ rel = rel.slice(root.length + 1);
3989
+ return exempt.some((entry) => {
3990
+ const e = normalizeRepoPath(entry);
3991
+ return rel === e || rel.startsWith(`${e}/`);
3992
+ });
3993
+ }
3994
+ function ruleReads(set, rule, path) {
3995
+ return !isConfiguredExempt(path, set.exempt, set.repoRoot) && !isConfiguredExempt(path, rule.exempt, set.repoRoot);
3996
+ }
3997
+ var RESOLVABLE_RUN_ORDER = [
3998
+ "forge-number",
3999
+ "tranche-slug",
4000
+ "legacy-batch-name",
4001
+ "task-number",
4002
+ "source-comment-tranche-slug",
4003
+ "source-comment-forge-number",
4004
+ "coined-term"
4005
+ ];
4006
+ var REPORT_GROUPS = { "task-number": 2, "legacy-batch-name": 2 };
4007
+ function scopeDefaultSeverity(scope, sourceCommentSeverity) {
4008
+ if (scope === "source-comment")
4009
+ return sourceCommentSeverity ?? "warning";
4010
+ if (scope === "repository")
4011
+ return "error";
4012
+ return "warning";
4013
+ }
4014
+ function applySeverity(scopes, base, setting) {
4015
+ const out = {};
4016
+ for (const scope of scopes) {
4017
+ const configured = typeof setting === "string" ? setting : setting?.[scope];
4018
+ const value = configured ?? base[scope];
4019
+ if (value !== undefined)
4020
+ out[scope] = value;
4021
+ }
4022
+ return out;
4023
+ }
4024
+ function defaultPatternFor(rule) {
4025
+ const cache = new Map;
4026
+ return (scope) => {
4027
+ if (cache.has(scope))
4028
+ return cache.get(scope) ?? null;
4029
+ const own = rule.patterns[scope] ?? (scope === "source-comment" ? rule.patterns.comment : rule.patterns.prose) ?? Object.values(rule.patterns)[0];
4030
+ const compiled = own === undefined ? null : own instanceof RegExp ? own : new RegExp(own);
4031
+ cache.set(scope, compiled);
4032
+ return compiled;
4033
+ };
4034
+ }
4035
+ function customPatternFor(rule, global) {
4036
+ const cache = new Map;
4037
+ return (scope) => {
4038
+ if (cache.has(scope))
4039
+ return cache.get(scope) ?? null;
4040
+ const source = rule.patterns?.[scope] ?? rule.pattern;
4041
+ const compiled = source === undefined ? null : new RegExp(source, `${rule.flags ?? ""}${global ? "g" : ""}`);
4042
+ cache.set(scope, compiled);
4043
+ return compiled;
4044
+ };
4045
+ }
4046
+ function resolveProseRules(config = undefined, options = {}) {
4047
+ const rules = [];
4048
+ const defaults = config?.defaults ?? {};
4049
+ for (const rule of CONFIGURABLE_DEFAULT_RULES) {
4050
+ const override = defaults[rule.id];
4051
+ if (override === "off")
4052
+ continue;
4053
+ const group = rule.group;
4054
+ const scopes = override?.scopes ?? rule.scopes;
4055
+ const base = {};
4056
+ for (const scope of scopes) {
4057
+ base[scope] = scope === "source-comment" ? options.sourceCommentSeverity ?? rule.severity[scope] ?? "warning" : rule.severity[scope] ?? scopeDefaultSeverity(scope, options.sourceCommentSeverity);
4058
+ }
4059
+ rules.push({
4060
+ id: rule.id,
4061
+ group,
4062
+ custom: false,
4063
+ builtIn: rule.builtIn === true,
4064
+ scopes,
4065
+ message: rule.message,
4066
+ severity: applySeverity(scopes, base, override?.severity),
4067
+ exempt: override?.exempt ?? [],
4068
+ substringExempt: rule.exemptions,
4069
+ reportGroup: REPORT_GROUPS[rule.id],
4070
+ patternFor: defaultPatternFor(rule)
4071
+ });
4072
+ }
4073
+ for (const rule of config?.custom ?? []) {
4074
+ const group = groupOfScope(rule.scopes[0] ?? "") ?? "reader-resolvable";
4075
+ const base = {};
4076
+ for (const scope of rule.scopes)
4077
+ base[scope] = scopeDefaultSeverity(scope, options.sourceCommentSeverity);
4078
+ rules.push({
4079
+ id: rule.id,
4080
+ group,
4081
+ custom: true,
4082
+ builtIn: false,
4083
+ scopes: rule.scopes,
4084
+ message: rule.means,
4085
+ severity: applySeverity(rule.scopes, base, rule.severity),
4086
+ exempt: rule.exempt ?? [],
4087
+ substringExempt: [],
4088
+ patternFor: customPatternFor(rule, group === "reader-resolvable")
4089
+ });
4090
+ }
4091
+ if (options.decisionRecordsPath !== undefined)
4092
+ rules.push(decisionRecordCitationRule(options.decisionRecordsPath));
4093
+ const order = (rule) => {
4094
+ const at = RESOLVABLE_RUN_ORDER.indexOf(rule.id);
4095
+ return rule.custom || at === -1 ? RESOLVABLE_RUN_ORDER.length : at;
4096
+ };
4097
+ const resolvable = rules.filter((rule) => rule.group === "reader-resolvable");
4098
+ const sorted = resolvable.map((rule, index) => ({ rule, index })).sort((a, b) => order(a.rule) - order(b.rule) || a.index - b.index).map(({ rule }) => rule);
4099
+ return {
4100
+ rules: [...sorted, ...rules.filter((rule) => rule.group === "retired-vocabulary")],
4101
+ exempt: config?.exempt ?? [],
4102
+ repoRoot: options.repoRoot
4103
+ };
4104
+ }
4105
+ function rulesOfGroup(set, group) {
4106
+ return set.rules.filter((rule) => rule.group === group);
4107
+ }
4108
+ function rulesInScope(set, scope) {
4109
+ return set.rules.filter((rule) => rule.scopes.includes(scope));
4110
+ }
4111
+ var DEFAULT_PROSE_RULE_SET = resolveProseRules();
4112
+ var DECISION_RECORD_CITATION_ID = "decision-record-citation";
4113
+ var DECISION_RECORD_CITATION_SCOPES = ["ships", "product", "spec", "source-comment"];
4114
+ var DECISION_RECORD_CITATION_MESSAGE = "a decision-record number";
4115
+ function escapeRegExp(text) {
4116
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4117
+ }
4118
+ function decisionRecordCitationPattern(decisionRecordsPath) {
4119
+ const folder = escapeRegExp(normalizeRepoPath(decisionRecordsPath));
4120
+ return new RegExp(String.raw`\bADR[- ]?[0-9]+\b|(?<![A-Za-z0-9_-])${folder}/[0-9]+[A-Za-z0-9._-]*`, "g");
4121
+ }
4122
+ function decisionRecordCitationRule(decisionRecordsPath) {
4123
+ const folder = normalizeRepoPath(decisionRecordsPath);
4124
+ const pattern = decisionRecordCitationPattern(folder);
4125
+ const severity = {};
4126
+ for (const scope of DECISION_RECORD_CITATION_SCOPES)
4127
+ severity[scope] = "error";
4128
+ return {
4129
+ id: DECISION_RECORD_CITATION_ID,
4130
+ group: "reader-resolvable",
4131
+ custom: false,
4132
+ builtIn: false,
4133
+ scopes: DECISION_RECORD_CITATION_SCOPES,
4134
+ message: DECISION_RECORD_CITATION_MESSAGE,
4135
+ severity,
4136
+ exempt: [folder],
4137
+ substringExempt: [],
4138
+ patternFor: () => pattern
4139
+ };
4140
+ }
4141
+
3444
4142
  // ../../packages/aeg-core/src/reader-resolvable-prose.ts
3445
4143
  var PRODUCT_SLUG_SCOPE = [
3446
4144
  "apps/cli/src",
@@ -3452,8 +4150,8 @@ var PRODUCT_SLUG_SCOPE = [
3452
4150
  function isUnderOrEqual(path, prefix) {
3453
4151
  return path === prefix || path.startsWith(`${prefix}/`);
3454
4152
  }
3455
- function isProductScopeFile(path) {
3456
- return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
4153
+ function isProductScopeFile(path, productPaths) {
4154
+ return productPaths.some((prefix) => isUnderOrEqual(path, normalizeRepoPath(prefix)));
3457
4155
  }
3458
4156
  var SHIPS_PREFIX = "aeg-root/";
3459
4157
  function shipsArchivePrefix(shipsPrefix) {
@@ -3461,13 +4159,7 @@ function shipsArchivePrefix(shipsPrefix) {
3461
4159
  }
3462
4160
  var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
3463
4161
  function normalizeSpecPath(entry) {
3464
- let out = entry.replace(/\\/g, "/");
3465
- while (out.startsWith("./"))
3466
- out = out.slice(2);
3467
- out = out.replace(/\/{2,}/g, "/");
3468
- while (out.endsWith("/"))
3469
- out = out.slice(0, -1);
3470
- return out;
4162
+ return normalizeRepoPath(entry);
3471
4163
  }
3472
4164
  function isSpecFile2(path, specPaths) {
3473
4165
  if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
@@ -3479,7 +4171,7 @@ function isSpecFile2(path, specPaths) {
3479
4171
  function isClaudeMdFile(path) {
3480
4172
  return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
3481
4173
  }
3482
- function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
4174
+ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS, productPaths = PRODUCT_SLUG_SCOPE) {
3483
4175
  if (path.startsWith(shipsPrefix)) {
3484
4176
  return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
3485
4177
  }
@@ -3490,7 +4182,7 @@ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPr
3490
4182
  return "internal";
3491
4183
  if (isSpecFile2(path, specPaths))
3492
4184
  return "spec";
3493
- if (isProductScopeFile(path))
4185
+ if (isProductScopeFile(path, productPaths))
3494
4186
  return "product";
3495
4187
  return null;
3496
4188
  }
@@ -3515,9 +4207,16 @@ function lineAt(content, index) {
3515
4207
  }
3516
4208
  return line;
3517
4209
  }
3518
- var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
3519
- var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
3520
- var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
4210
+ var readerRules = rulesForGroup("reader-resolvable");
4211
+ var readerPattern = (id, scope = "prose") => {
4212
+ const pattern = readerRules.find((rule) => rule.id === id)?.patterns[scope];
4213
+ if (!(pattern instanceof RegExp))
4214
+ throw new Error(`default prose rule ${id} has no ${scope} pattern`);
4215
+ return pattern;
4216
+ };
4217
+ var FORGE_NUMBER_PATTERN = readerPattern("forge-number");
4218
+ var TRANCHE_SLUG_VN_PATTERN = readerPattern("tranche-slug");
4219
+ var TASK_NUMBER_PATTERN = readerPattern("task-number");
3521
4220
  function legacySlugPattern(legacySlugs) {
3522
4221
  if (legacySlugs.length === 0)
3523
4222
  return null;
@@ -3527,48 +4226,61 @@ function legacySlugPattern(legacySlugs) {
3527
4226
  function specGrandfatherPaths(specGrandfather) {
3528
4227
  return Array.isArray(specGrandfather) ? [...specGrandfather] : Object.keys(specGrandfather);
3529
4228
  }
3530
- function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4229
+ var REFERENCE_CLASSES = new Set(["ships", "reader-facing", "product", "spec"]);
4230
+ function referenceRulesFor(set, cls) {
4231
+ return rulesInScope(set, cls).filter((rule) => rule.group === "reader-resolvable" && rule.id !== "coined-term");
4232
+ }
4233
+ function citations(pattern, text, group) {
4234
+ const out = [];
4235
+ const re = pattern.global ? pattern : new RegExp(pattern.source, `${pattern.flags}g`);
4236
+ re.lastIndex = 0;
4237
+ let match = re.exec(text);
4238
+ while (match !== null) {
4239
+ if (match[0] === "") {
4240
+ re.lastIndex++;
4241
+ } else {
4242
+ const cited = group !== undefined ? match[group] ?? match[0] : match[0];
4243
+ out.push({ cited, index: match.index + match[0].indexOf(cited) });
4244
+ }
4245
+ match = re.exec(text);
4246
+ }
4247
+ re.lastIndex = 0;
4248
+ return out;
4249
+ }
4250
+ function customMessage(rule, cited) {
4251
+ return `${rule.id}: ${rule.message} ("${cited}")`;
4252
+ }
4253
+ function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS, options = {}) {
4254
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4255
+ const productPaths = options.productPaths ?? PRODUCT_SLUG_SCOPE;
3531
4256
  const findings = [];
3532
4257
  const legacyPattern = legacySlugPattern(legacySlugs);
3533
4258
  const grandfatheredWhole = new Set(Array.isArray(specGrandfather) ? specGrandfather : []);
3534
4259
  const limits = new Map(Array.isArray(specGrandfather) ? [] : Object.entries(specGrandfather));
3535
- const patterns = [
3536
- { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
3537
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
3538
- ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
3539
- ];
3540
- const productPatterns = [
3541
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
3542
- ];
3543
- const specPatterns = [
3544
- ...patterns,
3545
- { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
3546
- ];
3547
4260
  for (const file of files) {
3548
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
3549
- if (!cls || cls === "internal")
3550
- continue;
3551
- if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
4261
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths, productPaths);
4262
+ if (!cls || !REFERENCE_CLASSES.has(cls))
3552
4263
  continue;
3553
4264
  if (cls === "spec" && grandfatheredWhole.has(file.path))
3554
4265
  continue;
3555
- const blocking = cls === "product" || cls === "spec";
3556
4266
  const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
3557
- const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
3558
4267
  const fileFindings = [];
3559
- for (const { pattern, what, group } of patternsToRun) {
3560
- pattern.lastIndex = 0;
3561
- let match = pattern.exec(scrubbed);
3562
- while (match !== null) {
3563
- const cited = group !== undefined ? match[group] ?? match[0] : match[0];
3564
- const citedIndex = match.index + match[0].indexOf(cited);
3565
- fileFindings.push({
4268
+ for (const rule of referenceRulesFor(set, cls)) {
4269
+ if (!ruleReads(set, rule, file.path))
4270
+ continue;
4271
+ const pattern = !rule.custom && rule.id === "legacy-batch-name" ? legacyPattern : rule.patternFor(cls);
4272
+ if (!pattern)
4273
+ continue;
4274
+ const blocking = rule.severity[cls] === "error";
4275
+ const what = cls === "product" ? `${rule.message} in product code` : rule.message;
4276
+ for (const { cited, index } of citations(pattern, scrubbed, rule.custom ? undefined : rule.reportGroup)) {
4277
+ fileFindings.push({
3566
4278
  file: file.path,
3567
- line: lineAt(scrubbed, citedIndex),
3568
- message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
3569
- blocking
4279
+ line: lineAt(scrubbed, index),
4280
+ message: rule.custom ? customMessage(rule, cited) : `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4281
+ blocking,
4282
+ rule: rule.id
3570
4283
  });
3571
- match = pattern.exec(scrubbed);
3572
4284
  }
3573
4285
  }
3574
4286
  const limit = cls === "spec" ? limits.get(file.path) : undefined;
@@ -3609,11 +4321,17 @@ function definesOrLinksGlossary(content, term) {
3609
4321
  return true;
3610
4322
  return /docs\/glossary|glossary\.md/i.test(content);
3611
4323
  }
3612
- function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
4324
+ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, options = {}) {
3613
4325
  const findings = [];
4326
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4327
+ const rule = set.rules.find((r) => !r.custom && r.id === "coined-term");
4328
+ if (!rule)
4329
+ return findings;
3614
4330
  for (const file of files) {
3615
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3616
- if (!cls || !SWEPT_CLASSES.has(cls))
4331
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, DEFAULT_SPEC_PATHS, options.productPaths);
4332
+ if (!cls || !SWEPT_CLASSES.has(cls) || !rule.scopes.includes(cls))
4333
+ continue;
4334
+ if (!ruleReads(set, rule, file.path))
3617
4335
  continue;
3618
4336
  const scrubbed = stripNonProse(file.path, file.content);
3619
4337
  for (const term of glossaryTerms) {
@@ -3626,14 +4344,15 @@ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, read
3626
4344
  file: file.path,
3627
4345
  line,
3628
4346
  message: `uses coined term "${term}" without defining it inline or linking the glossary`,
3629
- blocking: false
4347
+ blocking: rule.severity[cls] === "error",
4348
+ rule: rule.id
3630
4349
  });
3631
4350
  }
3632
4351
  }
3633
4352
  return findings;
3634
4353
  }
3635
- var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
3636
- var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
4354
+ var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = readerPattern("source-comment-tranche-slug", "comment");
4355
+ var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = readerPattern("source-comment-forge-number", "comment");
3637
4356
  function extractComments(path, content) {
3638
4357
  if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
3639
4358
  return content.replace(/[^\n]/g, "");
@@ -3730,39 +4449,40 @@ function extractComments(path, content) {
3730
4449
  }
3731
4450
  return out;
3732
4451
  }
3733
- function checkSourceComments(files, allowlist = []) {
4452
+ function checkSourceComments(files, allowlist = [], options = {}) {
3734
4453
  const findings = [];
3735
4454
  const allowed = new Set(allowlist);
3736
- const patterns = [
3737
- { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
3738
- { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
3739
- ];
4455
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4456
+ const rules = rulesInScope(set, "source-comment").filter((rule) => rule.group === "reader-resolvable");
3740
4457
  for (const file of files) {
3741
4458
  if (!file.path.endsWith(".ts"))
3742
4459
  continue;
3743
4460
  if (allowed.has(file.path))
3744
4461
  continue;
3745
4462
  const comments = extractComments(file.path, file.content);
3746
- for (const { pattern, what } of patterns) {
3747
- pattern.lastIndex = 0;
3748
- let match = pattern.exec(comments);
3749
- while (match !== null) {
4463
+ for (const rule of rules) {
4464
+ if (!ruleReads(set, rule, file.path))
4465
+ continue;
4466
+ const pattern = rule.patternFor("source-comment");
4467
+ if (!pattern)
4468
+ continue;
4469
+ for (const { cited, index } of citations(pattern, comments)) {
3750
4470
  findings.push({
3751
4471
  file: file.path,
3752
- line: lineAt(comments, match.index),
3753
- message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
3754
- blocking: false
4472
+ line: lineAt(comments, index),
4473
+ message: rule.custom ? customMessage(rule, cited) : `comment cites ${rule.message} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4474
+ blocking: rule.severity["source-comment"] === "error",
4475
+ rule: rule.id
3755
4476
  });
3756
- match = pattern.exec(comments);
3757
4477
  }
3758
4478
  }
3759
4479
  }
3760
4480
  return findings;
3761
4481
  }
3762
- function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4482
+ function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS, options = {}) {
3763
4483
  return [
3764
- ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
3765
- ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
4484
+ ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths, options),
4485
+ ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix, options)
3766
4486
  ];
3767
4487
  }
3768
4488
  function parseGlossaryTerms(glossaryContent) {
@@ -3965,6 +4685,17 @@ function checkDocClaims(files, fileReader) {
3965
4685
  };
3966
4686
  }
3967
4687
 
4688
+ // ../../packages/aeg-core/src/protected-paths.ts
4689
+ import { posix as posixPath } from "node:path";
4690
+ var PROTECTED_ADMIN_PATHS = ["vinaya.config.json", ".vinaya/doc-owners", ".github/", "aeg-root/"];
4691
+ function normalizeTouchedPath(path) {
4692
+ return posixPath.resolve("/", path.replace(/\\/g, "/")).replace(/^\/+/, "");
4693
+ }
4694
+ function isProtectedAdminPath(path) {
4695
+ const normalized = normalizeTouchedPath(path);
4696
+ return PROTECTED_ADMIN_PATHS.some((prefix) => normalized === prefix || normalized.startsWith(prefix));
4697
+ }
4698
+
3968
4699
  // ../../packages/aeg-core/src/issue-validation.ts
3969
4700
  function hasRationaleField(body, labelPattern) {
3970
4701
  const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
@@ -4084,13 +4815,20 @@ function globCoversPath(glob, path) {
4084
4815
  return !p.includes("/");
4085
4816
  return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
4086
4817
  }
4818
+ function surfaceEntryResolves(entry, resolvesToFile, pinnedFiles) {
4819
+ if (resolvesToFile(entry))
4820
+ return true;
4821
+ const directory = entry.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
4822
+ return pinnedFiles.some((path) => path.startsWith(`${directory}/`));
4823
+ }
4087
4824
  function checkSurfaceGlobsResolve(body, resolvesToFile) {
4088
4825
  const surface = parseIssueSurface(body);
4089
4826
  if (!surface.ok)
4090
4827
  return { status: "pass", errors: [] };
4828
+ const pinnedFiles = boundaryPinnedFiles(body);
4091
4829
  const errors = [];
4092
4830
  for (const glob of surface.value.in) {
4093
- if (!resolvesToFile(glob)) {
4831
+ if (!surfaceEntryResolves(glob, resolvesToFile, pinnedFiles)) {
4094
4832
  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.`);
4095
4833
  }
4096
4834
  }
@@ -4120,6 +4858,14 @@ function recordedBeyondSurfacePaths(body) {
4120
4858
  return paths;
4121
4859
  }
4122
4860
  function checkSurfaceScope(changedFiles, surface, recorded) {
4861
+ for (const path of changedFiles) {
4862
+ if (!isProtectedAdminPath(path))
4863
+ continue;
4864
+ const normalized = normalizeTouchedPath(path);
4865
+ if (!surface.in.some((glob) => globCoversPath(glob, normalized))) {
4866
+ return { ok: false, violation: { path, reason: "protected" } };
4867
+ }
4868
+ }
4123
4869
  const listed = new Set(recorded);
4124
4870
  const violation = beyondSurfacePaths(changedFiles, surface).find((entry) => !listed.has(entry.path));
4125
4871
  return violation ? { ok: false, violation } : { ok: true };
@@ -4175,12 +4921,22 @@ function checkPartsCiteDefinedObjectives(body) {
4175
4921
  }
4176
4922
  return { status: errors.length > 0 ? "fail" : "pass", errors };
4177
4923
  }
4924
+ var ISSUE_LIVE_LINE_RE = /^-\s*\*{2}\[live\]\*{2}(.*)$/gim;
4925
+ function liveCommand(text) {
4926
+ const trimmed = text.trim();
4927
+ const span = /^(`+)(.+)\1$/.exec(trimmed);
4928
+ return span ? span[2].trim() : trimmed;
4929
+ }
4930
+ function liveItemsIn(region) {
4931
+ return [...region.matchAll(ISSUE_LIVE_LINE_RE)].map((m) => liveCommand(m[1] ?? "")).filter(Boolean);
4932
+ }
4933
+ function parseLiveTestPlanItems(body) {
4934
+ const located = locateTestPlanSection(body);
4935
+ return located.found ? liveItemsIn(located.section) : [];
4936
+ }
4178
4937
  function isTaskIssueLabelSet(labels) {
4179
4938
  return hasLabel("tranche", labels);
4180
4939
  }
4181
- function checkTrancheLabelPresence(_body, _labels) {
4182
- return { status: "pass", errors: [] };
4183
- }
4184
4940
  function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
4185
4941
  if (!isTaskIssueLabelSet(labels))
4186
4942
  return { status: "pass", errors: [] };
@@ -4196,6 +4952,7 @@ function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTi
4196
4952
  };
4197
4953
  }
4198
4954
  var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
4955
+ var PATH_TEXT = (body) => stripCode(body, { inlineSpans: "keep" });
4199
4956
  function isControlCodePoint(codePoint) {
4200
4957
  return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
4201
4958
  }
@@ -4256,8 +5013,14 @@ function checkProjectsRegistered(body, _labels, registeredNames) {
4256
5013
  }
4257
5014
  return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
4258
5015
  }
5016
+ function rationaleFieldText(text, labelPattern) {
5017
+ const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})[^\\n]*\\n?([\\s\\S]*?)(?=\\n\\s*(?:\\*\\*[A-Z]|#{1,4}\\s)|(?![\\s\\S]))`, "im");
5018
+ const m = re.exec(text);
5019
+ return m ? m[0] : "";
5020
+ }
4259
5021
  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;
4260
5022
  var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
5023
+ var RATIONALE_PATH_RE_GLOBAL = /`([\w.@-]+(?:\/[\w.@-]+)+)`/g;
4261
5024
  function normalizeEdgeId(s) {
4262
5025
  const qualified = splitSlugQualifiedEdge(s);
4263
5026
  return (qualified ? qualified.bareId : s).replace(/^#/, "").trim();
@@ -4265,6 +5028,15 @@ function normalizeEdgeId(s) {
4265
5028
  function edgesNameEachOther(a, b) {
4266
5029
  return a.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(b.ref)) || b.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(a.ref));
4267
5030
  }
5031
+ var BOUNDARY_OUT_RE = /\bOut\s*:\s*([\s\S]*)$/im;
5032
+ function boundaryOutText(body) {
5033
+ const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
5034
+ const m = BOUNDARY_OUT_RE.exec(boundary);
5035
+ return m ? m[1] : "";
5036
+ }
5037
+ function namedPathsIn(text) {
5038
+ return [...new Set([...text.matchAll(RATIONALE_PATH_RE_GLOBAL)].map((m) => m[1]))].filter((p) => !/^https?:\/\//i.test(p));
5039
+ }
4268
5040
  var FILE_EXTENSIONS = new Set([
4269
5041
  "ts",
4270
5042
  "tsx",
@@ -4286,6 +5058,11 @@ var FILE_EXTENSIONS = new Set([
4286
5058
  "html",
4287
5059
  "css"
4288
5060
  ]);
5061
+ function boundaryPinnedFiles(body) {
5062
+ const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
5063
+ const excluded = new Set(namedPathsIn(boundaryOutText(body)));
5064
+ return namedPathsIn(boundary).filter((p) => looksLikeFilePath(p) && !excluded.has(p));
5065
+ }
4289
5066
  var CI_SHARD_DIR = "apps/cli/tests/ci-shards";
4290
5067
  var CI_SHARD_PROBE = `${CI_SHARD_DIR}/shard-1.txt`;
4291
5068
 
@@ -4310,7 +5087,7 @@ function isGrandfathered(isoDate) {
4310
5087
  return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
4311
5088
  }
4312
5089
  var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
4313
- function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
5090
+ function checkA1(entries, principalAllowlist) {
4314
5091
  const failures = [];
4315
5092
  for (const e of entries) {
4316
5093
  if (!e.facts)
@@ -4340,6 +5117,37 @@ function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
4340
5117
  note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4341
5118
  };
4342
5119
  }
5120
+ function checkA2(entries, hasProvenanceByKey) {
5121
+ const failures = [];
5122
+ for (const e of entries) {
5123
+ if (!e.facts)
5124
+ continue;
5125
+ if (e.facts.issueState !== "closed" || e.facts.prState !== "merged")
5126
+ continue;
5127
+ const key = `${e.trancheSlug}/${e.task.id}`;
5128
+ const hasProvenance = hasProvenanceByKey.get(key);
5129
+ if (hasProvenance === undefined)
5130
+ continue;
5131
+ if (!hasProvenance) {
5132
+ failures.push({
5133
+ code: "archived-without-provenance",
5134
+ issue: e.task.issue,
5135
+ tranche: e.trancheSlug,
5136
+ task: e.task.id,
5137
+ reason: "Closing PR has no `### AEG provenance` comment (Archivist close-out missing)",
5138
+ grandfathered: isGrandfathered(e.facts.mergedAt)
5139
+ });
5140
+ }
5141
+ }
5142
+ const activeFails = failures.filter((f) => !f.grandfathered);
5143
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
5144
+ return {
5145
+ check: "A2",
5146
+ status,
5147
+ failures,
5148
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
5149
+ };
5150
+ }
4343
5151
  function checkA3(entries) {
4344
5152
  const failures = [];
4345
5153
  for (const e of entries) {
@@ -4555,6 +5363,33 @@ function checkL1(files, entriesBySlug) {
4555
5363
  note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
4556
5364
  };
4557
5365
  }
5366
+ function checkL2(files, entriesBySlug) {
5367
+ const failures = [];
5368
+ for (const f of files) {
5369
+ if (!f.archived)
5370
+ continue;
5371
+ const entries = entriesBySlug.get(f.slug) ?? [];
5372
+ for (const e of entries) {
5373
+ if (!e.facts)
5374
+ continue;
5375
+ if (e.facts.issueState === "open") {
5376
+ failures.push({
5377
+ code: "premature-archive",
5378
+ issue: e.task.issue,
5379
+ tranche: f.slug,
5380
+ task: e.task.id,
5381
+ reason: `Archived tranche has open task-Issue #${e.task.issue ?? "?"} (premature archive)`
5382
+ });
5383
+ }
5384
+ }
5385
+ }
5386
+ return {
5387
+ check: "L2",
5388
+ status: "info",
5389
+ failures,
5390
+ note: failures.length > 0 ? `${failures.length} archived tranche(s) with an open task-Issue — investigate (advisory)` : undefined
5391
+ };
5392
+ }
4558
5393
  function checkL3(files) {
4559
5394
  const active = files.filter((f) => !f.archived);
4560
5395
  return {
@@ -4564,6 +5399,51 @@ function checkL3(files) {
4564
5399
  note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
4565
5400
  };
4566
5401
  }
5402
+ function checkL4(activeTrancheSlugs, issueMilestones) {
5403
+ const activeSet = new Set(activeTrancheSlugs);
5404
+ const failures = [];
5405
+ for (const f of issueMilestones) {
5406
+ if (!activeSet.has(f.tranche))
5407
+ continue;
5408
+ if (f.milestoneTitle === f.tranche)
5409
+ continue;
5410
+ failures.push({
5411
+ code: "milestone-drift",
5412
+ issue: f.issue,
5413
+ tranche: f.tranche,
5414
+ 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`
5415
+ });
5416
+ }
5417
+ return {
5418
+ check: "L4",
5419
+ status: "info",
5420
+ failures,
5421
+ 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
5422
+ };
5423
+ }
5424
+ function checkL5(activeTrancheSlugs, entriesBySlug) {
5425
+ const failures = [];
5426
+ for (const slug of activeTrancheSlugs) {
5427
+ const entries = entriesBySlug.get(slug) ?? [];
5428
+ const withFacts = entries.filter((e) => e.facts !== undefined);
5429
+ if (withFacts.length === 0)
5430
+ continue;
5431
+ const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
5432
+ if (allClosed) {
5433
+ failures.push({
5434
+ code: "tranche-not-archived",
5435
+ tranche: slug,
5436
+ reason: "Every task Issue is closed but the tranche is not recorded as complete — archive it"
5437
+ });
5438
+ }
5439
+ }
5440
+ return {
5441
+ check: "L5",
5442
+ status: failures.length > 0 ? "fail" : "pass",
5443
+ failures,
5444
+ note: failures.length > 0 ? `${failures.length} tranche(s) whose task Issues are all closed but were never archived` : undefined
5445
+ };
5446
+ }
4567
5447
  function extractClosesReferences(prBody) {
4568
5448
  const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
4569
5449
  const stripped = stripCode(prBody);
@@ -4659,6 +5539,58 @@ function extractIssue(body) {
4659
5539
  }
4660
5540
  // ../../packages/aeg-core/src/review-input-manifest.ts
4661
5541
  import { createHash as createHash4 } from "node:crypto";
5542
+
5543
+ // ../../packages/aeg-core/src/ruling-ordinal.ts
5544
+ var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
5545
+ function newestPrincipalRulingOrdinal(comments, allowlist) {
5546
+ let best = 0;
5547
+ for (const c of comments) {
5548
+ if (!isPrincipal(c.author, allowlist))
5549
+ continue;
5550
+ const firstLine = (c.body.split(`
5551
+ `)[0] ?? "").trim();
5552
+ const m = RULING_MARKER_ORDINAL.exec(firstLine);
5553
+ if (!m)
5554
+ continue;
5555
+ const k = Number.parseInt(m[1], 10);
5556
+ if (k > best)
5557
+ best = k;
5558
+ }
5559
+ return best;
5560
+ }
5561
+ function parseRulingIdentity(rulingId) {
5562
+ const m = /^(issue-)?(\d+)-(\d+)$/.exec(rulingId);
5563
+ if (!m)
5564
+ return null;
5565
+ const ref = Number.parseInt(m[2], 10);
5566
+ const ordinal = Number.parseInt(m[3], 10);
5567
+ if (ref <= 0 || ordinal <= 0)
5568
+ return null;
5569
+ return { target: m[1] ? "issue" : "pr", ref, ordinal };
5570
+ }
5571
+ function principalRulingTextById(comments, allowlist, rulingId) {
5572
+ const identity = parseRulingIdentity(rulingId);
5573
+ if (identity === null)
5574
+ return null;
5575
+ const matches = comments.filter((c) => {
5576
+ if (!isPrincipal(c.author, allowlist))
5577
+ return false;
5578
+ const m = RULING_MARKER_ORDINAL.exec((c.body.split(`
5579
+ `)[0] ?? "").trim());
5580
+ return m !== null && Number.parseInt(m[1], 10) === identity.ordinal;
5581
+ });
5582
+ if (matches.length !== 1)
5583
+ return null;
5584
+ const body = matches[0].body;
5585
+ const idx = body.indexOf(`
5586
+ `);
5587
+ return idx === -1 ? "" : body.slice(idx + 1).trim();
5588
+ }
5589
+
5590
+ // ../../packages/aeg-core/src/review-input-manifest.ts
5591
+ function pauseBoundRulingDigest(rulingText) {
5592
+ return createHash4("sha256").update(rulingText).digest("hex");
5593
+ }
4662
5594
  function briefHash(brief) {
4663
5595
  return createHash4("sha256").update(`${brief}
4664
5596
  `).digest("hex");
@@ -4719,14 +5651,19 @@ function compareManifest(echoed, current, patchIdOf) {
4719
5651
  const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4720
5652
  const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4721
5653
  const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
5654
+ const legacyCurrent = current.manifestVersion === undefined;
5655
+ const manifestVersion = legacyCurrent ? echoed.manifestVersion === undefined || echoed.manifestVersion === null : echoed.manifestVersion === current.manifestVersion;
5656
+ const pauseBoundRuling = legacyCurrent ? true : Object.hasOwn(echoed, "pauseBoundRuling") && JSON.stringify(echoed.pauseBoundRuling) === JSON.stringify(current.pauseBoundRuling);
4722
5657
  const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4723
5658
  return {
4724
- bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
5659
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && pauseBoundRuling && manifestVersion && policyDigestBound,
4725
5660
  head,
4726
5661
  base,
4727
5662
  briefHash: briefHashBound,
4728
5663
  objectivesVersion,
4729
5664
  rulingOrdinal,
5665
+ pauseBoundRuling,
5666
+ manifestVersion,
4730
5667
  policyDigest: policyDigestBound
4731
5668
  };
4732
5669
  }
@@ -4742,7 +5679,7 @@ function renderGateDeferred(deferred) {
4742
5679
  return ` ${deferred.length} finding(s) deferred, not blocking this round: ${items}.`;
4743
5680
  }
4744
5681
  function checkReviewGate(input) {
4745
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
5682
+ const { principalAllowlist } = input;
4746
5683
  const waived = isWaiverLabelActorVerified({
4747
5684
  label: WAIVER_LABEL_REVIEW,
4748
5685
  labels: input.labels,
@@ -4781,27 +5718,33 @@ function checkReviewGate(input) {
4781
5718
  const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4782
5719
  const securityClean = securityTextClean && securityPolicyClean;
4783
5720
  const currentManifest = {
5721
+ ...input.manifestVersion === undefined ? {} : { manifestVersion: input.manifestVersion },
4784
5722
  headSha: input.headSha,
4785
5723
  baseSha: input.baseSha ?? null,
4786
5724
  briefHash: input.briefHash ?? null,
4787
5725
  objectivesVersion: input.objectivesVersion,
4788
5726
  rulingOrdinal: input.rulingOrdinal,
5727
+ pauseBoundRuling: input.pauseBoundRuling ?? null,
4789
5728
  policyDigest: policyDigest(policy)
4790
5729
  };
4791
5730
  const codeReviewEchoed = {
5731
+ manifestVersion: codeReview.manifestVersion,
4792
5732
  headSha: codeReview.headSha,
4793
5733
  baseSha: codeReview.baseSha,
4794
5734
  briefHash: codeReview.briefHash,
4795
5735
  objectivesVersion: codeReview.objectivesVersion,
4796
5736
  rulingOrdinal: codeReview.rulingOrdinal,
5737
+ pauseBoundRuling: codeReview.pauseBoundRuling,
4797
5738
  policyDigest: codeReview.policyDigest
4798
5739
  };
4799
5740
  const securityEchoed = {
5741
+ manifestVersion: security.manifestVersion,
4800
5742
  headSha: security.headSha,
4801
5743
  baseSha: security.baseSha,
4802
5744
  briefHash: security.briefHash,
4803
5745
  objectivesVersion: security.objectivesVersion,
4804
5746
  rulingOrdinal: security.rulingOrdinal,
5747
+ pauseBoundRuling: security.pauseBoundRuling,
4805
5748
  policyDigest: security.policyDigest
4806
5749
  };
4807
5750
  const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
@@ -4840,6 +5783,10 @@ function checkReviewGate(input) {
4840
5783
  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"}`);
4841
5784
  } else if (!codeReviewBinding.policyDigest) {
4842
5785
  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}`);
5786
+ } else if (!codeReviewBinding.manifestVersion) {
5787
+ problems.push(`the newest code-review verdict echoes manifest version ${codeReview.manifestVersion ?? "none"}, the frozen review-input manifest is version ${currentManifest.manifestVersion ?? "unversioned"}`);
5788
+ } else if (!codeReviewBinding.pauseBoundRuling) {
5789
+ problems.push(`the newest code-review verdict echoes pauseBoundRuling ${renderBinding(codeReview.pauseBoundRuling)}, the frozen review-input manifest binds ${renderBinding(currentManifest.pauseBoundRuling)}`);
4843
5790
  }
4844
5791
  if (!securityTextClean) {
4845
5792
  problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
@@ -4857,6 +5804,10 @@ function checkReviewGate(input) {
4857
5804
  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"}`);
4858
5805
  } else if (!securityBinding.policyDigest) {
4859
5806
  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}`);
5807
+ } else if (!securityBinding.manifestVersion) {
5808
+ problems.push(`the newest security-review verdict echoes manifest version ${security.manifestVersion ?? "none"}, the frozen review-input manifest is version ${currentManifest.manifestVersion ?? "unversioned"}`);
5809
+ } else if (!securityBinding.pauseBoundRuling) {
5810
+ problems.push(`the newest security-review verdict echoes pauseBoundRuling ${renderBinding(security.pauseBoundRuling)}, the frozen review-input manifest binds ${renderBinding(currentManifest.pauseBoundRuling)}`);
4860
5811
  }
4861
5812
  const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4862
5813
  return {
@@ -4865,29 +5816,16 @@ function checkReviewGate(input) {
4865
5816
  waived: false
4866
5817
  };
4867
5818
  }
5819
+ function renderBinding(binding) {
5820
+ if (binding === undefined)
5821
+ return "(absent)";
5822
+ return binding === null ? "(none)" : `${binding.rulingId}|${binding.pauseId}|${binding.contentDigest}`;
5823
+ }
4868
5824
  var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4869
5825
  var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4870
5826
  function isChangesetsReleasePr(branch, author, expectedAuthor) {
4871
5827
  return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4872
5828
  }
4873
- // ../../packages/aeg-core/src/ruling-ordinal.ts
4874
- var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4875
- function newestPrincipalRulingOrdinal(comments, allowlist) {
4876
- let best = 0;
4877
- for (const c of comments) {
4878
- if (!isPrincipal(c.author, allowlist))
4879
- continue;
4880
- const firstLine = (c.body.split(`
4881
- `)[0] ?? "").trim();
4882
- const m = RULING_MARKER_ORDINAL.exec(firstLine);
4883
- if (!m)
4884
- continue;
4885
- const k = Number.parseInt(m[1], 10);
4886
- if (k > best)
4887
- best = k;
4888
- }
4889
- return best;
4890
- }
4891
5829
  // ../../packages/aeg-core/src/markdown-table.ts
4892
5830
  function splitRow(line) {
4893
5831
  const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
@@ -5039,7 +5977,6 @@ var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
5039
5977
  var NON_GATE_BIN_NAMES = NON_GATE_BINS;
5040
5978
  var TWIN_CANDIDATE_EXCEPTIONS = {
5041
5979
  "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)',
5042
- "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)`,
5043
5980
  "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
5044
5981
  };
5045
5982
  var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
@@ -5263,72 +6200,10 @@ function compareToBaseline(current, baseline) {
5263
6200
  };
5264
6201
  }
5265
6202
  // ../../packages/aeg-core/src/retired-vocabulary.ts
5266
- var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
5267
- var RETIRED_PATTERNS = [
5268
- String.raw`\bD-[0-9]{3}\b`,
5269
- "D-(###|NNN|nnn|xxx)",
5270
- "decision (entry|logged)",
5271
- "decision-log entry",
5272
- "decision log entry",
5273
- "decision log(s|ged|ging)?([^a-z]|$)",
5274
- "decision-log",
5275
- "decision entr",
5276
- "decisions? (are |is )?logged",
5277
- "log entries",
5278
- String.raw`decisions\.md`,
5279
- "decisions-legacy",
5280
- "CONTRADICTION",
5281
- "assumes Tier 3",
5282
- "Lock: ?YES",
5283
- "Lock: ?NO",
5284
- "lock approvals?",
5285
- "approves locks",
5286
- "Conforms to lock",
5287
- "Challenges lock",
5288
- "checkDecisionNumbersFresh",
5289
- String.raw`roles/team-leader\.md`,
5290
- String.raw`\(,`,
5291
- String.raw`,\)`,
5292
- String.raw`\(\.\)`,
5293
- ...PLAN_ON_DISK_PATTERNS
5294
- ];
5295
- var TRANCHE_MODEL_FILE = "/tranche-model.md";
5296
- var RETIRED_EXEMPT_SUBSTRINGS = [
5297
- "docs/decisions-legacy.md",
5298
- "apps/herald-ai/docs/",
5299
- "apps/vada-ai/docs/",
5300
- "aeg-root/tranches/completed/",
5301
- "packages/aeg-core/src/docs/published-prose",
5302
- "packages/aeg-core/src/retired-vocabulary.test.ts",
5303
- "packages/aeg-core/src/retired-vocabulary.ts",
5304
- "/fixtures/",
5305
- "/node_modules/",
5306
- "/.next/",
5307
- "/.turbo/"
5308
- ];
5309
- var PATTERN_EXEMPT = {
5310
- [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
5311
- [String.raw`decisions\.md`]: [
5312
- "docs-index.md",
5313
- "apps/vada-ai/specs/legacy/README.md",
5314
- "apps/vada-ai/specs/vada-product-spec.md",
5315
- "apps/vada-ai/web/CLAUDE.md",
5316
- "apps/vada-ai/CLAUDE.md"
5317
- ],
5318
- "decisions-legacy": [
5319
- "packages/aeg-core/src/file-classify.ts",
5320
- "packages/aeg-core/src/file-classify.test.ts",
5321
- "packages/aeg-core/src/pr-tier.test.ts",
5322
- "docs-index.md",
5323
- ".claude/skills/database/SKILL.md",
5324
- ".claude/skills/vada-architecture/SKILL.md",
5325
- "apps/vada-ai/specs/vada-byok-principles.md",
5326
- "apps/vada-ai/web/CLAUDE.md",
5327
- "apps/vada-ai/CLAUDE.md"
5328
- ],
5329
- CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
5330
- ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
5331
- };
6203
+ var retiredRules = rulesForGroup("retired-vocabulary");
6204
+ var RETIRED_PATTERNS = retiredRules.map((rule) => rule.patterns.repository);
6205
+ var PATTERN_EXEMPT = RETIRED_PATTERN_EXEMPTIONS;
6206
+ var DEFAULT_PATTERN_OF = new Map(retiredRules.map((rule) => [rule.id, rule.patterns.repository]));
5332
6207
  function lineNumbers(content, pattern) {
5333
6208
  const out = [];
5334
6209
  const lines = content.split(`
@@ -5339,22 +6214,29 @@ function lineNumbers(content, pattern) {
5339
6214
  }
5340
6215
  return out;
5341
6216
  }
5342
- function scanRetiredVocabulary(files) {
6217
+ function scanRetiredVocabulary(files, rules = DEFAULT_PROSE_RULE_SET) {
5343
6218
  const findings = [];
6219
+ const retired = rulesOfGroup(rules, "retired-vocabulary");
5344
6220
  for (const file of files) {
5345
- if (RETIRED_EXEMPT_SUBSTRINGS.some((e) => file.path.includes(e)))
5346
- continue;
5347
- for (const pattern of RETIRED_PATTERNS) {
5348
- const patternExempt = PATTERN_EXEMPT[pattern] ?? [];
5349
- if (patternExempt.some((e) => file.path.includes(e)))
6221
+ for (const rule of retired) {
6222
+ if (rule.substringExempt.some((e) => file.path.includes(e)))
6223
+ continue;
6224
+ if (!ruleReads(rules, rule, file.path))
6225
+ continue;
6226
+ const re = rule.patternFor("repository");
6227
+ if (!re)
6228
+ continue;
6229
+ const pattern = rule.custom ? re.source : DEFAULT_PATTERN_OF.get(rule.id) ?? re.source;
6230
+ if (!rule.custom && (PATTERN_EXEMPT[pattern] ?? []).some((e) => file.path.includes(e)))
5350
6231
  continue;
5351
- const re = new RegExp(pattern);
5352
6232
  for (const line of lineNumbers(file.content, re)) {
5353
6233
  findings.push({
5354
6234
  file: file.path,
5355
6235
  line,
5356
6236
  pattern,
5357
- message: `claims a retired AEG mechanism is still live (matches /${pattern}/)`
6237
+ message: rule.custom ? `${rule.id}: ${rule.message} (matches /${pattern}/)` : `claims a retired AEG mechanism is still live (matches /${pattern}/)`,
6238
+ rule: rule.id,
6239
+ blocking: rule.severity.repository === "error"
5358
6240
  });
5359
6241
  }
5360
6242
  }
@@ -5378,7 +6260,7 @@ function isSelfDependency(dep, task, issue) {
5378
6260
  function checkDispatchReadiness(input) {
5379
6261
  const { trancheSlug, task } = input;
5380
6262
  const taskLabel = `task ${task.id} (tranche ${trancheSlug})`;
5381
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
6263
+ const { principalAllowlist } = input;
5382
6264
  const blockerDetails = [];
5383
6265
  const push = (blockerClass, message) => {
5384
6266
  blockerDetails.push({ class: blockerClass, message });
@@ -5470,6 +6352,16 @@ function pushesAnyBranchRef(pushRefs) {
5470
6352
  return pushRefs.split(`
5471
6353
  `).map((line) => line.trim()).filter((line) => line.length > 0).some((line) => line.split(/\s+/)[2]?.startsWith("refs/heads/") === true);
5472
6354
  }
6355
+ function resolveDefaultBranch(facts) {
6356
+ const { originHead, hasOriginMain, hasOriginMaster } = facts;
6357
+ if (originHead !== null && originHead !== "")
6358
+ return originHead;
6359
+ if (hasOriginMain)
6360
+ return "main";
6361
+ if (hasOriginMaster)
6362
+ return "master";
6363
+ return null;
6364
+ }
5473
6365
  function checkMainBranchRefusal(facts) {
5474
6366
  const { currentSymbolicBranch, defaultBranch, pushRefs = null } = facts;
5475
6367
  if (currentSymbolicBranch === null)
@@ -5730,54 +6622,61 @@ function checkFirstPushDispatchGate(input) {
5730
6622
  reason: `verify-dispatch reports READY TO DISPATCH for \`${branch}\`.`
5731
6623
  };
5732
6624
  }
5733
- // ../../packages/aeg-core/src/issue-assignment.ts
5734
- function decideIssueAssignment(input) {
5735
- const { branch, remoteRefExists, issue, assignees, login } = input;
5736
- if (parseTaskBranch(branch) === null) {
5737
- return {
5738
- action: "skip",
5739
- reason: `Branch \`${branch}\` is not a task/<tranche>/<n> branch — Issue self-assignment only applies to task branches.`
5740
- };
5741
- }
5742
- if (remoteRefExists) {
5743
- return {
5744
- action: "skip",
5745
- reason: `Branch \`${branch}\` already exists on the remote — not its first push, nothing to assign.`
5746
- };
5747
- }
5748
- if (issue === null) {
5749
- return {
5750
- action: "skip",
5751
- reason: `No Issue resolved for \`${branch}\` from its topology row — skipping self-assignment (the gate owns refusing an unplanned branch).`
5752
- };
5753
- }
5754
- if (assignees === null) {
5755
- return {
5756
- action: "skip",
5757
- reason: `Could not read Issue #${issue}'s current assignees — skipping rather than risking a double-assign (fail-open, never a guess).`
5758
- };
5759
- }
5760
- if (assignees.length > 0) {
5761
- return {
5762
- action: "skip",
5763
- reason: `Issue #${issue} is already assigned (${assignees.join(", ")}) — no-op.`
5764
- };
5765
- }
5766
- if (login === null) {
5767
- return {
5768
- action: "skip",
5769
- reason: "Could not resolve the authenticated `gh` login — never assigning anyone other than the actual pusher, so skipping."
5770
- };
6625
+ // ../../packages/aeg-core/src/live-record.ts
6626
+ var RECORD_LINE_RE = /^-\s*\[([ xX])\]\s*\*\*\[live\]\*\*\s+(`+) ?(.+?) ?\2(?!`)\s+—\s+(passed|failed|unverified)\s+at\s+`([^`]+)`/;
6627
+ function liveMarkers(body) {
6628
+ const masked = maskCode(body);
6629
+ return [...masked.matchAll(/<!--\s*AEG:LIVE:(?:START|END)\s*-->/g)].map((m) => ({
6630
+ start: m.index,
6631
+ end: m.index + m[0].length
6632
+ }));
6633
+ }
6634
+ var AMBIGUOUS_RECORD_LINE = {
6635
+ line: "- [ ] **[live]** the pull request body carries more than one `AEG:LIVE` marker pair, so the driver's record cannot be told apart",
6636
+ ticked: false,
6637
+ command: "",
6638
+ outcome: "failed",
6639
+ head: ""
6640
+ };
6641
+ function readLiveRecord(body) {
6642
+ const markers = liveMarkers(body).length;
6643
+ if (markers === 0)
6644
+ return [];
6645
+ if (markers !== 2)
6646
+ return [AMBIGUOUS_RECORD_LINE];
6647
+ const region = anchoredRegion(body, "LIVE");
6648
+ if (region === null)
6649
+ return [];
6650
+ const lines = [];
6651
+ for (const raw of region.split(`
6652
+ `)) {
6653
+ const line = raw.trim();
6654
+ const m = RECORD_LINE_RE.exec(line);
6655
+ if (!m)
6656
+ continue;
6657
+ lines.push({
6658
+ line,
6659
+ ticked: m[1].toLowerCase() === "x",
6660
+ command: m[3],
6661
+ outcome: m[4],
6662
+ head: m[5]
6663
+ });
5771
6664
  }
5772
- return {
5773
- action: "assign",
5774
- issue,
5775
- login,
5776
- reason: `First push of \`${branch}\` — assigning Issue #${issue} to @${login} (the authenticated pusher).`
5777
- };
6665
+ return lines;
5778
6666
  }
5779
6667
  // ../../packages/aeg-core/src/test-plan-gate.ts
5780
- function evaluateTestPlanGate(body, branch) {
6668
+ function gradedLiveLines(record, live) {
6669
+ if (live === undefined)
6670
+ return record.map((entry) => entry.line);
6671
+ const commands = new Set(live.liveCommands);
6672
+ const others = record.filter((entry) => !commands.has(entry.command)).map((entry) => entry.line);
6673
+ const graded = live.liveCommands.map((command) => {
6674
+ const atHead = record.filter((entry) => entry.command === command && entry.head === live.head);
6675
+ return (atHead.find((entry) => entry.ticked) ?? atHead[0])?.line ?? `- [ ] **[live]** \`${command}\` — no passed run recorded at \`${live.head || "an unknown head"}\``;
6676
+ });
6677
+ return [...others, ...graded];
6678
+ }
6679
+ function evaluateTestPlanGate(body, branch, live) {
5781
6680
  if (!body) {
5782
6681
  return {
5783
6682
  verdict: "pass",
@@ -5788,7 +6687,9 @@ function evaluateTestPlanGate(body, branch) {
5788
6687
  };
5789
6688
  }
5790
6689
  const located = locateTestPlanSection(body);
5791
- if (!located.found) {
6690
+ const liveLines = gradedLiveLines(readLiveRecord(body), live);
6691
+ const liveUnticked = liveLines.some((line) => /^[-*]\s+\[\s\]/.test(line));
6692
+ if (!located.found && !liveUnticked) {
5792
6693
  if (parseTaskBranchIdentity(branch) !== null) {
5793
6694
  return {
5794
6695
  verdict: "fail",
@@ -5808,15 +6709,18 @@ function evaluateTestPlanGate(body, branch) {
5808
6709
  ]
5809
6710
  };
5810
6711
  }
5811
- const section = located.section;
5812
- if (/unit-tests-only/i.test(section)) {
6712
+ const section = located.found ? located.section : "";
6713
+ if (/unit-tests-only/i.test(section) && !liveUnticked) {
5813
6714
  return {
5814
6715
  verdict: "pass",
5815
6716
  messages: ["Test Plan: unit-tests-only — pure-logic brief, CI unit-tests are the proof.", "PASS."]
5816
6717
  };
5817
6718
  }
5818
- const checkboxLines = section.split(`
5819
- `).map((line) => line.trimStart()).filter((line) => /^[-*]\s+\[[ xX]\]\s*\*{0,2}\[principal\]\*{0,2}/i.test(line));
6719
+ const checkboxLines = [
6720
+ ...section.split(`
6721
+ `).map((line) => line.trimStart()).filter((line) => /^[-*]\s+\[[ xX]\]\s*\*{0,2}\[principal\]\*{0,2}/i.test(line)),
6722
+ ...liveLines
6723
+ ];
5820
6724
  if (checkboxLines.length === 0) {
5821
6725
  return {
5822
6726
  verdict: "pass",
@@ -5833,7 +6737,9 @@ function evaluateTestPlanGate(body, branch) {
5833
6737
  messages.push("", "FAIL — the following [principal] Test Plan items are unticked:");
5834
6738
  for (const line of unchecked)
5835
6739
  messages.push(` ${line}`);
5836
- 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.");
6740
+ 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 ? [
6741
+ "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."
6742
+ ] : [], "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.");
5837
6743
  return { verdict: "fail", messages };
5838
6744
  }
5839
6745
  messages.push("All [principal] Test Plan items ticked — runtime verification complete.", "PASS.");
@@ -6022,9 +6928,11 @@ var LineageSchema = z3.object({
6022
6928
  parent: z3.string().nullable()
6023
6929
  }).strict();
6024
6930
  var InputVersionsSchema = z3.object({
6931
+ manifest_version: z3.literal(2).nullable().optional(),
6025
6932
  objectives_version: z3.string().nullable(),
6026
6933
  brief_hash: z3.string().nullable(),
6027
6934
  ruling_ordinal: z3.number().int().nullable(),
6935
+ pause_bound_ruling: z3.object({ rulingId: z3.string().min(1), pauseId: z3.string().min(1), contentDigest: z3.string().min(1) }).strict().nullable().optional(),
6028
6936
  policy_digest: z3.string().nullable()
6029
6937
  }).strict();
6030
6938
  var ProvenanceSchema = z3.enum(["parent_attributed", "env_correlated", "self_reported", "unavailable"]);
@@ -6572,17 +7480,19 @@ function buildHeader(input) {
6572
7480
  parent: lineageFieldFromEnv(input.env.parent)
6573
7481
  },
6574
7482
  input_versions: {
7483
+ manifest_version: input.inputVersions?.manifestVersion ?? null,
6575
7484
  objectives_version: input.inputVersions?.objectivesVersion ?? null,
6576
7485
  brief_hash: input.inputVersions?.briefHash ?? null,
6577
7486
  ruling_ordinal: input.inputVersions?.rulingOrdinal ?? null,
7487
+ pause_bound_ruling: input.inputVersions?.pauseBoundRuling ?? null,
6578
7488
  policy_digest: input.inputVersions?.policyDigest ?? null
6579
7489
  },
6580
7490
  provenance: provenanceFor(input),
6581
7491
  work: {
6582
7492
  ref: lineageFieldFromEnv(input.env.workRef) ?? (issue === null ? null : String(issue)),
6583
7493
  repo: input.repo,
6584
- change: null,
6585
- revision: null
7494
+ change: pr === undefined ? null : String(pr),
7495
+ revision: input.revision ?? null
6586
7496
  },
6587
7497
  flow: {
6588
7498
  id: lineageFieldFromEnv(input.env.flow) ?? "vinaya",
@@ -6770,6 +7680,12 @@ var ManifestRecordSchema = z4.object({
6770
7680
  briefHash: z4.string().min(1).nullable(),
6771
7681
  objectivesVersion: z4.string().min(1).nullable(),
6772
7682
  rulingOrdinal: epochNumber,
7683
+ manifestVersion: z4.literal(2).optional(),
7684
+ pauseBoundRuling: z4.object({
7685
+ rulingId: z4.string().min(1),
7686
+ pauseId: z4.string().min(1),
7687
+ contentDigest: z4.string().min(1)
7688
+ }).strict().nullable().optional(),
6773
7689
  policyDigest: z4.string().min(1),
6774
7690
  recordedAt: isoTimestamp
6775
7691
  }).strict();
@@ -6791,7 +7707,11 @@ var LoopStateRecordSchema = z4.object({
6791
7707
  deliveredFindings: roundHeadIdentity.nullable(),
6792
7708
  repeatMemory: z4.object({
6793
7709
  blockingFindings: z4.array(z4.string()),
6794
- lastFailure: z4.object({ signature: z4.string(), message: z4.string() }).nullable()
7710
+ lastFailure: z4.object({ signature: z4.string(), message: z4.string(), developerAttemptedSince: z4.boolean().optional() }).nullable()
7711
+ }).strict().optional(),
7712
+ developerHandoff: z4.object({
7713
+ findings: z4.array(z4.object({ id: z4.string().min(1), description: z4.string().min(1) }).strict()),
7714
+ failingChecks: z4.array(z4.string().min(1))
6795
7715
  }).strict().optional(),
6796
7716
  publicationExpectedBase: z4.string().regex(/^[0-9a-f]{40}$/).nullable().optional(),
6797
7717
  taskStartedAt: isoTimestamp.optional(),
@@ -6854,29 +7774,313 @@ import { promisify as promisify4 } from "node:util";
6854
7774
  import { existsSync, mkdirSync, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync } from "node:fs";
6855
7775
  import { homedir } from "node:os";
6856
7776
  import { dirname, isAbsolute, join, resolve } from "node:path";
6857
- import { z as z5 } from "zod";
7777
+ import { z as z6 } from "zod";
6858
7778
 
6859
7779
  // src/lib/agent-vendors.ts
6860
7780
  var AGENT_VENDORS = ["skills", "claude", "gemini"];
6861
7781
 
7782
+ // src/lib/prose-rules-config.ts
7783
+ import safeRegex from "safe-regex2";
7784
+ import { z as z5 } from "zod";
7785
+ var SEVERITIES = ["error", "warning"];
7786
+ var OVERRIDE_KEYS = ["scopes", "severity", "exempt"];
7787
+ var FIXED_DEFAULT_KEYS = ["pattern", "patterns", "flags", "means", "message", "id"];
7788
+ var CUSTOM_KEYS = ["id", "pattern", "patterns", "flags", "means", "scopes", "severity", "exempt"];
7789
+ var DEFAULT_IDS = new Set([...DEFAULT_PROSE_RULES.map((rule) => rule.id), DECISION_RECORD_CITATION_ID]);
7790
+ function isPlainObject3(value) {
7791
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7792
+ }
7793
+ function outsideRepositoryReason(entry) {
7794
+ if (entry.startsWith("/") || /^[A-Za-z]:/.test(entry))
7795
+ return "must be a repository-relative path, not an absolute one";
7796
+ if (entry.split(/[\\/]/).includes(".."))
7797
+ return "must stay inside the repository — no `..` segment";
7798
+ return null;
7799
+ }
7800
+ var RepoRelativePathSchema = z5.string().min(1).superRefine((entry, ctx) => {
7801
+ const reason = outsideRepositoryReason(entry);
7802
+ if (reason)
7803
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, message: reason });
7804
+ });
7805
+ function pathListIssues(value, path, issues) {
7806
+ if (!Array.isArray(value)) {
7807
+ issues.push({ path, message: "must be a list of repository-relative paths" });
7808
+ return;
7809
+ }
7810
+ value.forEach((entry, index) => {
7811
+ if (typeof entry !== "string" || entry.length === 0) {
7812
+ issues.push({ path: [...path, index], message: "must be a non-empty repository-relative path" });
7813
+ return;
7814
+ }
7815
+ const reason = outsideRepositoryReason(entry);
7816
+ if (reason)
7817
+ issues.push({ path: [...path, index], message: reason });
7818
+ });
7819
+ }
7820
+ function scopeListIssues(value, path, allowed, issues) {
7821
+ if (!Array.isArray(value) || value.length === 0) {
7822
+ issues.push({ path, message: "must name at least one scope" });
7823
+ return null;
7824
+ }
7825
+ const scopes = [];
7826
+ value.forEach((scope, index) => {
7827
+ if (typeof scope !== "string" || !CONFIGURABLE_PROSE_SCOPES.includes(scope)) {
7828
+ issues.push({
7829
+ path: [...path, index],
7830
+ 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(", ")}`
7831
+ });
7832
+ return;
7833
+ }
7834
+ if (!allowed.includes(scope)) {
7835
+ issues.push({
7836
+ path: [...path, index],
7837
+ message: `scope "${scope}" is not one this rule can run in — it can run in: ${allowed.join(", ")}`
7838
+ });
7839
+ return;
7840
+ }
7841
+ scopes.push(scope);
7842
+ });
7843
+ return scopes;
7844
+ }
7845
+ function severityIssues(value, path, scopes, issues) {
7846
+ if (typeof value === "string") {
7847
+ if (!SEVERITIES.includes(value)) {
7848
+ issues.push({ path, message: `unknown severity ${JSON.stringify(value)} — use "error" or "warning"` });
7849
+ }
7850
+ return;
7851
+ }
7852
+ if (!isPlainObject3(value)) {
7853
+ issues.push({ path, message: 'must be "error", "warning", or a map from scope to one of them' });
7854
+ return;
7855
+ }
7856
+ for (const [scope, severity] of Object.entries(value)) {
7857
+ if (!scopes.includes(scope)) {
7858
+ issues.push({ path: [...path, scope], message: `names scope "${scope}", which this rule's scopes do not cover` });
7859
+ }
7860
+ if (typeof severity !== "string" || !SEVERITIES.includes(severity)) {
7861
+ issues.push({
7862
+ path: [...path, scope],
7863
+ message: `unknown severity ${JSON.stringify(severity)} — use "error" or "warning"`
7864
+ });
7865
+ }
7866
+ }
7867
+ }
7868
+ function patternIssues(source, flags, path, issues) {
7869
+ if (typeof source !== "string" || source.length === 0) {
7870
+ issues.push({ path, message: "must be a non-empty regular expression" });
7871
+ return;
7872
+ }
7873
+ if (source.length > CONFIGURED_PATTERN_MAX_LENGTH) {
7874
+ issues.push({
7875
+ path,
7876
+ message: `is ${source.length} characters, over the ${CONFIGURED_PATTERN_MAX_LENGTH}-character limit for a configured pattern`
7877
+ });
7878
+ return;
7879
+ }
7880
+ try {
7881
+ new RegExp(source, flags);
7882
+ } catch (err) {
7883
+ issues.push({ path, message: `does not compile: ${err.message}` });
7884
+ return;
7885
+ }
7886
+ if (!safeRegex(source, { limit: Number.MAX_SAFE_INTEGER })) {
7887
+ issues.push({
7888
+ path,
7889
+ 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."
7890
+ });
7891
+ }
7892
+ }
7893
+ function flagIssues(value, path, issues) {
7894
+ if (value === undefined)
7895
+ return "";
7896
+ if (typeof value !== "string") {
7897
+ issues.push({ path, message: 'must be a string of flags, e.g. "i"' });
7898
+ return "";
7899
+ }
7900
+ const seen = new Set;
7901
+ for (const flag of value) {
7902
+ if (!CONFIGURED_PROSE_FLAGS.includes(flag)) {
7903
+ issues.push({
7904
+ path,
7905
+ message: `unknown flag ${JSON.stringify(flag)} — only ${CONFIGURED_PROSE_FLAGS.map((f) => `"${f}"`).join(" and ")} are allowed`
7906
+ });
7907
+ return "";
7908
+ }
7909
+ if (seen.has(flag)) {
7910
+ issues.push({ path, message: `repeats the flag "${flag}"` });
7911
+ return "";
7912
+ }
7913
+ seen.add(flag);
7914
+ }
7915
+ return value;
7916
+ }
7917
+ function defaultsIssues(value, issues) {
7918
+ const base = ["defaults"];
7919
+ if (!isPlainObject3(value)) {
7920
+ issues.push({ path: base, message: 'must map a default rule id to "off" or an override' });
7921
+ return;
7922
+ }
7923
+ for (const [id, override] of Object.entries(value)) {
7924
+ const path = [...base, id];
7925
+ const rule = CONFIGURABLE_DEFAULT_RULES.find((candidate) => candidate.id === id);
7926
+ if (!rule) {
7927
+ issues.push({
7928
+ path,
7929
+ message: `unknown default rule id "${id}" — \`vinaya check --plan\` lists the rules each prose check runs`
7930
+ });
7931
+ continue;
7932
+ }
7933
+ if (override === "off")
7934
+ continue;
7935
+ if (!isPlainObject3(override)) {
7936
+ issues.push({ path, message: 'must be "off" or an object with any of scopes, severity, exempt' });
7937
+ continue;
7938
+ }
7939
+ for (const key of Object.keys(override)) {
7940
+ if (OVERRIDE_KEYS.includes(key))
7941
+ continue;
7942
+ issues.push({
7943
+ path: [...path, key],
7944
+ 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`
7945
+ });
7946
+ }
7947
+ const scopes = override.scopes === undefined ? [...rule.scopes] : scopeListIssues(override.scopes, [...path, "scopes"], allowedScopesFor(rule), issues);
7948
+ if (override.severity !== undefined && scopes)
7949
+ severityIssues(override.severity, [...path, "severity"], scopes, issues);
7950
+ if (override.exempt !== undefined)
7951
+ pathListIssues(override.exempt, [...path, "exempt"], issues);
7952
+ }
7953
+ }
7954
+ function customIssues(value, issues) {
7955
+ if (!Array.isArray(value)) {
7956
+ issues.push({ path: ["custom"], message: "must be a list of rules" });
7957
+ return;
7958
+ }
7959
+ const ids = new Set;
7960
+ value.forEach((rule, index) => {
7961
+ const path = ["custom", index];
7962
+ if (!isPlainObject3(rule)) {
7963
+ issues.push({ path, message: "must be a rule object" });
7964
+ return;
7965
+ }
7966
+ for (const key of Object.keys(rule)) {
7967
+ if (!CUSTOM_KEYS.includes(key)) {
7968
+ issues.push({ path: [...path, key], message: `unknown key "${key}" — a rule takes ${CUSTOM_KEYS.join(", ")}` });
7969
+ }
7970
+ }
7971
+ if (typeof rule.id !== "string" || rule.id.length === 0) {
7972
+ issues.push({ path: [...path, "id"], message: "a custom rule needs an id" });
7973
+ } else if (DEFAULT_IDS.has(rule.id)) {
7974
+ issues.push({
7975
+ path: [...path, "id"],
7976
+ message: `"${rule.id}" is a default rule id — a custom rule needs its own id; retune the default under proseGates.rules.defaults instead`
7977
+ });
7978
+ } else if (ids.has(rule.id)) {
7979
+ issues.push({ path: [...path, "id"], message: `"${rule.id}" is used by an earlier custom rule` });
7980
+ } else {
7981
+ ids.add(rule.id);
7982
+ }
7983
+ if (typeof rule.means !== "string" || rule.means.trim().length === 0) {
7984
+ issues.push({ path: [...path, "means"], message: "a custom rule needs a message (`means`)" });
7985
+ }
7986
+ let scopes = null;
7987
+ if (rule.scopes === undefined) {
7988
+ issues.push({ path: [...path, "scopes"], message: "a custom rule needs at least one scope (`scopes`)" });
7989
+ } else {
7990
+ scopes = scopeListIssues(rule.scopes, [...path, "scopes"], CONFIGURABLE_PROSE_SCOPES, issues);
7991
+ }
7992
+ if (scopes && new Set(scopes.map(groupOfScope)).size > 1) {
7993
+ issues.push({
7994
+ path: [...path, "scopes"],
7995
+ 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'
7996
+ });
7997
+ }
7998
+ const flags = flagIssues(rule.flags, [...path, "flags"], issues);
7999
+ if (rule.pattern === undefined && rule.patterns === undefined) {
8000
+ issues.push({
8001
+ path: [...path, "pattern"],
8002
+ message: "a custom rule needs a `pattern` or a per-scope `patterns` map"
8003
+ });
8004
+ }
8005
+ if (rule.pattern !== undefined)
8006
+ patternIssues(rule.pattern, flags, [...path, "pattern"], issues);
8007
+ if (rule.patterns !== undefined) {
8008
+ if (!isPlainObject3(rule.patterns)) {
8009
+ issues.push({ path: [...path, "patterns"], message: "must map a scope to a regular expression" });
8010
+ } else {
8011
+ for (const [scope, source] of Object.entries(rule.patterns)) {
8012
+ if (scopes && !scopes.includes(scope)) {
8013
+ issues.push({
8014
+ path: [...path, "patterns", scope],
8015
+ message: `names scope "${scope}", which this rule's scopes do not cover`
8016
+ });
8017
+ continue;
8018
+ }
8019
+ patternIssues(source, flags, [...path, "patterns", scope], issues);
8020
+ }
8021
+ if (rule.pattern === undefined && scopes) {
8022
+ for (const scope of scopes) {
8023
+ if (!(scope in rule.patterns)) {
8024
+ issues.push({
8025
+ path: [...path, "patterns"],
8026
+ message: `has no pattern for scope "${scope}" — add one, or a \`pattern\` every other scope uses`
8027
+ });
8028
+ }
8029
+ }
8030
+ }
8031
+ }
8032
+ }
8033
+ if (rule.severity !== undefined && scopes)
8034
+ severityIssues(rule.severity, [...path, "severity"], scopes, issues);
8035
+ if (rule.exempt !== undefined)
8036
+ pathListIssues(rule.exempt, [...path, "exempt"], issues);
8037
+ });
8038
+ }
8039
+ function proseRulesIssues(value) {
8040
+ const issues = [];
8041
+ if (!isPlainObject3(value))
8042
+ return [{ path: [], message: "must be an object with any of exempt, defaults, custom" }];
8043
+ for (const key of Object.keys(value)) {
8044
+ if (!["exempt", "defaults", "custom"].includes(key)) {
8045
+ issues.push({ path: [key], message: `unknown key "${key}" — proseGates.rules takes exempt, defaults and custom` });
8046
+ }
8047
+ }
8048
+ if (value.exempt !== undefined)
8049
+ pathListIssues(value.exempt, ["exempt"], issues);
8050
+ if (value.defaults !== undefined)
8051
+ defaultsIssues(value.defaults, issues);
8052
+ if (value.custom !== undefined)
8053
+ customIssues(value.custom, issues);
8054
+ return issues;
8055
+ }
8056
+ var ProseRulesSchema = z5.unknown().superRefine((value, ctx) => {
8057
+ for (const issue of proseRulesIssues(value)) {
8058
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, path: issue.path, message: issue.message });
8059
+ }
8060
+ }).transform((value) => value);
8061
+ var PublishedProseSchema = z5.object({
8062
+ allow: z5.array(z5.string().min(1)).optional()
8063
+ }).strict();
8064
+
6862
8065
  // src/lib/config.ts
6863
- var EnvEntrySchema = z5.union([
6864
- z5.literal(true),
6865
- z5.object({ optional: z5.literal(true) }),
6866
- z5.object({ anyOf: z5.array(z5.string()).min(2) }),
6867
- z5.string()
8066
+ var EnvEntrySchema = z6.union([
8067
+ z6.literal(true),
8068
+ z6.object({ optional: z6.literal(true) }),
8069
+ z6.object({ anyOf: z6.array(z6.string()).min(2) }),
8070
+ z6.string()
6868
8071
  ]);
6869
- var CheckEntrySchema = z5.object({
6870
- run: z5.string(),
6871
- scope: z5.enum(["diff", "full"]),
6872
- include: z5.array(z5.string()).optional(),
6873
- args: z5.array(z5.string()).optional(),
6874
- timeoutMs: z5.number().optional(),
6875
- env: z5.record(z5.string(), EnvEntrySchema).optional(),
6876
- requiresOpenPr: z5.boolean().optional(),
6877
- ownWorkflow: z5.boolean().optional(),
6878
- principalOwed: z5.literal(true).optional(),
6879
- validates: z5.enum(["body", "issue"]).optional()
8072
+ var CheckEntrySchema = z6.object({
8073
+ run: z6.string(),
8074
+ scope: z6.enum(["diff", "full"]),
8075
+ include: z6.array(z6.string()).optional(),
8076
+ args: z6.array(z6.string()).optional(),
8077
+ timeoutMs: z6.number().optional(),
8078
+ env: z6.record(z6.string(), EnvEntrySchema).optional(),
8079
+ requiresOpenPr: z6.boolean().optional(),
8080
+ ownWorkflow: z6.boolean().optional(),
8081
+ principalOwed: z6.literal(true).optional(),
8082
+ validates: z6.enum(["body", "issue"]).optional(),
8083
+ advisory: z6.literal(true).optional()
6880
8084
  }).superRefine((entry, ctx) => {
6881
8085
  if (!entry.env)
6882
8086
  return;
@@ -6886,22 +8090,22 @@ var CheckEntrySchema = z5.object({
6886
8090
  const members = value.anyOf;
6887
8091
  if (new Set(members).size !== members.length) {
6888
8092
  ctx.addIssue({
6889
- code: z5.ZodIssueCode.custom,
8093
+ code: z6.ZodIssueCode.custom,
6890
8094
  message: `env.${key}.anyOf has duplicate members`,
6891
8095
  path: ["env", key, "anyOf"]
6892
8096
  });
6893
8097
  }
6894
8098
  if (!members.includes(key)) {
6895
8099
  ctx.addIssue({
6896
- code: z5.ZodIssueCode.custom,
8100
+ code: z6.ZodIssueCode.custom,
6897
8101
  message: `env.${key}.anyOf must include "${key}" itself as a member`,
6898
8102
  path: ["env", key, "anyOf"]
6899
8103
  });
6900
8104
  }
6901
8105
  }
6902
8106
  });
6903
- var RoleEntrySchema = z5.object({
6904
- contract: z5.string().refine((p) => p.includes("/"), {
8107
+ var RoleEntrySchema = z6.object({
8108
+ contract: z6.string().refine((p) => p.includes("/"), {
6905
8109
  message: 'must be a path (contain at least one "/"), not a bare filename'
6906
8110
  })
6907
8111
  });
@@ -6925,17 +8129,17 @@ var BRIEF_BUILTINS = [
6925
8129
  "briefSections",
6926
8130
  "milestoneShape"
6927
8131
  ];
6928
- var BriefSectionSchema = z5.union([
6929
- z5.object({ builtin: z5.enum(BRIEF_BUILTINS) }),
6930
- z5.object({ heading: z5.string().min(1), name: z5.string().optional() }),
6931
- z5.object({ field: z5.string().min(1), name: z5.string().optional() }),
6932
- z5.object({ phrase: z5.string().min(1), name: z5.string().optional() })
8132
+ var BriefSectionSchema = z6.union([
8133
+ z6.object({ builtin: z6.enum(BRIEF_BUILTINS) }),
8134
+ z6.object({ heading: z6.string().min(1), name: z6.string().optional() }),
8135
+ z6.object({ field: z6.string().min(1), name: z6.string().optional() }),
8136
+ z6.object({ phrase: z6.string().min(1), name: z6.string().optional() })
6933
8137
  ]);
6934
- var BriefSchemaSchema = z5.object({
6935
- pr: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6936
- issue: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6937
- milestone: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6938
- ack: z5.array(z5.enum(BRIEF_BUILTINS)).optional()
8138
+ var BriefSchemaSchema = z6.object({
8139
+ pr: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8140
+ issue: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8141
+ milestone: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8142
+ ack: z6.array(z6.enum(BRIEF_BUILTINS)).optional()
6939
8143
  });
6940
8144
  function isSafeRepoRelPath(p) {
6941
8145
  if (p.length === 0)
@@ -6944,7 +8148,7 @@ function isSafeRepoRelPath(p) {
6944
8148
  return false;
6945
8149
  return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
6946
8150
  }
6947
- var SafeRepoRelPath = z5.string().refine(isSafeRepoRelPath, {
8151
+ var SafeRepoRelPath = z6.string().refine(isSafeRepoRelPath, {
6948
8152
  message: "must be a repo-root-relative path with no `..` segment or absolute root"
6949
8153
  });
6950
8154
  var CANONICAL_HOOK_BLOCK_PREFIXES = [".git/", ".husky/", ".vinaya/hooks/", ".claude/hooks/"];
@@ -6954,22 +8158,22 @@ function isCanonicalHookBlockPath(p) {
6954
8158
  var ManagedHookBlockPath = SafeRepoRelPath.refine(isCanonicalHookBlockPath, {
6955
8159
  message: `must start with one of ${CANONICAL_HOOK_BLOCK_PREFIXES.join(", ")} (byte-exact, case-sensitive)`
6956
8160
  });
6957
- var ManagedBlockRecordSchema = z5.object({
8161
+ var ManagedBlockRecordSchema = z6.object({
6958
8162
  path: ManagedHookBlockPath,
6959
- marker: z5.string(),
6960
- comment: z5.enum(["hash", "html"])
8163
+ marker: z6.string(),
8164
+ comment: z6.enum(["hash", "html"])
6961
8165
  });
6962
- var ManagedManifestSchema = z5.object({
6963
- version: z5.number().int().positive(),
6964
- files: z5.array(SafeRepoRelPath),
6965
- blocks: z5.array(ManagedBlockRecordSchema),
6966
- labels: z5.array(z5.string()),
6967
- agents: z5.array(z5.enum(AGENT_VENDORS)).optional()
8166
+ var ManagedManifestSchema = z6.object({
8167
+ version: z6.number().int().positive(),
8168
+ files: z6.array(SafeRepoRelPath),
8169
+ blocks: z6.array(ManagedBlockRecordSchema),
8170
+ labels: z6.array(z6.string()),
8171
+ agents: z6.array(z6.enum(AGENT_VENDORS)).optional()
6968
8172
  });
6969
- var ProjectEntrySchema = z5.object({
6970
- name: z5.string().min(1),
6971
- description: z5.string().min(1).optional(),
6972
- path: z5.string().min(1).optional()
8173
+ var ProjectEntrySchema = z6.object({
8174
+ name: z6.string().min(1),
8175
+ description: z6.string().min(1).optional(),
8176
+ path: z6.string().min(1).optional()
6973
8177
  });
6974
8178
  function parseTokensCollectDeclaration(value) {
6975
8179
  const m = value.trim().match(/^(\S+)\s+(\S+)$/);
@@ -6980,90 +8184,90 @@ function parseTokensCollectDeclaration(value) {
6980
8184
  return null;
6981
8185
  return { interpreter, script };
6982
8186
  }
6983
- var VinayaConfigSchema = z5.object({
6984
- rings: z5.object({
6985
- ring1_forgeWriteInterception: z5.boolean(),
6986
- ring2_asyncAudits: z5.boolean()
8187
+ var VinayaConfigObjectSchema = z6.object({
8188
+ rings: z6.object({
8189
+ ring1_forgeWriteInterception: z6.boolean(),
8190
+ ring2_asyncAudits: z6.boolean()
6987
8191
  }).optional(),
6988
- checks: z5.record(z5.string(), CheckEntrySchema).optional(),
6989
- roles: z5.record(z5.string(), RoleEntrySchema).optional(),
8192
+ checks: z6.record(z6.string(), CheckEntrySchema).optional(),
8193
+ roles: z6.record(z6.string(), RoleEntrySchema).optional(),
6990
8194
  briefSchema: BriefSchemaSchema.optional(),
6991
8195
  managed: ManagedManifestSchema.optional(),
6992
- principals: z5.array(z5.string()).min(1).optional(),
6993
- releaseActor: z5.string().min(1).optional(),
6994
- ci: z5.object({ setup: z5.string().min(1) }).optional(),
6995
- tokens: z5.object({
6996
- collect: z5.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
8196
+ principals: z6.array(z6.string()).min(1).optional(),
8197
+ releaseActor: z6.string().min(1).optional(),
8198
+ ci: z6.object({ setup: z6.string().min(1) }).optional(),
8199
+ tokens: z6.object({
8200
+ collect: z6.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
6997
8201
  message: 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
6998
8202
  })
6999
8203
  }).optional(),
7000
- blastRadius: z5.object({ extraDomains: z5.array(z5.string()).optional() }).optional(),
7001
- proseGates: z5.object({
7002
- doctrineRoot: z5.string().min(1).optional(),
7003
- readerFacingPrefix: z5.string().min(1).optional(),
7004
- readerFacingSuffix: z5.string().min(1).optional(),
7005
- legacySlugDir: z5.string().min(1).optional(),
7006
- sourceComments: z5.object({
7007
- globs: z5.array(z5.string().min(1)).optional(),
7008
- allowlist: z5.array(z5.string().min(1)).optional(),
7009
- severity: z5.enum(["warning", "error"]).optional()
8204
+ blastRadius: z6.object({ extraDomains: z6.array(z6.string()).optional() }).optional(),
8205
+ proseGates: z6.object({
8206
+ doctrineRoot: z6.string().min(1).optional(),
8207
+ readerFacingPrefix: z6.string().min(1).optional(),
8208
+ readerFacingSuffix: z6.string().min(1).optional(),
8209
+ legacySlugDir: z6.string().min(1).optional(),
8210
+ sourceComments: z6.object({
8211
+ globs: z6.array(z6.string().min(1)).optional(),
8212
+ allowlist: z6.array(z6.string().min(1)).optional(),
8213
+ severity: z6.enum(["warning", "error"]).optional()
7010
8214
  }).optional(),
7011
- specGrandfather: z5.union([z5.array(z5.string().min(1)), z5.record(z5.string().min(1), z5.number().int().min(0))]).optional(),
7012
- specPaths: z5.array(z5.string().min(1).refine((entry) => !entry.startsWith("/") && !/^[A-Za-z]:/.test(entry), {
7013
- message: "must be a repository-relative path, not an absolute one"
7014
- }).refine((entry) => !entry.split(/[\\/]/).includes(".."), {
7015
- message: "must stay inside the repository — no `..` segment"
7016
- })).optional()
8215
+ specGrandfather: z6.union([z6.array(z6.string().min(1)), z6.record(z6.string().min(1), z6.number().int().min(0))]).optional(),
8216
+ specPaths: z6.array(RepoRelativePathSchema).optional(),
8217
+ productPaths: z6.array(RepoRelativePathSchema).optional(),
8218
+ published: PublishedProseSchema.optional(),
8219
+ rules: ProseRulesSchema.optional()
7017
8220
  }).optional(),
7018
- projects: z5.array(ProjectEntrySchema).optional(),
7019
- dispatch: z5.object({
7020
- timeoutMs: z5.number().int().positive().optional(),
7021
- killGraceMs: z5.number().int().positive().optional(),
7022
- agent: z5.enum(["claude", "codex", "gemini"]).optional()
8221
+ projects: z6.array(ProjectEntrySchema).optional(),
8222
+ dispatch: z6.object({
8223
+ timeoutMs: z6.number().int().positive().optional(),
8224
+ reviewerTimeoutMs: z6.number().int().positive().optional(),
8225
+ killGraceMs: z6.number().int().positive().optional(),
8226
+ agent: z6.enum(["claude", "codex"]).optional()
7023
8227
  }).optional(),
7024
- reviewPolicy: z5.object({
7025
- codeReviewThreshold: z5.string().min(1).optional(),
7026
- securityThreshold: z5.string().min(1).optional(),
7027
- maxRounds: z5.number().optional(),
7028
- maxTaskMinutes: z5.number().optional()
8228
+ reviewPolicy: z6.object({
8229
+ codeReviewThreshold: z6.string().min(1).optional(),
8230
+ securityThreshold: z6.string().min(1).optional(),
8231
+ maxRounds: z6.number().optional(),
8232
+ maxTaskMinutes: z6.number().optional()
7029
8233
  }).optional(),
7030
- securityScan: z5.object({
7031
- command: z5.array(z5.string().min(1)).min(1)
8234
+ securityScan: z6.object({
8235
+ command: z6.array(z6.string().min(1)).min(1)
7032
8236
  }).optional(),
7033
- gateCutovers: z5.object({
7034
- objectivesSinceIssue: z5.number().int().nonnegative().optional(),
7035
- briefSectionsSinceIssue: z5.number().int().nonnegative().optional(),
7036
- documentationSinceIssue: z5.number().int().nonnegative().optional(),
7037
- briefRulesSincePr: z5.number().int().nonnegative().optional(),
7038
- agentBoxesRefusedSincePr: z5.number().int().nonnegative().optional()
8237
+ gateCutovers: z6.object({
8238
+ objectivesSinceIssue: z6.number().int().nonnegative().optional(),
8239
+ briefSectionsSinceIssue: z6.number().int().nonnegative().optional(),
8240
+ documentationSinceIssue: z6.number().int().nonnegative().optional(),
8241
+ briefRulesSincePr: z6.number().int().nonnegative().optional(),
8242
+ agentBoxesRefusedSincePr: z6.number().int().nonnegative().optional()
7039
8243
  }).optional(),
7040
- planning: z5.object({
7041
- collisionThreshold: z5.number().int().nonnegative().optional()
8244
+ planning: z6.object({
8245
+ collisionThreshold: z6.number().int().nonnegative().optional()
7042
8246
  }).optional(),
7043
- prePush: z5.object({
7044
- alwaysRun: z5.array(z5.string()).optional()
8247
+ prePush: z6.object({
8248
+ alwaysRun: z6.array(z6.string()).optional()
7045
8249
  }).optional(),
7046
- report: z5.object({
7047
- commandTimeoutMs: z5.number().int().positive().optional()
8250
+ report: z6.object({
8251
+ commandTimeoutMs: z6.number().int().positive().optional()
7048
8252
  }).superRefine((report, ctx) => {
7049
8253
  const commandTimeoutMs = report.commandTimeoutMs;
7050
8254
  if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
7051
8255
  ctx.addIssue({
7052
- code: z5.ZodIssueCode.custom,
8256
+ code: z6.ZodIssueCode.custom,
7053
8257
  path: ["commandTimeoutMs"],
7054
8258
  message: "must be at most 3600000 (1 hour)"
7055
8259
  });
7056
8260
  }
7057
8261
  }).optional(),
7058
- logPublish: z5.unknown().refine((v) => v === undefined, {
8262
+ logPublish: z6.unknown().refine((v) => v === undefined, {
7059
8263
  message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
7060
8264
  }),
7061
- runtimeDir: z5.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
7062
- logs: z5.object({
7063
- folder: z5.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
7064
- url: z5.string().url().optional(),
7065
- headers: z5.record(z5.string()).optional(),
7066
- readHeaders: z5.record(z5.string()).optional(),
8265
+ runtimeDir: z6.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
8266
+ logs: z6.object({
8267
+ folder: z6.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
8268
+ url: z6.string().url().optional(),
8269
+ headers: z6.record(z6.string()).optional(),
8270
+ readHeaders: z6.record(z6.string()).optional(),
7067
8271
  events: CustomEventDeclarationsSchema.optional()
7068
8272
  }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
7069
8273
  message: "logs: set at most one of folder/url"
@@ -7071,8 +8275,33 @@ var VinayaConfigSchema = z5.object({
7071
8275
  message: "logs: headers requires url"
7072
8276
  }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
7073
8277
  message: "logs: readHeaders requires url"
7074
- }).optional()
8278
+ }).optional(),
8279
+ decisionRecords: z6.object({
8280
+ path: RepoRelativePathSchema
8281
+ }).strict().optional()
8282
+ });
8283
+ function decisionRecordsPathIssue(path, doctrineRoot) {
8284
+ const reason = outsideRepositoryReason(path);
8285
+ if (reason)
8286
+ return reason;
8287
+ const folder = normalizeSpecPath(path);
8288
+ if (folder === "" || folder === ".")
8289
+ return "must name a folder, not the repository root";
8290
+ const root = normalizeSpecPath(doctrineRoot ?? "aeg-root");
8291
+ if (folder === root || folder.startsWith(`${root}/`)) {
8292
+ return `must be outside the doctrine tree "${root}" — decision records belong to this repository, not to the doctrine it ships`;
8293
+ }
8294
+ return null;
8295
+ }
8296
+ var VinayaConfigSchema = VinayaConfigObjectSchema.superRefine((config, ctx) => {
8297
+ const path = config.decisionRecords?.path;
8298
+ if (path === undefined || outsideRepositoryReason(path))
8299
+ return;
8300
+ const issue = decisionRecordsPathIssue(path, config.proseGates?.doctrineRoot);
8301
+ if (issue)
8302
+ ctx.addIssue({ code: z6.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
7075
8303
  });
8304
+ var VinayaConfigShape = VinayaConfigObjectSchema.shape;
7076
8305
  var GLOBAL_VINAYA_HOME = join(homedir(), ".vinaya");
7077
8306
  var GLOBAL_CONFIG_PATH = join(GLOBAL_VINAYA_HOME, "config.json");
7078
8307
  var LOCAL_CONFIG_FILENAME = "vinaya.config.json";
@@ -7153,9 +8382,6 @@ function stripGlobalOnlyKeys(config, path) {
7153
8382
  }
7154
8383
  return result;
7155
8384
  }
7156
- function resolvePrincipalAllowlist(config) {
7157
- return config?.principals ?? PRINCIPAL_ALLOWLIST;
7158
- }
7159
8385
  function resolveReleaseActor(config) {
7160
8386
  return config?.releaseActor ?? DEFAULT_RELEASE_ACTOR;
7161
8387
  }
@@ -7291,13 +8517,14 @@ function readTrustAnchorConfigAtRef(ref) {
7291
8517
  });
7292
8518
  return Buffer.from(raw, "utf-8").toString("base64");
7293
8519
  }
8520
+ var NO_TRUST_ANCHOR_REPO_MESSAGE = "could not resolve repo identity for the trust-anchor read";
7294
8521
  function ghFetchTrustAnchorConfig() {
7295
8522
  const probeRef = resolveCiTrustAnchorProbeRef();
7296
8523
  if (probeRef)
7297
8524
  return readTrustAnchorConfigAtRef(probeRef);
7298
8525
  const repo = trustAnchorRepo();
7299
8526
  if (!repo)
7300
- throw new Error("could not resolve repo identity for the trust-anchor read");
8527
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
7301
8528
  return execFileSync2("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
7302
8529
  encoding: "utf-8",
7303
8530
  stdio: ["ignore", "pipe", "pipe"]
@@ -7314,7 +8541,7 @@ async function ghFetchTrustAnchorConfigAsync() {
7314
8541
  }
7315
8542
  const repo = await trustAnchorRepoAsync();
7316
8543
  if (!repo)
7317
- throw new Error("could not resolve repo identity for the trust-anchor read");
8544
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
7318
8545
  const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4, killSignal: "SIGKILL" });
7319
8546
  return stdout;
7320
8547
  }
@@ -7340,6 +8567,47 @@ function loadTrustAnchorConfig(fetcher = ghFetchTrustAnchorConfig) {
7340
8567
  }
7341
8568
  return parseTrustAnchorContent(base64);
7342
8569
  }
8570
+ class PrincipalsUnresolvedError extends Error {
8571
+ kind;
8572
+ constructor(kind, message) {
8573
+ super(message);
8574
+ this.name = "PrincipalsUnresolvedError";
8575
+ this.kind = kind;
8576
+ }
8577
+ }
8578
+ var PRINCIPALS_FIX = 'add "principals": [...] to vinaya.config.json on the default branch';
8579
+ function fetchFailureReason(err) {
8580
+ const stderr = err?.stderr;
8581
+ const text = (typeof stderr === "string" ? stderr : stderr?.toString() ?? "").trim();
8582
+ return text.split(`
8583
+ `)[0]?.trim() || firstLine(err);
8584
+ }
8585
+ function principalsNotConfigured(why) {
8586
+ return new PrincipalsUnresolvedError("not-configured", `no Principal is configured (${why}) — ${PRINCIPALS_FIX}.`);
8587
+ }
8588
+ function resolveTrustedPrincipals(fetcher = ghFetchTrustAnchorConfig) {
8589
+ let content;
8590
+ try {
8591
+ content = fetcher();
8592
+ } catch (err) {
8593
+ if (err?.message === NO_TRUST_ANCHOR_REPO_MESSAGE) {
8594
+ throw principalsNotConfigured("no repository resolves for the read");
8595
+ }
8596
+ if (isMissingFileError(err))
8597
+ throw principalsNotConfigured("the default branch has no vinaya.config.json");
8598
+ throw new PrincipalsUnresolvedError("read-failed", `could not read "principals" from vinaya.config.json on the default branch: ${fetchFailureReason(err)}`);
8599
+ }
8600
+ const unusable = { why: "" };
8601
+ const config = parseTrustAnchorContent(content, (why) => {
8602
+ unusable.why = why;
8603
+ });
8604
+ if (config === null) {
8605
+ throw principalsNotConfigured(`vinaya.config.json on the default branch ${unusable.why ? `is unusable: ${unusable.why}` : "is empty"}`);
8606
+ }
8607
+ if (!config.principals)
8608
+ throw principalsNotConfigured('vinaya.config.json on the default branch sets no "principals"');
8609
+ return config.principals;
8610
+ }
7343
8611
  async function loadTrustAnchorConfigAsync(fetcher = ghFetchTrustAnchorConfigAsync, options = {}) {
7344
8612
  const warn = options.quiet ? () => {} : warnTrustAnchorFallback;
7345
8613
  let base64;
@@ -7379,17 +8647,183 @@ function loadConfig() {
7379
8647
  const path = configPath();
7380
8648
  if (!path)
7381
8649
  return null;
8650
+ let text;
7382
8651
  try {
7383
- const raw = JSON.parse(readFileSync2(path, "utf-8"));
7384
- return stripGlobalOnlyKeys(VinayaConfigSchema.parse(raw), path);
7385
- } catch {
8652
+ text = readFileSync2(path, "utf-8");
8653
+ } catch (err) {
8654
+ reportInvalidConfigOnce(path, `unreadable: ${err.message}`);
8655
+ return null;
8656
+ }
8657
+ let raw;
8658
+ try {
8659
+ raw = JSON.parse(text);
8660
+ } catch (err) {
8661
+ reportInvalidConfigOnce(path, `invalid JSON: ${err.message}`);
7386
8662
  return null;
7387
8663
  }
8664
+ const parsed = VinayaConfigSchema.safeParse(raw);
8665
+ if (!parsed.success) {
8666
+ reportInvalidConfigOnce(path, schemaIssueDetail(parsed.error));
8667
+ return null;
8668
+ }
8669
+ return stripGlobalOnlyKeys(parsed.data, path);
8670
+ }
8671
+ function schemaIssueDetail(error) {
8672
+ return error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
8673
+ }
8674
+ var emittedInvalidConfigReports = new Set;
8675
+ function reportInvalidConfigOnce(path, detail) {
8676
+ const key = `${path}
8677
+ ${detail}`;
8678
+ if (emittedInvalidConfigReports.has(key))
8679
+ return;
8680
+ emittedInvalidConfigReports.add(key);
8681
+ const message = `${path} is not a valid Vinaya configuration (${detail}) — falling back to built-in defaults.`;
8682
+ const checkName = process.env.VINAYA_CHECK_NAME;
8683
+ if (checkName) {
8684
+ emitCheckError({
8685
+ schema: CHECK_SCHEMA_VERSION,
8686
+ check: checkName,
8687
+ severity: "warning",
8688
+ message,
8689
+ agent_recovery_prompt: `Fix the failing keys in ${path} (${detail}) so the file parses and satisfies the configuration schema, then re-run.`,
8690
+ file: path
8691
+ });
8692
+ return;
8693
+ }
8694
+ console.error(`⚠ ${message}`);
8695
+ }
8696
+ function loadConfigChecked() {
8697
+ const path = configPath();
8698
+ if (!path)
8699
+ return { ok: true, config: null };
8700
+ let raw;
8701
+ try {
8702
+ raw = JSON.parse(readFileSync2(path, "utf-8"));
8703
+ } catch (err) {
8704
+ return { ok: false, path, error: `invalid JSON: ${err.message}` };
8705
+ }
8706
+ const parsed = VinayaConfigSchema.safeParse(raw);
8707
+ if (!parsed.success) {
8708
+ return { ok: false, path, error: schemaIssueDetail(parsed.error) };
8709
+ }
8710
+ return { ok: true, config: stripGlobalOnlyKeys(parsed.data, path) };
7388
8711
  }
7389
8712
  var TOKENS_COLLECT_TRUST_PATH = join(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
7390
8713
 
7391
8714
  // src/lib/forge-read.ts
7392
8715
  import { execFileSync as execFileSync3 } from "node:child_process";
8716
+
8717
+ // src/lib/forge-snapshot.ts
8718
+ import { existsSync as existsSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
8719
+ import { join as join2 } from "node:path";
8720
+ var FORGE_SNAPSHOT_DIR_ENV = "VINAYA_FORGE_SNAPSHOT_DIR";
8721
+ var PULL_FILE = "pull.json";
8722
+ var PULL_COMMENTS_FILE = "pull-comments.json";
8723
+ var ISSUE_FILE = "issue.json";
8724
+ var ISSUE_COMMENTS_FILE = "issue-comments.json";
8725
+ function forgeSnapshotDir(env = process.env) {
8726
+ if (env.GITHUB_ACTIONS !== "true")
8727
+ return null;
8728
+ const dir = env[FORGE_SNAPSHOT_DIR_ENV];
8729
+ return dir ? dir : null;
8730
+ }
8731
+
8732
+ class ForgeSnapshotIncompleteError extends Error {
8733
+ constructor(dir, file) {
8734
+ 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.`);
8735
+ this.name = "ForgeSnapshotIncompleteError";
8736
+ }
8737
+ }
8738
+
8739
+ class ForgeSnapshotIssueNotFoundError extends Error {
8740
+ constructor(issue) {
8741
+ super(`Issue #${issue} did not resolve (HTTP 404) when this run's forge snapshot was read.`);
8742
+ this.name = "ForgeSnapshotIssueNotFoundError";
8743
+ }
8744
+ }
8745
+ function readSnapshotFile(dir, file) {
8746
+ let text;
8747
+ try {
8748
+ text = readFileSync3(join2(dir, file), "utf8");
8749
+ } catch {
8750
+ throw new ForgeSnapshotIncompleteError(dir, file);
8751
+ }
8752
+ return JSON.parse(text);
8753
+ }
8754
+ function readComments(dir, file, number) {
8755
+ const parsed = readSnapshotFile(dir, file);
8756
+ if (parsed.number !== number)
8757
+ throw new ForgeSnapshotIncompleteError(dir, `${file} for #${number}`);
8758
+ return parsed.comments;
8759
+ }
8760
+ function snapshotPullRequest(number, env = process.env) {
8761
+ const dir = forgeSnapshotDir(env);
8762
+ if (dir === null)
8763
+ return null;
8764
+ const pull = readSnapshotFile(dir, PULL_FILE);
8765
+ return pull.number === number ? pull : null;
8766
+ }
8767
+ function snapshotIssue(number, env = process.env) {
8768
+ const dir = forgeSnapshotDir(env);
8769
+ if (dir === null)
8770
+ return null;
8771
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
8772
+ if (issue.number !== number)
8773
+ return null;
8774
+ if ("notFound" in issue)
8775
+ throw new ForgeSnapshotIssueNotFoundError(number);
8776
+ return issue;
8777
+ }
8778
+ function snapshotComments(number, env = process.env) {
8779
+ const dir = forgeSnapshotDir(env);
8780
+ if (dir === null)
8781
+ return null;
8782
+ if (snapshotPullRequest(number, env) !== null)
8783
+ return readComments(dir, PULL_COMMENTS_FILE, number);
8784
+ if (snapshotIssue(number, env) !== null)
8785
+ return readComments(dir, ISSUE_COMMENTS_FILE, number);
8786
+ return null;
8787
+ }
8788
+ function snapshotBody(number, env = process.env) {
8789
+ const pull = snapshotPullRequest(number, env);
8790
+ if (pull !== null)
8791
+ return pull.body;
8792
+ return snapshotIssue(number, env)?.body ?? null;
8793
+ }
8794
+ function incompleteForgeSnapshot(env = process.env) {
8795
+ const dir = forgeSnapshotDir(env);
8796
+ if (dir === null)
8797
+ return null;
8798
+ for (const file of [PULL_FILE, PULL_COMMENTS_FILE, ISSUE_FILE]) {
8799
+ if (!existsSync2(join2(dir, file)))
8800
+ return new ForgeSnapshotIncompleteError(dir, file).message;
8801
+ }
8802
+ try {
8803
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
8804
+ if (typeof issue.number === "number" && !("notFound" in issue) && !existsSync2(join2(dir, ISSUE_COMMENTS_FILE))) {
8805
+ return new ForgeSnapshotIncompleteError(dir, ISSUE_COMMENTS_FILE).message;
8806
+ }
8807
+ } catch (err) {
8808
+ return `the forge snapshot ${dir} has an unreadable ${ISSUE_FILE}: ${err.message}`;
8809
+ }
8810
+ return null;
8811
+ }
8812
+ function exitOnIncompleteForgeSnapshot(checkName, env = process.env) {
8813
+ const reason = incompleteForgeSnapshot(env);
8814
+ if (reason === null)
8815
+ return;
8816
+ emitCheckError({
8817
+ schema: CHECK_SCHEMA_VERSION,
8818
+ check: checkName,
8819
+ severity: "error",
8820
+ message: `${checkName}: ${reason}`,
8821
+ 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.`
8822
+ });
8823
+ process.exit(1);
8824
+ }
8825
+
8826
+ // src/lib/forge-read.ts
7393
8827
  var FORGE_READ_CEILING_BYTES = 64 * 1024 * 1024;
7394
8828
  var PAGE_SIZE = 100;
7395
8829
  var ghRunner = (args, maxBuffer) => execFileSync3("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer });
@@ -7412,7 +8846,7 @@ function isForgeReadOversize(err) {
7412
8846
  function isBufferOverflow(err) {
7413
8847
  return err?.code === "ENOBUFS";
7414
8848
  }
7415
- function run2(runner, args, subject, usedBytes) {
8849
+ function runBounded(runner, args, subject, usedBytes) {
7416
8850
  const remaining = FORGE_READ_CEILING_BYTES - usedBytes;
7417
8851
  let out;
7418
8852
  try {
@@ -7427,31 +8861,40 @@ function run2(runner, args, subject, usedBytes) {
7427
8861
  throw new ForgeReadOversizeError(subject, usedBytes + size);
7428
8862
  return out;
7429
8863
  }
7430
- function readIssueComments(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
7431
- const number = resolveNumber(issue, subjectLabel, runner);
7432
- const comments = [];
8864
+ function readRestCommentRows(number, subjectLabel = `Issue ${number}`, runner = ghRunner) {
8865
+ const rows = [];
7433
8866
  let used = 0;
7434
8867
  for (let page = 1;; page++) {
7435
- const out = run2(runner, ["api", `repos/{owner}/{repo}/issues/${number}/comments?per_page=${PAGE_SIZE}&page=${page}`], subjectLabel, used);
8868
+ const out = runBounded(runner, ["api", `repos/{owner}/{repo}/issues/${number}/comments?per_page=${PAGE_SIZE}&page=${page}`], subjectLabel, used);
7436
8869
  used += Buffer.byteLength(out, "utf8");
7437
- const rows = JSON.parse(out);
7438
- for (const r of rows) {
7439
- comments.push({
7440
- body: r.body ?? "",
7441
- url: r.html_url ?? "",
7442
- author: r.user?.login ? { login: r.user.login } : null
7443
- });
7444
- }
7445
- if (rows.length < PAGE_SIZE)
7446
- return comments;
8870
+ const pageRows = JSON.parse(out);
8871
+ rows.push(...pageRows);
8872
+ if (pageRows.length < PAGE_SIZE)
8873
+ return rows;
7447
8874
  }
7448
8875
  }
8876
+ function readIssueComments(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
8877
+ const number = resolveNumber(issue, subjectLabel, runner);
8878
+ const fromSnapshot = snapshotComments(number);
8879
+ if (fromSnapshot !== null)
8880
+ return fromSnapshot;
8881
+ return readRestCommentRows(number, subjectLabel, runner).map((r) => ({
8882
+ body: r.body ?? "",
8883
+ url: r.html_url ?? "",
8884
+ author: r.user?.login ? { login: r.user.login } : null
8885
+ }));
8886
+ }
7449
8887
  function readIssueBody(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
7450
- const out = run2(runner, ["issue", "view", String(issue), "--json", "body"], subjectLabel, 0);
8888
+ if (forgeSnapshotDir() !== null) {
8889
+ const fromSnapshot = snapshotBody(resolveNumber(issue, subjectLabel, runner));
8890
+ if (fromSnapshot !== null)
8891
+ return fromSnapshot;
8892
+ }
8893
+ const out = runBounded(runner, ["issue", "view", String(issue), "--json", "body"], subjectLabel, 0);
7451
8894
  return JSON.parse(out).body ?? "";
7452
8895
  }
7453
8896
  function readIssueFields(issue, fields, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
7454
- return JSON.parse(run2(runner, ["issue", "view", String(issue), "--json", fields], subjectLabel, 0));
8897
+ return JSON.parse(runBounded(runner, ["issue", "view", String(issue), "--json", fields], subjectLabel, 0));
7455
8898
  }
7456
8899
  function resolveNumber(issue, subjectLabel, runner) {
7457
8900
  if (typeof issue === "number")
@@ -7462,9 +8905,9 @@ function resolveNumber(issue, subjectLabel, runner) {
7462
8905
  }
7463
8906
 
7464
8907
  // src/lib/brief-assembly.ts
7465
- import { execFileSync as execFileSync6 } from "node:child_process";
7466
- import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2 } from "node:fs";
7467
- import { join as join4 } from "node:path";
8908
+ import { execFileSync as execFileSync7 } from "node:child_process";
8909
+ import { existsSync as existsSync5, readFileSync as readFileSync5, readdirSync as readdirSync2 } from "node:fs";
8910
+ import { join as join5 } from "node:path";
7468
8911
 
7469
8912
  // ../../packages/sources/src/commands.ts
7470
8913
  var COMMANDS = [
@@ -7580,6 +9023,16 @@ var COMMANDS = [
7580
9023
  ],
7581
9024
  status: "shipped"
7582
9025
  },
9026
+ {
9027
+ name: "new adr",
9028
+ needs: [],
9029
+ description: "Write the next numbered decision record into the folder decisionRecords.path names",
9030
+ details: [
9031
+ "`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.",
9032
+ "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."
9033
+ ],
9034
+ status: "shipped"
9035
+ },
7583
9036
  {
7584
9037
  name: "brief render",
7585
9038
  needs: ["forge", "default-branch"],
@@ -7598,9 +9051,7 @@ var COMMANDS = [
7598
9051
  name: "task dispatch",
7599
9052
  needs: ["forge", "operator-seat"],
7600
9053
  description: "Deprecated — render, pin, and post the brief on the Issue as the frozen original; start the developer",
7601
- flags: [
7602
- { flag: "--agent <claude|codex|gemini>", description: "Start the developer through dispatchRole once posted" }
7603
- ],
9054
+ flags: [{ flag: "--agent <claude|codex>", description: "Start the developer through dispatchRole once posted" }],
7604
9055
  details: [
7605
9056
  "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.",
7606
9057
  "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.",
@@ -7625,7 +9076,7 @@ var COMMANDS = [
7625
9076
  description: "One command from a planned Issue to a reviewed pull request — exactly one developer started",
7626
9077
  flags: [
7627
9078
  {
7628
- flag: "--agent <claude|codex|gemini>",
9079
+ flag: "--agent <claude|codex>",
7629
9080
  description: "Vendor for the developer and both reviewers this run dispatches"
7630
9081
  },
7631
9082
  {
@@ -7800,6 +9251,22 @@ var COMMANDS = [
7800
9251
  ],
7801
9252
  status: "shipped"
7802
9253
  },
9254
+ {
9255
+ name: "pr snapshot",
9256
+ needs: ["forge"],
9257
+ description: "CI plumbing: write a run's forge snapshot of the pull request and its task Issue, read over REST",
9258
+ flags: [
9259
+ {
9260
+ flag: "--dir",
9261
+ description: "The snapshot directory; its `raw/` holds the REST pull request and comment pages the read step wrote"
9262
+ }
9263
+ ],
9264
+ details: [
9265
+ "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.",
9266
+ "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."
9267
+ ],
9268
+ status: "shipped"
9269
+ },
7803
9270
  {
7804
9271
  name: "issue create",
7805
9272
  needs: ["forge"],
@@ -7920,14 +9387,14 @@ var COMMANDS = [
7920
9387
  {
7921
9388
  name: "milestone close",
7922
9389
  needs: ["forge"],
7923
- description: "Close a tranche's Milestone after verifying every labeled Issue is actually attached",
9390
+ description: "Close a tranche's Milestone after verifying every labeled Issue is attached and every tranche it declares is complete",
7924
9391
  flags: [
7925
9392
  { flag: "--slug", description: "The tranche whose Milestone is being closed" },
7926
9393
  { flag: "--validate-only", description: "Run every gate and report PASS without closing the Milestone" },
7927
9394
  { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
7928
9395
  ],
7929
9396
  details: [
7930
- "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."
9397
+ "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."
7931
9398
  ],
7932
9399
  status: "shipped"
7933
9400
  },
@@ -8216,7 +9683,7 @@ var COMMANDS = [
8216
9683
  }
8217
9684
  ],
8218
9685
  details: [
8219
- "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.",
9686
+ "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.",
8220
9687
  "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.",
8221
9688
  '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.'
8222
9689
  ],
@@ -8225,11 +9692,11 @@ var COMMANDS = [
8225
9692
  {
8226
9693
  name: "dispatch",
8227
9694
  needs: ["operator-seat"],
8228
- description: "Start a role's headless agent session (claude/codex/gemini) with attribution set on its environment, recording the outcome through the Vinaya Log",
9695
+ description: "Start a role's headless agent session (claude/codex) with attribution set on its environment, recording the outcome through the Vinaya Log",
8229
9696
  flags: [
8230
9697
  {
8231
9698
  flag: "--agent",
8232
- description: "Vendor to start: `claude`, `codex`, or `gemini` (falls back to `dispatch.agent` in config)"
9699
+ description: "Vendor to start: `claude` or `codex` (falls back to `dispatch.agent` in config)"
8233
9700
  },
8234
9701
  { flag: "--prompt-file", description: "Path to the prompt text sent to the agent (never on argv)" },
8235
9702
  { flag: "--task", description: "This dispatch's task Issue number — mutually exclusive with `--pr`" },
@@ -8246,9 +9713,9 @@ var COMMANDS = [
8246
9713
  ],
8247
9714
  details: [
8248
9715
  "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.",
8249
- "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`.",
9716
+ "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`.",
8250
9717
  "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.",
8251
- "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."
9718
+ "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."
8252
9719
  ],
8253
9720
  status: "shipped"
8254
9721
  },
@@ -8259,7 +9726,7 @@ var COMMANDS = [
8259
9726
  flags: [
8260
9727
  { flag: "--task <n>", description: "This task's Issue number — its frozen `aeg:brief:v1` comment is the brief" },
8261
9728
  {
8262
- flag: "--agent <claude|codex|gemini>",
9729
+ flag: "--agent <claude|codex>",
8263
9730
  description: "Vendor for every dispatch this loop makes (falls back to `dispatch.agent` in config)"
8264
9731
  },
8265
9732
  { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
@@ -8338,22 +9805,72 @@ function createForgeSource(config) {
8338
9805
  };
8339
9806
  }
8340
9807
  // ../../packages/sources/src/select-source.ts
8341
- import { z as z6 } from "zod";
8342
- var StateSourceConfigSchema = z6.discriminatedUnion("kind", [
8343
- z6.object({ kind: z6.literal("forge"), owner: z6.string(), repo: z6.string() }),
8344
- z6.object({ kind: z6.literal("file"), root: z6.string().optional() })
9808
+ import { z as z7 } from "zod";
9809
+ var StateSourceConfigSchema = z7.discriminatedUnion("kind", [
9810
+ z7.object({ kind: z7.literal("forge"), owner: z7.string(), repo: z7.string() }),
9811
+ z7.object({ kind: z7.literal("file"), root: z7.string().optional() })
8345
9812
  ]);
8346
9813
  // src/checks/edge-resolve.ts
9814
+ import { execFileSync as execFileSync5 } from "node:child_process";
9815
+
9816
+ // src/lib/github-rate-limit.ts
8347
9817
  import { execFileSync as execFileSync4 } from "node:child_process";
9818
+ var GITHUB_RATE_LIMIT_WORDING = /api rate limit (?:already )?exceeded|secondary rate limit|rate limit exceeded/i;
9819
+ var SECONDARY_RATE_LIMIT_WORDING = /secondary rate limit/i;
9820
+ function isGithubRateLimitError(text) {
9821
+ return GITHUB_RATE_LIMIT_WORDING.test(text);
9822
+ }
9823
+ function rateLimitBudget(errorText) {
9824
+ return errorText.trimStart().startsWith("GraphQL:") ? "GraphQL" : "REST";
9825
+ }
9826
+ var defaultReader = () => execFileSync4("gh", ["api", "rate_limit"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
9827
+ function readRateLimitReset(budget, read = defaultReader) {
9828
+ let parsed;
9829
+ try {
9830
+ parsed = JSON.parse(read());
9831
+ } catch {
9832
+ return null;
9833
+ }
9834
+ const resources = parsed.resources;
9835
+ const entry = resources?.[budget === "GraphQL" ? "graphql" : "core"];
9836
+ if (!entry || typeof entry.reset !== "number" || !Number.isFinite(entry.reset) || entry.reset <= 0)
9837
+ return null;
9838
+ if (typeof entry.remaining === "number" && entry.remaining > 0)
9839
+ return null;
9840
+ return entry.reset;
9841
+ }
9842
+ function formatResetUtc(epochSeconds) {
9843
+ const d = new Date(epochSeconds * 1000);
9844
+ const hh = String(d.getUTCHours()).padStart(2, "0");
9845
+ const mm = String(d.getUTCMinutes()).padStart(2, "0");
9846
+ return `${hh}:${mm} UTC`;
9847
+ }
9848
+ function rateLimitMessage(errorText, read = defaultReader) {
9849
+ const budget = rateLimitBudget(errorText);
9850
+ const reset = SECONDARY_RATE_LIMIT_WORDING.test(errorText) ? null : readRateLimitReset(budget, read);
9851
+ const when = reset === null ? "resets in a few minutes" : `resets at ${formatResetUtc(reset)}`;
9852
+ return `GitHub rate limit (${budget}), ${when}`;
9853
+ }
9854
+ function execErrorText(err) {
9855
+ const e = err;
9856
+ const stderr = e?.stderr === undefined || e.stderr === null ? "" : String(e.stderr);
9857
+ const message = typeof e?.message === "string" ? e.message : "";
9858
+ return stderr.trim() !== "" ? `${stderr}
9859
+ ${message}` : message;
9860
+ }
9861
+
9862
+ // src/checks/edge-resolve.ts
8348
9863
  var DIRECT_ISSUE_REF = /#(\d+)/;
8349
9864
  var issueCache = new Map;
9865
+ var ISSUE_NOT_FOUND = /could not resolve to an issue/i;
8350
9866
  function fetchIssueState(num, repo) {
8351
9867
  const key = `${repo.owner}/${repo.repo}#${num}`;
8352
- if (issueCache.has(key))
8353
- return issueCache.get(key) ?? null;
8354
- let out = null;
9868
+ const cached = issueCache.get(key);
9869
+ if (cached)
9870
+ return cached;
9871
+ let out;
8355
9872
  try {
8356
- const raw = execFileSync4("gh", [
9873
+ const raw = execFileSync5("gh", [
8357
9874
  "issue",
8358
9875
  "view",
8359
9876
  String(num),
@@ -8362,9 +9879,9 @@ function fetchIssueState(num, repo) {
8362
9879
  "--json",
8363
9880
  "state,stateReason,closedByPullRequestsReferences"
8364
9881
  ], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
8365
- out = JSON.parse(raw);
8366
- } catch {
8367
- out = null;
9882
+ out = { json: JSON.parse(raw), readFailed: false };
9883
+ } catch (err) {
9884
+ out = { json: null, readFailed: !ISSUE_NOT_FOUND.test(execErrorText(err)) };
8368
9885
  }
8369
9886
  issueCache.set(key, out);
8370
9887
  return out;
@@ -8384,7 +9901,7 @@ var defaultResolveSiblingTranche = async (slug, repo) => {
8384
9901
  };
8385
9902
  };
8386
9903
  var siblingTrancheCache = new Map;
8387
- function edgeFromIssueJson(num, json) {
9904
+ function edgeFromIssueJson(num, json, readFailed = false) {
8388
9905
  if (json === null) {
8389
9906
  return {
8390
9907
  issue: num,
@@ -8393,7 +9910,8 @@ function edgeFromIssueJson(num, json) {
8393
9910
  issueState: null,
8394
9911
  stateReason: null,
8395
9912
  closedByActor: null,
8396
- resolved: true
9913
+ resolved: true,
9914
+ ...readFailed ? { readFailed: true } : {}
8397
9915
  };
8398
9916
  }
8399
9917
  const state = json.state === "CLOSED" ? "closed" : json.state === "OPEN" ? "open" : null;
@@ -8426,7 +9944,8 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
8426
9944
  const direct = id.match(DIRECT_ISSUE_REF);
8427
9945
  if (direct) {
8428
9946
  const num = Number(direct[1]);
8429
- return edgeFromIssueJson(num, fetchIssueState(num, repo));
9947
+ const read = fetchIssueState(num, repo);
9948
+ return edgeFromIssueJson(num, read.json, read.readFailed);
8430
9949
  }
8431
9950
  const qualified = splitSlugQualifiedEdge(id);
8432
9951
  if (qualified) {
@@ -8460,15 +9979,27 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
8460
9979
  resolved: false
8461
9980
  };
8462
9981
  }
9982
+ function dependsOnFactFromEdge(id, r) {
9983
+ return {
9984
+ id,
9985
+ issue: r.issue,
9986
+ merged: r.merged,
9987
+ resolved: r.resolved,
9988
+ issueState: r.issueState,
9989
+ stateReason: r.stateReason,
9990
+ closedByActor: r.closedByActor,
9991
+ ...r.readFailed ? { readFailed: true } : {}
9992
+ };
9993
+ }
8463
9994
 
8464
9995
  // src/lib/package-root.ts
8465
- import { existsSync as existsSync2 } from "node:fs";
8466
- import { dirname as dirname2, join as join2 } from "node:path";
9996
+ import { existsSync as existsSync3 } from "node:fs";
9997
+ import { dirname as dirname2, join as join3 } from "node:path";
8467
9998
  import { fileURLToPath as fileURLToPath2 } from "node:url";
8468
9999
  function packageRoot(moduleUrl) {
8469
10000
  let dir = dirname2(fileURLToPath2(moduleUrl));
8470
- while (!existsSync2(join2(dir, "package.json"))) {
8471
- if (existsSync2(join2(dir, ".git")))
10001
+ while (!existsSync3(join3(dir, "package.json"))) {
10002
+ if (existsSync3(join3(dir, ".git")))
8472
10003
  break;
8473
10004
  const parent = dirname2(dir);
8474
10005
  if (parent === dir)
@@ -8479,15 +10010,22 @@ function packageRoot(moduleUrl) {
8479
10010
  }
8480
10011
 
8481
10012
  // src/commands/doctrine.ts
8482
- import { execFileSync as execFileSync5 } from "node:child_process";
8483
- import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync3 } from "node:fs";
8484
- import { dirname as dirname3, join as join3, sep } from "node:path";
10013
+ import { execFileSync as execFileSync6 } from "node:child_process";
10014
+ import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync4 } from "node:fs";
10015
+ import { dirname as dirname3, join as join4, sep } from "node:path";
8485
10016
  import matter4 from "gray-matter";
8486
10017
 
8487
10018
  // ../../packages/aeg-core/src/docs/parse-doc.ts
8488
10019
  import matter2 from "gray-matter";
8489
10020
  // ../../packages/aeg-core/src/docs/surfaced-manifest.ts
8490
10021
  var NO_MODEL_BACKED_PATHS = new Set;
10022
+ // ../../packages/aeg-core/src/docs/published-prose.ts
10023
+ var ALLOWED_MECHANICS = rulesForGroup("published-prose")[0]?.exemptions ?? [];
10024
+ var PROSE_RULES = rulesForGroup("published-prose").map((rule) => ({
10025
+ id: rule.id,
10026
+ what: rule.message,
10027
+ pattern: rule.patterns.published
10028
+ }));
8491
10029
  // src/roles/contract.ts
8492
10030
  import matter3 from "gray-matter";
8493
10031
 
@@ -8498,7 +10036,7 @@ function resolveDoctrineRoot(pkg = packageRoot(import.meta.url), cwd = process.c
8498
10036
  }
8499
10037
  function gitToplevel(cwd) {
8500
10038
  try {
8501
- return execFileSync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
10039
+ return execFileSync6("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
8502
10040
  encoding: "utf8",
8503
10041
  stdio: ["ignore", "pipe", "pipe"]
8504
10042
  }).trim();
@@ -8509,25 +10047,25 @@ function gitToplevel(cwd) {
8509
10047
  function resolveDoctrineRootInfo(pkg = packageRoot(import.meta.url), cwd = process.cwd()) {
8510
10048
  const toplevel = gitToplevel(cwd);
8511
10049
  if (toplevel !== null) {
8512
- const treeRoot = join3(toplevel, "aeg-root");
8513
- if (existsSync3(join3(treeRoot, "roles")))
10050
+ const treeRoot = join4(toplevel, "aeg-root");
10051
+ if (existsSync4(join4(treeRoot, "roles")))
8514
10052
  return { root: treeRoot, source: "tree" };
8515
10053
  }
8516
10054
  const fromSource = !pkg.split(sep).includes("node_modules");
8517
- const bundleRoot = fromSource ? join3(dirname3(dirname3(pkg)), "aeg-root") : join3(pkg, "aeg-root");
10055
+ const bundleRoot = fromSource ? join4(dirname3(dirname3(pkg)), "aeg-root") : join4(pkg, "aeg-root");
8518
10056
  return hasDoctrineEntry(bundleRoot) ? { root: bundleRoot, source: "bundle" } : null;
8519
10057
  }
8520
10058
  function hasDoctrineEntry(root) {
8521
- return existsSync3(join3(root, ...ENTRY_SEGMENTS));
10059
+ return existsSync4(join4(root, ...ENTRY_SEGMENTS));
8522
10060
  }
8523
10061
 
8524
10062
  // src/lib/brief-assembly.ts
8525
10063
  var PACKAGE_ROOT = packageRoot(import.meta.url);
8526
- var PACKAGED_TEMPLATE_PATH = join4(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
8527
- var TEMPLATE_PATH = existsSync4(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join4(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
10064
+ var PACKAGED_TEMPLATE_PATH = join5(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
10065
+ var TEMPLATE_PATH = existsSync5(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join5(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
8528
10066
  function git(args) {
8529
10067
  try {
8530
- return execFileSync6("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
10068
+ return execFileSync7("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
8531
10069
  } catch {
8532
10070
  return "";
8533
10071
  }
@@ -8540,24 +10078,25 @@ function expandGlob(glob) {
8540
10078
  var DRAFT_ISSUE_SENTINEL = Number.MAX_SAFE_INTEGER;
8541
10079
 
8542
10080
  // src/checks/registry.ts
8543
- import { join as join5, relative, sep as sep2 } from "node:path";
10081
+ import { join as join6, relative, sep as sep2 } from "node:path";
8544
10082
  import { fileURLToPath as fileURLToPath3 } from "node:url";
8545
10083
  function resolveCheckBin(packageDir, moduleUrl) {
8546
10084
  const fromPackage = relative(packageDir, fileURLToPath3(moduleUrl));
8547
10085
  const bundled = fromPackage === "dist" || fromPackage.startsWith(`dist${sep2}`);
8548
- return bundled ? { dir: join5(packageDir, "dist", "checks", "bin"), ext: ".js" } : { dir: join5(packageDir, "src", "checks", "bin"), ext: ".ts" };
10086
+ return bundled ? { dir: join6(packageDir, "dist", "checks", "bin"), ext: ".js" } : { dir: join6(packageDir, "src", "checks", "bin"), ext: ".ts" };
8549
10087
  }
8550
10088
  var CHECK_BIN = resolveCheckBin(packageRoot(import.meta.url), import.meta.url);
8551
10089
  var BIN_DIR = CHECK_BIN.dir;
8552
10090
  var BIN_EXT = CHECK_BIN.ext;
8553
10091
  function bin(name) {
8554
- return join5(BIN_DIR, `${name}${BIN_EXT}`);
10092
+ return join6(BIN_DIR, `${name}${BIN_EXT}`);
8555
10093
  }
8556
10094
  var REGISTRY = [
8557
10095
  [
8558
10096
  {
8559
10097
  name: "brief-shape",
8560
10098
  validates: "body",
10099
+ requiresOpenPr: true,
8561
10100
  run: bin("check-brief-shape"),
8562
10101
  scope: "diff",
8563
10102
  timeoutMs: 15000,
@@ -8566,7 +10105,9 @@ var REGISTRY = [
8566
10105
  BRANCH: { optional: true },
8567
10106
  PR_NUMBER: { optional: true },
8568
10107
  GITHUB_TOKEN: { optional: true },
8569
- GH_TOKEN: { optional: true }
10108
+ GH_TOKEN: { optional: true },
10109
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10110
+ GITHUB_ACTIONS: { optional: true }
8570
10111
  }
8571
10112
  },
8572
10113
  0
@@ -8575,6 +10116,7 @@ var REGISTRY = [
8575
10116
  {
8576
10117
  name: "pr-report-density",
8577
10118
  validates: "body",
10119
+ requiresOpenPr: true,
8578
10120
  run: bin("check-pr-report-density"),
8579
10121
  scope: "diff",
8580
10122
  timeoutMs: 15000,
@@ -8600,7 +10142,9 @@ var REGISTRY = [
8600
10142
  PR_NUMBER: { optional: true },
8601
10143
  GITHUB_REPOSITORY: { optional: true },
8602
10144
  GITHUB_TOKEN: { optional: true },
8603
- GH_TOKEN: { optional: true }
10145
+ GH_TOKEN: { optional: true },
10146
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10147
+ GITHUB_ACTIONS: { optional: true }
8604
10148
  }
8605
10149
  },
8606
10150
  0
@@ -8624,6 +10168,7 @@ var REGISTRY = [
8624
10168
  {
8625
10169
  name: "pr-premise-reassert",
8626
10170
  validates: "body",
10171
+ requiresOpenPr: true,
8627
10172
  run: bin("check-pr-premise-reassert"),
8628
10173
  scope: "diff",
8629
10174
  timeoutMs: 15000,
@@ -8644,7 +10189,9 @@ var REGISTRY = [
8644
10189
  BRANCH: { optional: true },
8645
10190
  GITHUB_TOKEN: { optional: true },
8646
10191
  GH_TOKEN: { optional: true },
8647
- PREMISE_FILE: { optional: true }
10192
+ PREMISE_FILE: { optional: true },
10193
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10194
+ GITHUB_ACTIONS: { optional: true }
8648
10195
  }
8649
10196
  },
8650
10197
  0
@@ -8696,7 +10243,9 @@ var REGISTRY = [
8696
10243
  PR_BODY: { optional: true },
8697
10244
  PR_BODY_FILE: { optional: true },
8698
10245
  GITHUB_TOKEN: { optional: true },
8699
- GH_TOKEN: { optional: true }
10246
+ GH_TOKEN: { optional: true },
10247
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10248
+ GITHUB_ACTIONS: { optional: true }
8700
10249
  }
8701
10250
  },
8702
10251
  1
@@ -8712,7 +10261,13 @@ var REGISTRY = [
8712
10261
  principalOwed: true,
8713
10262
  env: {
8714
10263
  PR_BODY: { optional: true },
8715
- BRANCH: { optional: true }
10264
+ BRANCH: { optional: true },
10265
+ PULL_REQUEST_HEAD_SHA: { optional: true },
10266
+ GITHUB_REPOSITORY: { optional: true },
10267
+ GITHUB_TOKEN: { optional: true },
10268
+ GH_TOKEN: { optional: true },
10269
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10270
+ GITHUB_ACTIONS: { optional: true }
8716
10271
  }
8717
10272
  },
8718
10273
  1
@@ -8728,7 +10283,13 @@ var REGISTRY = [
8728
10283
  ownWorkflow: true,
8729
10284
  env: {
8730
10285
  PR_BODY: { optional: true },
8731
- BRANCH: { optional: true }
10286
+ BRANCH: { optional: true },
10287
+ PULL_REQUEST_HEAD_SHA: { optional: true },
10288
+ GITHUB_REPOSITORY: { optional: true },
10289
+ GITHUB_TOKEN: { optional: true },
10290
+ GH_TOKEN: { optional: true },
10291
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10292
+ GITHUB_ACTIONS: { optional: true }
8732
10293
  }
8733
10294
  },
8734
10295
  1
@@ -8747,7 +10308,9 @@ var REGISTRY = [
8747
10308
  PR_NUMBER: { optional: true },
8748
10309
  GITHUB_REPOSITORY: { optional: true },
8749
10310
  GITHUB_TOKEN: { optional: true },
8750
- GH_TOKEN: { optional: true }
10311
+ GH_TOKEN: { optional: true },
10312
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10313
+ GITHUB_ACTIONS: { optional: true }
8751
10314
  }
8752
10315
  },
8753
10316
  1
@@ -8787,7 +10350,9 @@ var REGISTRY = [
8787
10350
  PR_NUMBER: { optional: true },
8788
10351
  GITHUB_REPOSITORY: { optional: true },
8789
10352
  GITHUB_TOKEN: { optional: true },
8790
- GH_TOKEN: { optional: true }
10353
+ GH_TOKEN: { optional: true },
10354
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10355
+ GITHUB_ACTIONS: { optional: true }
8791
10356
  }
8792
10357
  },
8793
10358
  1
@@ -8840,12 +10405,15 @@ var REGISTRY = [
8840
10405
  {
8841
10406
  name: "doc-coverage-push",
8842
10407
  validates: "body",
10408
+ advisory: true,
8843
10409
  run: bin("check-doc-coverage-push"),
8844
10410
  scope: "diff",
8845
10411
  timeoutMs: 15000,
8846
10412
  env: {
8847
10413
  OVERRIDE_DOCS: { optional: true },
8848
10414
  BASE_SHA: { optional: true },
10415
+ GIT_INDEX_FILE: { optional: true },
10416
+ VINAYA_COMMIT_HOOK: { optional: true },
8849
10417
  PR_BODY: { optional: true },
8850
10418
  PR_BODY_FILE: { optional: true },
8851
10419
  PR_LABELS: { optional: true },
@@ -8857,21 +10425,6 @@ var REGISTRY = [
8857
10425
  },
8858
10426
  0
8859
10427
  ],
8860
- [
8861
- {
8862
- name: "issue-assignment",
8863
- run: bin("check-issue-assignment"),
8864
- scope: "full",
8865
- timeoutMs: 30000,
8866
- env: {
8867
- AEG_REPO: { optional: true },
8868
- BRANCH: { optional: true },
8869
- GITHUB_TOKEN: { optional: true },
8870
- GH_TOKEN: { optional: true }
8871
- }
8872
- },
8873
- 0
8874
- ],
8875
10428
  [
8876
10429
  {
8877
10430
  name: "evidence-fresh",
@@ -8885,7 +10438,9 @@ var REGISTRY = [
8885
10438
  PR_BODY: { optional: true },
8886
10439
  BASE_SHA: { optional: true },
8887
10440
  GITHUB_TOKEN: { optional: true },
8888
- GH_TOKEN: { optional: true }
10441
+ GH_TOKEN: { optional: true },
10442
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10443
+ GITHUB_ACTIONS: { optional: true }
8889
10444
  }
8890
10445
  },
8891
10446
  1
@@ -8896,7 +10451,11 @@ var REGISTRY = [
8896
10451
  run: bin("check-reader-resolvable-prose"),
8897
10452
  scope: "full",
8898
10453
  timeoutMs: 30000,
8899
- env: {},
10454
+ env: {
10455
+ BASE_SHA: { optional: true },
10456
+ GIT_INDEX_FILE: { optional: true },
10457
+ VINAYA_COMMIT_HOOK: { optional: true }
10458
+ },
8900
10459
  include: [
8901
10460
  "aeg-root/**/*.md",
8902
10461
  "apps/cli/src/**",
@@ -8914,7 +10473,11 @@ var REGISTRY = [
8914
10473
  run: bin("check-retired-vocabulary"),
8915
10474
  scope: "full",
8916
10475
  timeoutMs: 30000,
8917
- env: {},
10476
+ env: {
10477
+ BASE_SHA: { optional: true },
10478
+ GIT_INDEX_FILE: { optional: true },
10479
+ VINAYA_COMMIT_HOOK: { optional: true }
10480
+ },
8918
10481
  include: ["aeg-root/**/*.md"]
8919
10482
  },
8920
10483
  0
@@ -8922,10 +10485,15 @@ var REGISTRY = [
8922
10485
  [
8923
10486
  {
8924
10487
  name: "doctrine-portability",
10488
+ advisory: true,
8925
10489
  run: bin("check-doctrine-portability"),
8926
10490
  scope: "full",
8927
10491
  timeoutMs: 30000,
8928
- env: { BASE_SHA: { optional: true } },
10492
+ env: {
10493
+ BASE_SHA: { optional: true },
10494
+ GIT_INDEX_FILE: { optional: true },
10495
+ VINAYA_COMMIT_HOOK: { optional: true }
10496
+ },
8929
10497
  include: ["aeg-root/**/*.md"]
8930
10498
  },
8931
10499
  0
@@ -8958,7 +10526,11 @@ var REGISTRY = [
8958
10526
  run: bin("check-exec-bits"),
8959
10527
  scope: "diff",
8960
10528
  timeoutMs: 30000,
8961
- env: {}
10529
+ env: {
10530
+ BASE_SHA: { optional: true },
10531
+ GIT_INDEX_FILE: { optional: true },
10532
+ VINAYA_COMMIT_HOOK: { optional: true }
10533
+ }
8962
10534
  },
8963
10535
  0
8964
10536
  ],
@@ -8968,17 +10540,26 @@ var REGISTRY = [
8968
10540
  run: bin("check-ci-shard-coverage"),
8969
10541
  scope: "diff",
8970
10542
  timeoutMs: 15000,
8971
- env: {}
10543
+ env: {
10544
+ BASE_SHA: { optional: true },
10545
+ GIT_INDEX_FILE: { optional: true },
10546
+ VINAYA_COMMIT_HOOK: { optional: true }
10547
+ }
8972
10548
  },
8973
10549
  0
8974
10550
  ],
8975
10551
  [
8976
10552
  {
8977
10553
  name: "workspace-escape",
10554
+ advisory: true,
8978
10555
  run: bin("check-workspace-escape"),
8979
10556
  scope: "full",
8980
10557
  timeoutMs: 30000,
8981
- env: {},
10558
+ env: {
10559
+ BASE_SHA: { optional: true },
10560
+ GIT_INDEX_FILE: { optional: true },
10561
+ VINAYA_COMMIT_HOOK: { optional: true }
10562
+ },
8982
10563
  include: ["aeg-root/**/*.md"]
8983
10564
  },
8984
10565
  0
@@ -8989,17 +10570,23 @@ var REGISTRY = [
8989
10570
  run: bin("check-changeset-coverage"),
8990
10571
  scope: "diff",
8991
10572
  timeoutMs: 15000,
8992
- env: {}
10573
+ env: {
10574
+ BASE_SHA: { optional: true },
10575
+ GIT_INDEX_FILE: { optional: true },
10576
+ VINAYA_COMMIT_HOOK: { optional: true }
10577
+ }
8993
10578
  },
8994
10579
  0
8995
10580
  ],
8996
10581
  [
8997
10582
  {
8998
10583
  name: "quoted-command",
10584
+ advisory: true,
8999
10585
  run: bin("check-quoted-command"),
9000
- scope: "diff",
10586
+ scope: "full",
9001
10587
  timeoutMs: 15000,
9002
- env: {}
10588
+ env: {},
10589
+ include: ["aeg-root/**/*.md"]
9003
10590
  },
9004
10591
  0
9005
10592
  ],
@@ -9007,7 +10594,7 @@ var REGISTRY = [
9007
10594
  {
9008
10595
  name: "main-branch-refusal",
9009
10596
  run: bin("check-main-branch-refusal"),
9010
- scope: "full",
10597
+ scope: "diff",
9011
10598
  timeoutMs: 15000,
9012
10599
  env: { VINAYA_PUSH_REFS: { optional: true } }
9013
10600
  },
@@ -9074,18 +10661,6 @@ var REGISTRY = [
9074
10661
  },
9075
10662
  1
9076
10663
  ],
9077
- [
9078
- {
9079
- name: "issue-tranche-label",
9080
- run: bin("check-issue-tranche-label"),
9081
- validates: "issue",
9082
- scope: "full",
9083
- ownWorkflow: true,
9084
- timeoutMs: 15000,
9085
- env: { ISSUE_BODY: { optional: true }, ISSUE_LABELS: { optional: true } }
9086
- },
9087
- 1
9088
- ],
9089
10664
  [
9090
10665
  {
9091
10666
  name: "issue-milestone-attach",
@@ -9115,24 +10690,24 @@ import {
9115
10690
  appendFileSync,
9116
10691
  closeSync as closeSync4,
9117
10692
  constants as fsConstants4,
9118
- existsSync as existsSync7,
10693
+ existsSync as existsSync8,
9119
10694
  fstatSync as fstatSync3,
9120
10695
  mkdirSync as mkdirSync4,
9121
10696
  lstatSync as lstatSync2,
9122
10697
  openSync as openSync4,
9123
- readFileSync as readFileSync7,
10698
+ readFileSync as readFileSync8,
9124
10699
  renameSync as renameSync2,
9125
- writeFileSync as writeFileSync3,
10700
+ writeFileSync as writeFileSync4,
9126
10701
  writeSync as writeSync3
9127
10702
  } from "node:fs";
9128
10703
  import { hostname as osHostname, homedir as homedir3 } from "node:os";
9129
- import { dirname as dirname7, join as join8 } from "node:path";
10704
+ import { dirname as dirname7, join as join9 } from "node:path";
9130
10705
  import { promisify as promisify5 } from "node:util";
9131
10706
 
9132
10707
  // src/lib/run-paths.ts
9133
- import { execFileSync as execFileSync7 } from "node:child_process";
9134
- import { chmodSync, existsSync as existsSync5, realpathSync as realpathSync3 } from "node:fs";
9135
- import { dirname as dirname4, join as join6, resolve as resolvePath } from "node:path";
10708
+ import { execFileSync as execFileSync8 } from "node:child_process";
10709
+ import { chmodSync, existsSync as existsSync6, realpathSync as realpathSync3 } from "node:fs";
10710
+ import { dirname as dirname4, join as join7, resolve as resolvePath } from "node:path";
9136
10711
  var TASKS_EXECUTION_DIRNAME = "tasks-execution";
9137
10712
  var RUN_AREA_DIRNAMES = {
9138
10713
  control: CONTROL_AREA_DIRNAME,
@@ -9151,7 +10726,7 @@ function repoSegment(repo) {
9151
10726
  return `${repo.owner}-${repo.repo}`;
9152
10727
  }
9153
10728
  function defaultRuntimeDir(repo, home = GLOBAL_VINAYA_HOME) {
9154
- return join6(home, "runtime", repoSegment(repo));
10729
+ return join7(home, "runtime", repoSegment(repo));
9155
10730
  }
9156
10731
  function resolveRuntimeDir(input) {
9157
10732
  const local = resolveRuntimeDirSetting(input.localConfig);
@@ -9172,27 +10747,27 @@ function isInsideRepo(candidate, repoRoot) {
9172
10747
  return target === root || target.startsWith(`${root}/`);
9173
10748
  }
9174
10749
  function runPath(runtimeDir, scope, location) {
9175
- const dir = join6(runtimeDir, TASKS_EXECUTION_DIRNAME, scopeSegment(scope));
10750
+ const dir = join7(runtimeDir, TASKS_EXECUTION_DIRNAME, scopeSegment(scope));
9176
10751
  switch (location.area) {
9177
10752
  case "task":
9178
- return location.file ? join6(dir, location.file) : dir;
10753
+ return location.file ? join7(dir, location.file) : dir;
9179
10754
  case "control": {
9180
- const controlDir = join6(dir, RUN_AREA_DIRNAMES.control);
9181
- return location.file ? join6(controlDir, location.file) : controlDir;
10755
+ const controlDir = join7(dir, RUN_AREA_DIRNAMES.control);
10756
+ return location.file ? join7(controlDir, location.file) : controlDir;
9182
10757
  }
9183
10758
  case "rounds":
9184
- return join6(dir, RUN_AREA_DIRNAMES.rounds);
10759
+ return join7(dir, RUN_AREA_DIRNAMES.rounds);
9185
10760
  case "round": {
9186
- const roundDir = join6(dir, RUN_AREA_DIRNAMES.rounds, String(location.round));
9187
- return location.file ? join6(roundDir, location.file) : roundDir;
10761
+ const roundDir = join7(dir, RUN_AREA_DIRNAMES.rounds, String(location.round));
10762
+ return location.file ? join7(roundDir, location.file) : roundDir;
9188
10763
  }
9189
10764
  case "developer": {
9190
- const developerDir = join6(dir, RUN_AREA_DIRNAMES.rounds, String(location.round), "developer");
9191
- return location.file ? join6(developerDir, location.file) : developerDir;
10765
+ const developerDir = join7(dir, RUN_AREA_DIRNAMES.rounds, String(location.round), "developer");
10766
+ return location.file ? join7(developerDir, location.file) : developerDir;
9192
10767
  }
9193
10768
  default: {
9194
- const areaDir = join6(dir, RUN_AREA_DIRNAMES[location.area]);
9195
- return location.file ? join6(areaDir, location.file) : areaDir;
10769
+ const areaDir = join7(dir, RUN_AREA_DIRNAMES[location.area]);
10770
+ return location.file ? join7(areaDir, location.file) : areaDir;
9196
10771
  }
9197
10772
  }
9198
10773
  }
@@ -9261,7 +10836,7 @@ function repoRootSync(start = process.cwd()) {
9261
10836
  return null;
9262
10837
  }
9263
10838
  for (;; ) {
9264
- if (existsSync5(join6(dir, ".git")))
10839
+ if (existsSync6(join7(dir, ".git")))
9265
10840
  return dir;
9266
10841
  const parent = dirname4(dir);
9267
10842
  if (parent === dir)
@@ -9278,7 +10853,7 @@ function resolveRepoSync() {
9278
10853
  }
9279
10854
  let url;
9280
10855
  try {
9281
- url = execFileSync7("git", ["remote", "get-url", "origin"], {
10856
+ url = execFileSync8("git", ["remote", "get-url", "origin"], {
9282
10857
  encoding: "utf-8",
9283
10858
  stdio: ["ignore", "pipe", "pipe"]
9284
10859
  }).trim();
@@ -9305,11 +10880,11 @@ function runtimeDirForThisRepo() {
9305
10880
  import {
9306
10881
  closeSync as closeSync2,
9307
10882
  constants as fsConstants2,
9308
- existsSync as existsSync6,
10883
+ existsSync as existsSync7,
9309
10884
  fstatSync as fstatSync2,
9310
10885
  mkdirSync as mkdirSync2,
9311
10886
  openSync as openSync2,
9312
- readFileSync as readFileSync5,
10887
+ readFileSync as readFileSync6,
9313
10888
  readSync,
9314
10889
  statSync,
9315
10890
  writeSync
@@ -9346,17 +10921,17 @@ import {
9346
10921
  mkdirSync as mkdirSync3,
9347
10922
  openSync as openSync3,
9348
10923
  linkSync,
9349
- readFileSync as readFileSync6,
10924
+ readFileSync as readFileSync7,
9350
10925
  renameSync,
9351
10926
  statSync as statSync2,
9352
10927
  unlinkSync,
9353
10928
  utimesSync,
9354
- writeFileSync as writeFileSync2,
10929
+ writeFileSync as writeFileSync3,
9355
10930
  writeSync as writeSync2
9356
10931
  } from "node:fs";
9357
10932
  import { randomUUID } from "node:crypto";
9358
10933
  import { homedir as homedir2 } from "node:os";
9359
- import { dirname as dirname6, join as join7 } from "node:path";
10934
+ import { dirname as dirname6, join as join8 } from "node:path";
9360
10935
  var MAX_WEBHOOK_BODY_BYTES = 5 * 1024 * 1024;
9361
10936
  var WEBHOOK_FETCH_TIMEOUT_MS = 30000;
9362
10937
  var SAFE_PATH_SEGMENT2 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
@@ -9437,7 +11012,7 @@ function acquireDrainLock(lockPath) {
9437
11012
  function renewDrainLock(lockPath, token) {
9438
11013
  let holder;
9439
11014
  try {
9440
- holder = readFileSync6(lockPath, "utf8").trim();
11015
+ holder = readFileSync7(lockPath, "utf8").trim();
9441
11016
  } catch (err) {
9442
11017
  if (!isEnoent(err))
9443
11018
  throw err;
@@ -9457,7 +11032,7 @@ function renewDrainLock(lockPath, token) {
9457
11032
  }
9458
11033
  function releaseDrainLock(lockPath, token) {
9459
11034
  try {
9460
- const holder = readFileSync6(lockPath, "utf8").trim();
11035
+ const holder = readFileSync7(lockPath, "utf8").trim();
9461
11036
  if (holder !== token)
9462
11037
  return;
9463
11038
  unlinkSync(lockPath);
@@ -9507,8 +11082,8 @@ function queueLines(buf) {
9507
11082
  return lines;
9508
11083
  }
9509
11084
  function removeQueueHead(path, cut) {
9510
- const remaining = readFileSync6(path);
9511
- writeFileSync2(path, remaining.subarray(Math.min(cut, remaining.byteLength)));
11085
+ const remaining = readFileSync7(path);
11086
+ writeFileSync3(path, remaining.subarray(Math.min(cut, remaining.byteLength)));
9512
11087
  }
9513
11088
  function queueBucketSize(path) {
9514
11089
  let lstat;
@@ -9528,7 +11103,7 @@ function queueBucketSize(path) {
9528
11103
  function readQueueFile(path) {
9529
11104
  if (queueBucketSize(path) === null)
9530
11105
  return null;
9531
- return readFileSync6(path);
11106
+ return readFileSync7(path);
9532
11107
  }
9533
11108
  function rejectLine(rejectedPath, reason, status, identity, raw) {
9534
11109
  const record = JSON.stringify({
@@ -9643,7 +11218,7 @@ async function drainRenamedAside(args, livePath, source) {
9643
11218
  async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeoutMs = WEBHOOK_FETCH_TIMEOUT_MS) {
9644
11219
  const resolved = await resolveRepo();
9645
11220
  const repo = resolved && isSafeRepoSegment2(resolved.owner) && isSafeRepoSegment2(resolved.repo) ? resolved : null;
9646
- const outboxRoot = () => join7(GLOBAL_VINAYA_HOME, "outbox");
11221
+ const outboxRoot = () => join8(GLOBAL_VINAYA_HOME, "outbox");
9647
11222
  const path = outboxPathFor({ outboxRoot }, repo, outboxTask);
9648
11223
  const lockPath = `${path}.flush-lock`;
9649
11224
  const lockToken = acquireDrainLock(lockPath);
@@ -9780,7 +11355,7 @@ async function defaultResolveLogDestination(repo, env) {
9780
11355
  trustAnchorConfig: unattended ? await processTrustAnchor(repoRoot) : null,
9781
11356
  unattended,
9782
11357
  env,
9783
- defaultFolder: join8(await runtimeDirForRepoAsync(repo), "logs"),
11358
+ defaultFolder: join9(await runtimeDirForRepoAsync(repo), "logs"),
9784
11359
  repoRoot
9785
11360
  });
9786
11361
  }
@@ -9796,7 +11371,7 @@ function unresolvedLogDestination(env) {
9796
11371
  const unattended = isUnattendedProcess(process.env);
9797
11372
  const repoRoot = repoRootSync();
9798
11373
  const runtimeDir = process.env[RUNTIME_DIR_ENV_KEY] || resolveRuntimeDir({ repo: null, localConfig, trustAnchorConfig: null, unattended, repoRoot });
9799
- const defaultFolder = join8(runtimeDir, "logs");
11374
+ const defaultFolder = join9(runtimeDir, "logs");
9800
11375
  const resolved = resolveLogDestinationFrom({
9801
11376
  localConfig,
9802
11377
  trustAnchorConfig: null,
@@ -9809,7 +11384,7 @@ function unresolvedLogDestination(env) {
9809
11384
  }
9810
11385
  function folderFallbackStatePath(repo, stateRoot = GLOBAL_VINAYA_HOME) {
9811
11386
  const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
9812
- return join8(stateRoot, "fallback", `${dirName}.json`);
11387
+ return join9(stateRoot, "fallback", `${dirName}.json`);
9813
11388
  }
9814
11389
  function recordFolderFallback(repo, issue, reason, now, runtimeDir, stateRoot = GLOBAL_VINAYA_HOME) {
9815
11390
  const message = describeFolderFallback(reason);
@@ -9825,7 +11400,7 @@ function recordFolderFallback(repo, issue, reason, now, runtimeDir, stateRoot =
9825
11400
  };
9826
11401
  const path = folderFallbackStatePath(repo, stateRoot);
9827
11402
  mkdirSync4(dirname7(path), { recursive: true, mode: 448 });
9828
- writeFileSync3(path, `${JSON.stringify(record)}
11403
+ writeFileSync4(path, `${JSON.stringify(record)}
9829
11404
  `, { mode: 384 });
9830
11405
  } catch {}
9831
11406
  }
@@ -9840,7 +11415,7 @@ async function resolveDoctrine(cwd, vinayaVersion) {
9840
11415
  } catch (err) {
9841
11416
  return isEnoent2(err) ? "unknown" : vinayaVersion;
9842
11417
  }
9843
- if (!existsSync7(join8(toplevel, "aeg-root", "roles")))
11418
+ if (!existsSync8(join9(toplevel, "aeg-root", "roles")))
9844
11419
  return vinayaVersion;
9845
11420
  try {
9846
11421
  const sha = (await execFileAsync5("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], { encoding: "utf8" })).stdout.trim();
@@ -9941,7 +11516,7 @@ async function resolveBranchIssue(cwd, env = process.env, repo = null) {
9941
11516
  }
9942
11517
  function readVinayaVersion() {
9943
11518
  try {
9944
- const pkg = JSON.parse(readFileSync7(join8(packageRoot(import.meta.url), "package.json"), "utf8"));
11519
+ const pkg = JSON.parse(readFileSync8(join9(packageRoot(import.meta.url), "package.json"), "utf8"));
9945
11520
  return pkg.version ?? "unknown";
9946
11521
  } catch {
9947
11522
  return "unknown";
@@ -9959,7 +11534,7 @@ function safeRepoSlug(repo) {
9959
11534
  function outboxPathFor(deps, repo, issue) {
9960
11535
  const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
9961
11536
  const fileName = `${issue ?? "none"}.ndjson`;
9962
- return join8(deps.outboxRoot(), dirName, fileName);
11537
+ return join9(deps.outboxRoot(), dirName, fileName);
9963
11538
  }
9964
11539
  function hostFromEnv(env) {
9965
11540
  if (env.GITHUB_ACTIONS)
@@ -10014,7 +11589,7 @@ async function resolveHeadSha(cwd) {
10014
11589
  }
10015
11590
  function defaultDeps() {
10016
11591
  return {
10017
- outboxRoot: () => join8(GLOBAL_VINAYA_HOME, "outbox"),
11592
+ outboxRoot: () => join9(GLOBAL_VINAYA_HOME, "outbox"),
10018
11593
  home: () => homedir3(),
10019
11594
  hostname: () => osHostname(),
10020
11595
  cwd: () => process.cwd(),
@@ -10059,7 +11634,7 @@ function appendHardenedLine(path, line) {
10059
11634
  function reportRotationOverflow(backupPath, warn) {
10060
11635
  let raw;
10061
11636
  try {
10062
- raw = readFileSync7(backupPath, "utf8");
11637
+ raw = readFileSync8(backupPath, "utf8");
10063
11638
  } catch {
10064
11639
  return;
10065
11640
  }
@@ -10272,12 +11847,14 @@ function createLogSink(overrides = {}) {
10272
11847
  branchIssue,
10273
11848
  eventId: randomUUID2(),
10274
11849
  processId,
11850
+ revision: headSha,
11851
+ provenance: deps.provenance,
10275
11852
  inputVersions: deps.inputVersions()
10276
11853
  });
10277
11854
  const header = headSha === null ? built : { ...built, subject: { ...built.subject, sha: headSha } };
10278
11855
  if (destination.kind === "folder" && destination.fallbackReason && !folderFallbackRecorded) {
10279
11856
  folderFallbackRecorded = true;
10280
- recordFolderFallback(repo, header.subject.issue, destination.fallbackReason, call.now, dirname7(destination.folder), join8(deps.home(), ".vinaya"));
11857
+ recordFolderFallback(repo, header.subject.issue, destination.fallbackReason, call.now, dirname7(destination.folder), join9(deps.home(), ".vinaya"));
10281
11858
  }
10282
11859
  const full = { ...e, ...header };
10283
11860
  const parsed = LogEventSchema.safeParse(full);
@@ -10402,20 +11979,40 @@ function parseChangedLineRanges(diffOutput) {
10402
11979
 
10403
11980
  // src/lib/diff-evidence.ts
10404
11981
  function fileDiffAgainst(ref, path) {
10405
- let out;
11982
+ let committed;
10406
11983
  try {
10407
- out = execFileSync8("git", ["diff", `${ref}...HEAD`, "--", path], {
11984
+ committed = execFileSync9("git", ["diff", `${ref}...HEAD`, "--", path], {
10408
11985
  encoding: "utf8",
10409
11986
  stdio: ["ignore", "pipe", "pipe"]
10410
11987
  }).trim();
10411
11988
  } catch {
10412
11989
  return null;
10413
11990
  }
11991
+ const staged = stagedDiff(["--", path]);
11992
+ if (staged === null)
11993
+ return null;
11994
+ const out = [committed, staged].filter(Boolean).join(`
11995
+ `);
10414
11996
  return out === "" ? null : out;
10415
11997
  }
11998
+ function readsStagedDiff() {
11999
+ return process.env.VINAYA_COMMIT_HOOK === "1" && Boolean(process.env.GIT_INDEX_FILE);
12000
+ }
12001
+ function stagedDiff(args) {
12002
+ if (!readsStagedDiff())
12003
+ return "";
12004
+ try {
12005
+ return execFileSync9("git", ["diff", "--cached", ...args], {
12006
+ encoding: "utf8",
12007
+ stdio: ["ignore", "pipe", "pipe"]
12008
+ }).trim();
12009
+ } catch {
12010
+ return null;
12011
+ }
12012
+ }
10416
12013
  function revParse(ref) {
10417
12014
  try {
10418
- return execFileSync8("git", ["rev-parse", "--verify", ref], {
12015
+ return execFileSync9("git", ["rev-parse", "--verify", ref], {
10419
12016
  encoding: "utf8",
10420
12017
  stdio: ["ignore", "pipe", "pipe"]
10421
12018
  }).trim();
@@ -10425,7 +12022,7 @@ function revParse(ref) {
10425
12022
  }
10426
12023
  function repoRoot() {
10427
12024
  try {
10428
- return execFileSync8("git", ["rev-parse", "--show-toplevel"], {
12025
+ return execFileSync9("git", ["rev-parse", "--show-toplevel"], {
10429
12026
  encoding: "utf8",
10430
12027
  stdio: ["ignore", "pipe", "pipe"]
10431
12028
  }).trim();
@@ -10436,7 +12033,7 @@ function repoRoot() {
10436
12033
  function changedFiles(base) {
10437
12034
  let out;
10438
12035
  try {
10439
- out = execFileSync8("git", ["diff", "--name-only", `${base}...HEAD`], {
12036
+ out = execFileSync9("git", ["diff", "--name-only", `${base}...HEAD`], {
10440
12037
  encoding: "utf8",
10441
12038
  stdio: ["ignore", "pipe", "pipe"]
10442
12039
  }).trim();
@@ -10446,6 +12043,13 @@ function changedFiles(base) {
10446
12043
  return out === "" ? [] : out.split(`
10447
12044
  `).map((s) => s.trim()).filter(Boolean);
10448
12045
  }
12046
+ function stagedChangedFiles() {
12047
+ const out = stagedDiff(["--name-only"]);
12048
+ if (out === null)
12049
+ return null;
12050
+ return out === "" ? [] : out.split(`
12051
+ `).map((s) => s.trim()).filter(Boolean);
12052
+ }
10449
12053
  function resolveChangedFiles(base = process.env.BASE_SHA || "origin/main") {
10450
12054
  return resolveDiff(base)?.files ?? null;
10451
12055
  }
@@ -10461,7 +12065,30 @@ function resolveDiff(base = process.env.BASE_SHA || "origin/main") {
10461
12065
  const relPaths = changedFiles(ref);
10462
12066
  if (relPaths === null)
10463
12067
  continue;
10464
- return { base: ref, root, files: relPaths.map((p) => join9(root, p)) };
12068
+ const stagedPaths = stagedChangedFiles();
12069
+ if (stagedPaths === null)
12070
+ return null;
12071
+ const paths = [...new Set([...relPaths, ...stagedPaths])];
12072
+ return { base: ref, root, files: paths.map((p) => join10(root, p)) };
12073
+ }
12074
+ return null;
12075
+ }
12076
+ function resolveAddedFiles(base = process.env.BASE_SHA || "origin/main") {
12077
+ if (repoRoot() === null)
12078
+ return null;
12079
+ const head = revParse("HEAD");
12080
+ for (const ref of new Set([base, "origin/main", "main"])) {
12081
+ const resolved = revParse(ref);
12082
+ if (resolved === null || resolved === head)
12083
+ continue;
12084
+ try {
12085
+ const out = execFileSync9("git", ["diff", "--name-only", "--diff-filter=A", `${ref}...HEAD`], {
12086
+ encoding: "utf8",
12087
+ stdio: ["ignore", "pipe", "pipe"]
12088
+ }).trim();
12089
+ return out === "" ? [] : out.split(`
12090
+ `).map((p) => p.trim()).filter(Boolean);
12091
+ } catch {}
10465
12092
  }
10466
12093
  return null;
10467
12094
  }
@@ -10497,7 +12124,7 @@ var CHECK_NAME = "exec-bits";
10497
12124
  var EXECUTABLE_MODE = "100755";
10498
12125
  function git2(args) {
10499
12126
  try {
10500
- return execFileSync9("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
12127
+ return execFileSync10("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
10501
12128
  } catch {
10502
12129
  return null;
10503
12130
  }
@@ -10511,7 +12138,7 @@ function indexMode(path) {
10511
12138
  }
10512
12139
  function hasShebang(path) {
10513
12140
  try {
10514
- return readFileSync8(path, "utf8").startsWith("#!");
12141
+ return readFileSync9(path, "utf8").startsWith("#!");
10515
12142
  } catch {
10516
12143
  return false;
10517
12144
  }