@attalabs/vinaya 0.39.0 → 0.41.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 (186) hide show
  1. package/README.md +9 -9
  2. package/aeg-root/contracts/developer-reviewer.md +2 -2
  3. package/aeg-root/contracts/planner-developer.md +5 -5
  4. package/aeg-root/enforcement.md +22 -22
  5. package/aeg-root/process.md +4 -4
  6. package/aeg-root/roles/archivist.md +1 -1
  7. package/aeg-root/roles/developer/reference.md +7 -1
  8. package/aeg-root/roles/developer.md +1 -1
  9. package/aeg-root/roles/planner/reference.md +18 -5
  10. package/aeg-root/roles/principal.md +1 -1
  11. package/aeg-root/roles/reviewer.md +3 -3
  12. package/aeg-root/roles/security.md +4 -4
  13. package/aeg-root/roles/tranche-archivist.md +2 -2
  14. package/aeg-root/skills/aeg/SKILL.md +1 -1
  15. package/aeg-root/state-machine.md +10 -15
  16. package/aeg-root/templates/brief-template.md +5 -2
  17. package/aeg-root/templates/decision-record-template.md +38 -0
  18. package/aeg-root/templates/issue-rationale-template.md +1 -1
  19. package/aeg-root/tranche-model.md +1 -1
  20. package/dist/checks/bin/check-body-bare-digits.js +1974 -354
  21. package/dist/checks/bin/check-branch-topology.js +1296 -243
  22. package/dist/checks/bin/check-brief-shape.js +2038 -460
  23. package/dist/checks/bin/check-changeset-coverage.js +2411 -564
  24. package/dist/checks/bin/check-ci-shard-coverage.js +12391 -15
  25. package/dist/checks/bin/check-closes-n.js +1296 -243
  26. package/dist/checks/bin/check-coherence.js +1914 -1155
  27. package/dist/checks/bin/check-dead-branch-push.js +1242 -230
  28. package/dist/checks/bin/check-dispatch-readiness.js +2222 -460
  29. package/dist/checks/bin/check-doc-claims.js +2233 -260
  30. package/dist/checks/bin/check-doc-coverage-push.js +2436 -550
  31. package/dist/checks/bin/check-doc-coverage.js +2434 -552
  32. package/dist/checks/bin/check-doctrine-no-procedures.js +1776 -353
  33. package/dist/checks/bin/check-doctrine-portability.js +2408 -561
  34. package/dist/checks/bin/check-evidence-fresh.js +2370 -508
  35. package/dist/checks/bin/check-exec-bits.js +2407 -560
  36. package/dist/checks/bin/check-first-push-dispatch.js +1984 -380
  37. package/dist/checks/bin/check-issue-assignment.js +712 -170
  38. package/dist/checks/bin/check-issue-milestone-attach.js +1233 -230
  39. package/dist/checks/bin/check-issue-objectives-numbering.js +1769 -346
  40. package/dist/checks/bin/check-issue-parts-coverage.js +1233 -230
  41. package/dist/checks/bin/check-issue-surface-globs.js +1926 -378
  42. package/dist/checks/bin/check-issue-title-grammar.js +1233 -230
  43. package/dist/checks/bin/check-issue-tranche-label.js +702 -170
  44. package/dist/checks/bin/check-main-branch-refusal.js +1245 -232
  45. package/dist/checks/bin/check-no-disk-state.js +1233 -230
  46. package/dist/checks/bin/check-pr-premise-reassert.js +1769 -346
  47. package/dist/checks/bin/check-pr-report-density.js +1233 -230
  48. package/dist/checks/bin/check-principal-test-plan-wait.js +2489 -259
  49. package/dist/checks/bin/check-quoted-command.js +2391 -544
  50. package/dist/checks/bin/check-reader-resolvable-prose.js +2437 -564
  51. package/dist/checks/bin/check-registry-gates.js +1380 -296
  52. package/dist/checks/bin/check-retired-vocabulary.js +2416 -550
  53. package/dist/checks/bin/check-review-gate.js +2073 -371
  54. package/dist/checks/bin/check-single-plan-pr.js +1297 -235
  55. package/dist/checks/bin/check-surface-scope.js +1531 -252
  56. package/dist/checks/bin/check-test-plan.js +2487 -258
  57. package/dist/checks/bin/check-token-collection-wired.js +1233 -230
  58. package/dist/checks/bin/check-workspace-escape.js +2408 -561
  59. package/dist/checks/bin/verify-coherence.js +597 -97
  60. package/dist/checks/bin/verify-dispatch.js +632 -152
  61. package/dist/checks/bin/verify-docs.js +642 -132
  62. package/dist/index.js +25948 -16630
  63. package/dist/lib/pre-push-cache-test-run.js +1813 -297
  64. package/dist/lib/pre-push-changed-files.js +65 -19
  65. package/dist/lib/pre-push-mode.js +466 -0
  66. package/dist/lib/pre-push-progress-dir.js +4205 -0
  67. package/dist/lib/pre-push-record-tests.js +446 -0
  68. package/dist/lib/pre-push-select-tests.js +2353 -632
  69. package/dist/lib/push-progress-observer.js +4213 -0
  70. package/package.json +22 -5
  71. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/anchored-region.ts +17 -3
  72. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-render.ts +73 -30
  73. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-validation.ts +3 -3
  74. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/coherence-checks.ts +2 -2
  75. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/local.ts +88 -5
  76. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/records.ts +34 -2
  77. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/assess-round.ts +26 -4
  78. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/fakes.ts +7 -2
  79. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/index.ts +7 -1
  80. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/types.ts +29 -3
  81. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dispatch-gate.ts +35 -18
  82. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/index.ts +1 -1
  83. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/published-prose.ts +70 -45
  84. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doctrine-portability.ts +6 -1
  85. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/entry-point.ts +27 -0
  86. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/gate-audience.ts +3 -5
  87. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/index.ts +96 -9
  88. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-assignment.ts +24 -54
  89. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-validation.ts +809 -106
  90. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/live-record.ts +179 -0
  91. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/envelope.ts +8 -2
  92. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/index.ts +1 -0
  93. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/narration.ts +2 -0
  94. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema-digest.ts +225 -0
  95. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema.ts +7 -1
  96. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/main-branch-refusal.ts +23 -1
  97. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/pr-report-density.ts +6 -4
  98. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/principals-config.ts +44 -0
  99. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/prose-rules.ts +532 -0
  100. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/protected-paths.ts +31 -0
  101. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/reader-resolvable-prose.ts +157 -80
  102. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/registry-checks.ts +8 -12
  103. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/retired-vocabulary.ts +53 -93
  104. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-gate.ts +46 -17
  105. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-input-manifest.ts +85 -1
  106. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-policy.ts +32 -13
  107. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/ruling-ordinal.ts +46 -0
  108. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/task-branch-identity.ts +2 -4
  109. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/test-plan-gate.ts +63 -8
  110. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/verdict-extraction.ts +24 -0
  111. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/waiver-label.ts +0 -1
  112. package/studio-standalone/apps/vinaya-studio/web/.next/BUILD_ID +1 -1
  113. package/studio-standalone/apps/vinaya-studio/web/.next/build-manifest.json +3 -3
  114. package/studio-standalone/apps/vinaya-studio/web/.next/prerender-manifest.json +3 -3
  115. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.html +1 -1
  116. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.rsc +1 -1
  117. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  118. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  119. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  120. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  121. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  122. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page/server-reference-manifest.json +2 -2
  123. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page.js.nft.json +1 -1
  124. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  125. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page/server-reference-manifest.json +2 -2
  126. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page.js.nft.json +1 -1
  127. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page_client-reference-manifest.js +1 -1
  128. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page/server-reference-manifest.json +2 -2
  129. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js +1 -1
  130. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js.nft.json +1 -1
  131. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page_client-reference-manifest.js +1 -1
  132. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page/server-reference-manifest.json +2 -2
  133. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js +1 -1
  134. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js.nft.json +1 -1
  135. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page_client-reference-manifest.js +1 -1
  136. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page/server-reference-manifest.json +2 -2
  137. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js +1 -1
  138. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js.nft.json +1 -1
  139. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page_client-reference-manifest.js +1 -1
  140. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page/server-reference-manifest.json +3 -3
  141. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js +1 -1
  142. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js.nft.json +1 -1
  143. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page_client-reference-manifest.js +1 -1
  144. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page/server-reference-manifest.json +2 -2
  145. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js +2 -2
  146. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js.nft.json +1 -1
  147. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page_client-reference-manifest.js +1 -1
  148. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page/server-reference-manifest.json +2 -2
  149. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js +1 -1
  150. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js.nft.json +1 -1
  151. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page_client-reference-manifest.js +1 -1
  152. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page/server-reference-manifest.json +2 -2
  153. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js +1 -1
  154. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js.nft.json +1 -1
  155. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page_client-reference-manifest.js +1 -1
  156. 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
  157. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__08e39jo._.js +1 -1
  158. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0ls23oh._.js +1 -1
  159. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0sxadt2._.js +13 -0
  160. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1a3j3n1._.js +57 -0
  161. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__1ug9syi._.js → [root-of-the-server]__1d4eth3._.js} +1 -1
  162. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1gjqmhq._.js +1 -1
  163. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1snpgaw._.js +3 -3
  164. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1wc4-ip._.js +1 -1
  165. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_08onyya._.js +2 -2
  166. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_096f46i._.js +1 -1
  167. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0af2one._.js +1 -1
  168. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0e5tkdd._.js +1 -1
  169. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0kf2g72._.js +1 -1
  170. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0zf4d27._.js +3 -3
  171. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1-wo68i._.js +1 -1
  172. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1achbh9._.js +1 -1
  173. 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
  174. package/studio-standalone/apps/vinaya-studio/web/.next/server/middleware-build-manifest.js +3 -3
  175. package/studio-standalone/apps/vinaya-studio/web/.next/server/pages/500.html +1 -1
  176. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.js +1 -1
  177. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.json +4 -4
  178. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{33rszkngkuoko.js → 0x7u6si-ai179.js} +1 -1
  179. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{06_55xbp7rcbi.js → 2fu7mfsj4oima.js} +1 -1
  180. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{2brkwv169ygep.js → 34b4ruddunn3q.js} +1 -1
  181. package/studio-standalone/apps/vinaya-studio/web/package.json +2 -2
  182. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__04adkz-._.js +0 -57
  183. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__19jyp3m._.js +0 -13
  184. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → 2ZARxTwpuRew8-SvYsRdU}/_buildManifest.js +0 -0
  185. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → 2ZARxTwpuRew8-SvYsRdU}/_clientMiddlewareManifest.js +0 -0
  186. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → 2ZARxTwpuRew8-SvYsRdU}/_ssgManifest.js +0 -0
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/checks/bin/check-body-bare-digits.ts
4
- import { execFileSync as execFileSync3 } from "node:child_process";
4
+ import { execFileSync as execFileSync4 } from "node:child_process";
5
5
 
6
6
  // ../../packages/aeg-core/src/entry-point.ts
7
7
  import { realpathSync } from "node:fs";
@@ -42,7 +42,6 @@ var GATE_AUDIENCE = {
42
42
  };
43
43
  var NON_GATE_BINS = [
44
44
  "archive-task",
45
- "assign-task-issue",
46
45
  "dead-branch-audit",
47
46
  "eval-agent-compliance",
48
47
  "open-issue",
@@ -305,6 +304,25 @@ async function runAsync(args) {
305
304
  function ghApiGet(path) {
306
305
  return JSON.parse(run(["api", path]));
307
306
  }
307
+ var MAX_PER_PAGE = 100;
308
+ var MAX_PAGES = 100;
309
+ async function ghApiGetAllPagesAsync(pathWithoutPage, opts) {
310
+ const [base = pathWithoutPage, query = ""] = pathWithoutPage.split("?");
311
+ const params = new URLSearchParams(query);
312
+ params.set("per_page", String(MAX_PER_PAGE));
313
+ const all = [];
314
+ for (let page = 1;page <= MAX_PAGES; page++) {
315
+ params.set("page", String(page));
316
+ const args = ["api", `${base}?${params.toString()}`];
317
+ if (opts?.jq)
318
+ args.push("-q", opts.jq);
319
+ const batch = JSON.parse(await runAsync(args));
320
+ all.push(...batch);
321
+ if (batch.length < MAX_PER_PAGE)
322
+ return all;
323
+ }
324
+ throw new Error(`ghApiGetAllPagesAsync: "${pathWithoutPage}" did not terminate within ${MAX_PAGES} pages (${MAX_PAGES * MAX_PER_PAGE} items) — refusing to keep walking.`);
325
+ }
308
326
  function issueListByLabelArgs(owner, repo, label) {
309
327
  return [
310
328
  "issue",
@@ -716,6 +734,10 @@ function intentGoalForSlug(description, slug) {
716
734
  function matchesLegacyMilestone(milestones, slug) {
717
735
  return milestones.find((m) => m.title === slug) ?? null;
718
736
  }
737
+ var TRANCHE_SLUG_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*-v\d+$/;
738
+ function slugShapedTitles(milestones) {
739
+ return milestones.map((m) => m.title).filter((t) => TRANCHE_SLUG_SHAPE.test(t));
740
+ }
719
741
  function factsFromLegacyMilestone(milestone) {
720
742
  return {
721
743
  goal: milestone.description ?? "",
@@ -749,6 +771,105 @@ function findMilestoneForSlug(owner, repo, slug) {
749
771
  return resolveLegacyFacts(legacy, issues);
750
772
  return { goal: goalFromMilestones(milestones, slug), lifecycle: lifecycleFromIssues(issues) };
751
773
  }
774
+ function trancheSlugsFromLabels(labels) {
775
+ const slugs = [];
776
+ for (const l of labels) {
777
+ const slug = trancheSlugOf(l.name);
778
+ if (slug !== null)
779
+ slugs.push(slug);
780
+ }
781
+ return slugs;
782
+ }
783
+ async function indexTrancheMilestonesAsync(owner, repo, options = {}) {
784
+ const read = (fetch) => options.retryFailedReads ? retryOnce(fetch) : fetch();
785
+ const [milestones, labels] = await Promise.all([
786
+ read(() => ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`)),
787
+ read(() => ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`))
788
+ ]);
789
+ const active = [];
790
+ const archived = [];
791
+ const facts = new Map;
792
+ const legacySlugs = new Set(slugShapedTitles(milestones));
793
+ const legacyMilestoneBySlug = new Map(milestones.filter((m) => legacySlugs.has(m.title)).map((m) => [m.title, m]));
794
+ const newPathSlugs = trancheSlugsFromLabels(labels).filter((slug) => !legacySlugs.has(slug));
795
+ const uniqueNewPathSlugs = [...new Set(newPathSlugs)];
796
+ const uniqueLegacySlugs = [...legacySlugs];
797
+ const [legacyIssuesBySlug, newPathIssuesBySlug] = await Promise.all([
798
+ Promise.all(uniqueLegacySlugs.map((slug) => read(() => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))))),
799
+ Promise.all(uniqueNewPathSlugs.map((slug) => read(() => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug)))))
800
+ ]);
801
+ const issuesBySlug = new Map;
802
+ uniqueLegacySlugs.forEach((slug, i) => {
803
+ issuesBySlug.set(slug, legacyIssuesBySlug[i] ?? []);
804
+ });
805
+ uniqueNewPathSlugs.forEach((slug, i) => {
806
+ issuesBySlug.set(slug, newPathIssuesBySlug[i] ?? []);
807
+ });
808
+ uniqueLegacySlugs.forEach((slug, i) => {
809
+ const m = legacyMilestoneBySlug.get(slug);
810
+ if (!m)
811
+ return;
812
+ const ref = { slug, goal: m.description ?? "" };
813
+ const f = resolveLegacyFacts(m, legacyIssuesBySlug[i] ?? []);
814
+ if (f.lifecycle === "complete")
815
+ archived.push(ref);
816
+ else if (f.lifecycle === "active")
817
+ active.push(ref);
818
+ facts.set(slug, f);
819
+ });
820
+ uniqueNewPathSlugs.forEach((slug, i) => {
821
+ const issues = newPathIssuesBySlug[i] ?? [];
822
+ const lifecycle = lifecycleFromIssues(issues);
823
+ const goal = goalFromMilestones(milestones, slug);
824
+ const f = { goal, lifecycle };
825
+ facts.set(slug, f);
826
+ if (lifecycle === "active")
827
+ active.push({ slug, goal });
828
+ else if (lifecycle === "complete")
829
+ archived.push({ slug, goal });
830
+ });
831
+ return { active, archived, facts, legacySlugs, issuesBySlug };
832
+ }
833
+ async function retryOnce(fetch) {
834
+ try {
835
+ return await fetch();
836
+ } catch {
837
+ return fetch();
838
+ }
839
+ }
840
+ async function indexTrancheMilestonesForSlugAsync(owner, repo, slug) {
841
+ const [milestones, labels, issues] = await Promise.all([
842
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`),
843
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`),
844
+ ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))
845
+ ]);
846
+ const active = [];
847
+ const archived = [];
848
+ const facts = new Map;
849
+ const legacySlugs = new Set;
850
+ const legacyMilestone = slugShapedTitles(milestones).includes(slug) ? matchesLegacyMilestone(milestones, slug) : null;
851
+ if (legacyMilestone) {
852
+ legacySlugs.add(slug);
853
+ const ref = { slug, goal: legacyMilestone.description ?? "" };
854
+ const f = resolveLegacyFacts(legacyMilestone, issues);
855
+ if (f.lifecycle === "complete")
856
+ archived.push(ref);
857
+ else if (f.lifecycle === "active")
858
+ active.push(ref);
859
+ facts.set(slug, f);
860
+ } else if (trancheSlugsFromLabels(labels).includes(slug)) {
861
+ const lifecycle = lifecycleFromIssues(issues);
862
+ const goal = goalFromMilestones(milestones, slug);
863
+ facts.set(slug, { goal, lifecycle });
864
+ if (lifecycle === "active")
865
+ active.push({ slug, goal });
866
+ else if (lifecycle === "complete")
867
+ archived.push({ slug, goal });
868
+ }
869
+ const openLegacyTitles = new Set(slugShapedTitles(milestones.filter((m) => m.state === "open")));
870
+ const otherOpenLegacySlugs = [...openLegacyTitles].filter((t) => t !== slug);
871
+ return { active, archived, facts, legacySlugs, otherOpenLegacySlugs };
872
+ }
752
873
 
753
874
  // ../../packages/aeg-forge-state/src/derive-from-forge.ts
754
875
  function trancheFromIssues(slug, issues, known) {
@@ -1409,6 +1530,125 @@ var graphql2 = withDefaults3(request, {
1409
1530
  method: "POST",
1410
1531
  url: "/graphql"
1411
1532
  });
1533
+
1534
+ // ../../packages/aeg-forge-state/src/fetch-provenance.ts
1535
+ var PROVENANCE_PATTERN = /^###\s+AEG provenance\b/im;
1536
+ function provenanceMatchesIssue(text, issueNum) {
1537
+ if (!PROVENANCE_PATTERN.test(text))
1538
+ return false;
1539
+ const m = text.match(/^-\s*Issue:\s*#(\d+)/im);
1540
+ return m !== null && Number(m[1]) === issueNum;
1541
+ }
1542
+ function isPrCloser(closer) {
1543
+ return closer !== null && typeof closer.number === "number";
1544
+ }
1545
+ async function fetchProvenanceViaCrossReferences(issueNums, owner, repo, token) {
1546
+ const result = new Map;
1547
+ if (issueNums.length === 0)
1548
+ return result;
1549
+ const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
1550
+ const perIssue = issueNums.map((n) => `
1551
+ i_${n}: issue(number: ${n}) {
1552
+ timelineItems(first: 50, itemTypes: [CROSS_REFERENCED_EVENT]) {
1553
+ nodes {
1554
+ ... on CrossReferencedEvent {
1555
+ source {
1556
+ ... on PullRequest {
1557
+ number
1558
+ body
1559
+ comments(first: 50) { nodes { body } }
1560
+ }
1561
+ }
1562
+ }
1563
+ }
1564
+ }
1565
+ }`).join("");
1566
+ const query = `query ProvenanceCrossRef($owner: String!, $repo: String!) {
1567
+ repository(owner: $owner, name: $repo) {${perIssue}
1568
+ }
1569
+ }`;
1570
+ let response;
1571
+ try {
1572
+ response = await client(query, { owner, repo });
1573
+ } catch {
1574
+ return result;
1575
+ }
1576
+ if (!response.repository)
1577
+ return result;
1578
+ for (const n of issueNums) {
1579
+ const raw = response.repository[`i_${n}`];
1580
+ const nodes = raw?.timelineItems?.nodes ?? [];
1581
+ const found = nodes.some(({ source }) => {
1582
+ if (!source || typeof source.number !== "number")
1583
+ return false;
1584
+ const pr = source;
1585
+ if (provenanceMatchesIssue(pr.body ?? "", n))
1586
+ return true;
1587
+ return pr.comments.nodes.some((c) => provenanceMatchesIssue(c.body, n));
1588
+ });
1589
+ result.set(n, found);
1590
+ }
1591
+ return result;
1592
+ }
1593
+ async function fetchProvenance(issueNums, owner, repo, token) {
1594
+ const result = new Map;
1595
+ if (issueNums.length === 0)
1596
+ return result;
1597
+ const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
1598
+ const perIssue = issueNums.map((n) => `
1599
+ i_${n}: issue(number: ${n}) {
1600
+ timelineItems(last: 1, itemTypes: [CLOSED_EVENT]) {
1601
+ nodes {
1602
+ ... on ClosedEvent {
1603
+ closer {
1604
+ ... on PullRequest {
1605
+ number
1606
+ body
1607
+ comments(first: 50) {
1608
+ nodes { body }
1609
+ }
1610
+ }
1611
+ }
1612
+ }
1613
+ }
1614
+ }
1615
+ }`).join("");
1616
+ const query = `query Provenance($owner: String!, $repo: String!) {
1617
+ repository(owner: $owner, name: $repo) {${perIssue}
1618
+ }
1619
+ }`;
1620
+ let response;
1621
+ try {
1622
+ response = await client(query, { owner, repo });
1623
+ } catch {
1624
+ return result;
1625
+ }
1626
+ if (!response.repository)
1627
+ return result;
1628
+ const needsFallback = [];
1629
+ for (const n of issueNums) {
1630
+ const raw = response.repository[`i_${n}`];
1631
+ if (!raw) {
1632
+ result.set(n, false);
1633
+ continue;
1634
+ }
1635
+ const closer = raw.timelineItems?.nodes?.[0]?.closer;
1636
+ const c = closer ?? null;
1637
+ if (!isPrCloser(c)) {
1638
+ needsFallback.push(n);
1639
+ continue;
1640
+ }
1641
+ const bodyHas = PROVENANCE_PATTERN.test(c.body ?? "");
1642
+ const commentHas = c.comments.nodes.some((x) => PROVENANCE_PATTERN.test(x.body));
1643
+ result.set(n, bodyHas || commentHas);
1644
+ }
1645
+ if (needsFallback.length > 0) {
1646
+ const fallback = await fetchProvenanceViaCrossReferences(needsFallback, owner, repo, token);
1647
+ for (const [n, found] of fallback)
1648
+ result.set(n, found);
1649
+ }
1650
+ return result;
1651
+ }
1412
1652
  // ../../packages/aeg-forge-state/src/github-token.ts
1413
1653
  import { execFile as execFile2 } from "node:child_process";
1414
1654
  import { promisify as promisify2 } from "node:util";
@@ -1638,6 +1878,52 @@ function describeError(err) {
1638
1878
  return err;
1639
1879
  return "unknown error";
1640
1880
  }
1881
+ // ../../packages/aeg-forge-state/src/prior-tranche-archival.ts
1882
+ function defaultPriorTrancheArchivalDeps() {
1883
+ return {
1884
+ activeTranches: async (excludeSlug, repo) => {
1885
+ const index = await indexTrancheMilestonesAsync(repo.owner, repo.repo, { retryFailedReads: true });
1886
+ return index.active.filter((m) => m.slug !== excludeSlug).map((m) => {
1887
+ const issues = index.issuesBySlug?.get(m.slug);
1888
+ if (!issues)
1889
+ throw new Error(`the Milestone index holds no Issue list for tranche \`${m.slug}\``);
1890
+ return { slug: m.slug, issues };
1891
+ });
1892
+ }
1893
+ };
1894
+ }
1895
+ function reason(err) {
1896
+ return err instanceof Error ? err.message.split(`
1897
+ `)[0] ?? "failed" : String(err);
1898
+ }
1899
+ async function resolvePriorTrancheArchival(projects, excludeSlug, repo, deps = defaultPriorTrancheArchivalDeps()) {
1900
+ if (projects.length === 0)
1901
+ return { facts: [], infraFailure: null };
1902
+ let candidates;
1903
+ try {
1904
+ candidates = await deps.activeTranches(excludeSlug, repo);
1905
+ } catch (err) {
1906
+ return {
1907
+ facts: [],
1908
+ infraFailure: `severity:infra — could not read the active tranches (${reason(err)}); whether a prior tranche is archived is unknown.`
1909
+ };
1910
+ }
1911
+ const tasksBySlug = new Map(candidates.map((c) => [c.slug, tasksFromIssues(c.issues)]));
1912
+ const facts = [];
1913
+ for (const project of projects) {
1914
+ let found = null;
1915
+ for (const { slug, issues } of candidates) {
1916
+ if (!(tasksBySlug.get(slug) ?? []).some((t) => t.projects.includes(project)))
1917
+ continue;
1918
+ if (!issues.some((issue) => issue.state === "OPEN")) {
1919
+ found = { project, priorTrancheSlug: slug, archived: false };
1920
+ break;
1921
+ }
1922
+ }
1923
+ facts.push(found ?? { project, priorTrancheSlug: null, archived: false });
1924
+ }
1925
+ return { facts, infraFailure: null };
1926
+ }
1641
1927
  // ../../packages/aeg-forge-state/src/fetch-open-issues.ts
1642
1928
  async function fetchOpenIssuesByLabel(slugs, owner, repo, token) {
1643
1929
  const result = new Map;
@@ -1712,6 +1998,10 @@ function buildQuery(issueNumbers) {
1712
1998
  }
1713
1999
  }`;
1714
2000
  }
2001
+ // ../../packages/aeg-forge-state/src/list-issue-milestones.ts
2002
+ function issueMilestonesFromIssues(issues) {
2003
+ return issues.filter((i) => i.state === "OPEN").map((i) => ({ issue: i.number, milestoneTitle: i.milestone?.title ?? null }));
2004
+ }
1715
2005
  // ../../packages/aeg-forge-state/src/resolve-repo.ts
1716
2006
  import { execFile as execFile3 } from "node:child_process";
1717
2007
  import { promisify as promisify3 } from "node:util";
@@ -1774,7 +2064,8 @@ var ANCHOR_FIELDS = [
1774
2064
  "PREMISE",
1775
2065
  "TEST-PLAN",
1776
2066
  "EVIDENCE",
1777
- "BEYOND-SURFACE"
2067
+ "BEYOND-SURFACE",
2068
+ "LIVE"
1778
2069
  ];
1779
2070
  function anchoredRegionBounds(body, field) {
1780
2071
  const masked = maskCode(body);
@@ -1975,7 +2266,6 @@ var DERIVABLE_STATUSES = DERIVED_STATUSES.filter((s) => s !== "backlog");
1975
2266
  // ../../packages/aeg-core/src/waiver-label.ts
1976
2267
  var WAIVER_LABEL = label("waiver-docs");
1977
2268
  var WAIVER_LABEL_REVIEW = label("waiver-review");
1978
- var PRINCIPAL_ALLOWLIST = ["daniboomerang"];
1979
2269
  function isPrincipal(login, principalAllowlist) {
1980
2270
  if (login === null)
1981
2271
  return false;
@@ -1994,6 +2284,14 @@ var RULING_ORDINAL_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Ruling ordinal:\s*(\d+)(
1994
2284
  var BRIEF_HASH_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Brief hash:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
1995
2285
  var POLICY_DIGEST_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Policy digest:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
1996
2286
  var BASE_SHA_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Judged base:\s*([0-9a-f]{7,40})(?![A-Za-z0-9])/im;
2287
+ var MANIFEST_VERSION_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Manifest version:\s*(\d+)\s*$/im;
2288
+ var PAUSE_BOUND_RULING_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Pause-bound ruling:\s*(?:(\S+)\|(\S+)\|([0-9a-f]{64})|\(none\))\s*$/im;
2289
+ function extractPauseBoundRuling(comment) {
2290
+ const m = comment.match(PAUSE_BOUND_RULING_PATTERN);
2291
+ if (!m)
2292
+ return;
2293
+ return m[1] ? { rulingId: m[1], pauseId: m[2], contentDigest: m[3] } : null;
2294
+ }
1997
2295
  function firstFiveLines(comment) {
1998
2296
  return comment.split(`
1999
2297
  `).slice(0, 5).join(`
@@ -2087,6 +2385,8 @@ function extractVerdict(comments, valuePattern, missingLabel) {
2087
2385
  danglingNote: `the most recent ${missingLabel} verdict comment carries a VERDICT-shaped line outside the first-five-line read window`
2088
2386
  };
2089
2387
  }
2388
+ const versionMatch = latest.match(MANIFEST_VERSION_PATTERN);
2389
+ const pauseBoundRuling = extractPauseBoundRuling(latest);
2090
2390
  return {
2091
2391
  value: m[1].toUpperCase().replace(/[_-]/g, " "),
2092
2392
  headSha: extractHeadSha(latest),
@@ -2095,6 +2395,8 @@ function extractVerdict(comments, valuePattern, missingLabel) {
2095
2395
  briefHash: extractBriefHash(latest),
2096
2396
  policyDigest: extractPolicyDigest(latest),
2097
2397
  baseSha: extractBaseSha(latest),
2398
+ ...versionMatch ? { manifestVersion: Number.parseInt(versionMatch[1], 10) } : {},
2399
+ ...pauseBoundRuling === undefined ? {} : { pauseBoundRuling },
2098
2400
  findingSeverities: extractFindingSeverities(latest),
2099
2401
  danglingNote: null
2100
2402
  };
@@ -2105,6 +2407,16 @@ function extractCodeReviewVerdict(comments) {
2105
2407
  function extractSecurityReviewVerdict(comments) {
2106
2408
  return extractVerdict(comments, /^[ \t]*(?:\*{1,3}|_{1,3})?VERDICT:\s*(PASS|FAIL)(?![A-Za-z0-9])/im, "security-review");
2107
2409
  }
2410
+
2411
+ // ../../packages/aeg-core/src/review-status.ts
2412
+ var DEVELOPER_ROUND_MARKER = /<!--\s*aeg:developer:round-(\d+)\s*-->/i;
2413
+ function parseDeveloperRoundMarker(body) {
2414
+ const m = body.match(DEVELOPER_ROUND_MARKER);
2415
+ if (!m)
2416
+ return null;
2417
+ const n = Number(m[1]);
2418
+ return Number.isFinite(n) ? n : null;
2419
+ }
2108
2420
  // ../../packages/aeg-core/src/report-tokens.ts
2109
2421
  var DASH_LOOKALIKES = {
2110
2422
  "-": "‑",
@@ -2436,11 +2748,13 @@ var CODE_REVIEW_SEVERITY_ORDER = ["BLOCKER", "MAJOR", "MINOR"];
2436
2748
  var SECURITY_SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW"];
2437
2749
  var DEFAULT_MAX_ROUNDS = 3;
2438
2750
  var DEFAULT_MAX_TASK_MINUTES = 180;
2751
+ var DEFAULT_READY_PUSH_TIMEOUT_MINUTES = 20;
2439
2752
  var DEFAULT_REVIEW_POLICY = {
2440
2753
  codeReviewThreshold: "BLOCKER",
2441
2754
  securityThreshold: "HIGH",
2442
2755
  maxRounds: DEFAULT_MAX_ROUNDS,
2443
- maxTaskMinutes: DEFAULT_MAX_TASK_MINUTES
2756
+ maxTaskMinutes: DEFAULT_MAX_TASK_MINUTES,
2757
+ readyPushTimeoutMinutes: DEFAULT_READY_PUSH_TIMEOUT_MINUTES
2444
2758
  };
2445
2759
  var FILE_SHAPED_LOCATION = /\.[a-zA-Z0-9]{1,10}(:\d+)?\s*$/;
2446
2760
  var PROSE_LOCATION_PATTERNS = [/\bpr\s*body\b/i, /\bcomment\b/i];
@@ -2800,14 +3114,14 @@ function checkTestPlan(prBody) {
2800
3114
  const region = located.found ? located.section : prBody;
2801
3115
  if (TEST_PLAN_UNIT_TESTS_ONLY_RE.test(region))
2802
3116
  return { status: "pass", errors: [] };
2803
- if (/\*\*\[(?:agent|principal)\]\*\*/.test(region))
3117
+ if (/\*\*\[(?:agent|principal|live)\]\*\*/.test(region))
2804
3118
  return { status: "pass", errors: [] };
2805
3119
  if (located.found && extractFencedBlocks(region).length > 0)
2806
3120
  return { status: "pass", errors: [] };
2807
3121
  return {
2808
3122
  status: "fail",
2809
3123
  errors: [
2810
- "brief-validation Test Plan: no Test Plan section found — expected `Test Plan: unit-tests-only`, a fenced `[agent]` command list, or at least one `**[agent]**`/`**[principal]**`-tagged checklist item."
3124
+ "brief-validation Test Plan: no Test Plan section found — expected `Test Plan: unit-tests-only`, a fenced `[agent]` command list, or at least one `**[agent]**`/`**[principal]**`/`**[live]**`-tagged item."
2811
3125
  ]
2812
3126
  };
2813
3127
  }
@@ -3429,6 +3743,375 @@ function checkPrReportDensity(prBody) {
3429
3743
  const results = [checkDecisionsDensity(prBody), checkScopeDensity(prBody)];
3430
3744
  return { errors: results.flatMap((r) => r.errors) };
3431
3745
  }
3746
+ // ../../packages/aeg-core/src/prose-rules.ts
3747
+ var RETIRED_GLOBAL_EXEMPTIONS = [
3748
+ "docs/decisions-legacy.md",
3749
+ "apps/herald-ai/docs/",
3750
+ "apps/vada-ai/docs/",
3751
+ "aeg-root/tranches/completed/",
3752
+ "packages/aeg-core/src/docs/published-prose",
3753
+ "packages/aeg-core/src/retired-vocabulary.test.ts",
3754
+ "packages/aeg-core/src/retired-vocabulary.ts",
3755
+ "/fixtures/",
3756
+ "/node_modules/",
3757
+ "/.next/",
3758
+ "/.turbo/"
3759
+ ];
3760
+ var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
3761
+ var TRANCHE_MODEL_FILE = "/tranche-model.md";
3762
+ var RETIRED_PATTERN_EXEMPTIONS = {
3763
+ [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
3764
+ [String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`]: [
3765
+ "docs-index.md",
3766
+ "apps/vada-ai/specs/legacy/README.md",
3767
+ "apps/vada-ai/specs/vada-product-spec.md",
3768
+ "apps/vada-ai/web/CLAUDE.md",
3769
+ "apps/vada-ai/CLAUDE.md"
3770
+ ],
3771
+ "decisions-legacy": [
3772
+ "packages/aeg-core/src/file-classify.ts",
3773
+ "packages/aeg-core/src/file-classify.test.ts",
3774
+ "packages/aeg-core/src/pr-tier.test.ts",
3775
+ "docs-index.md",
3776
+ ".claude/skills/database/SKILL.md",
3777
+ ".claude/skills/vada-architecture/SKILL.md",
3778
+ "apps/vada-ai/specs/vada-byok-principles.md",
3779
+ "apps/vada-ai/web/CLAUDE.md",
3780
+ "apps/vada-ai/CLAUDE.md"
3781
+ ],
3782
+ CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
3783
+ ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
3784
+ };
3785
+ var retiredPatterns = [
3786
+ String.raw`\bD-[0-9]{3}\b`,
3787
+ "D-(###|NNN|nnn|xxx)",
3788
+ "decision (entry|logged)",
3789
+ "decision-log entry",
3790
+ "decision log entry",
3791
+ "decision log(s|ged|ging)?([^a-z]|$)",
3792
+ "decision-log",
3793
+ "decision entr",
3794
+ "decisions? (are |is )?logged",
3795
+ "log entries",
3796
+ String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`,
3797
+ "decisions-legacy",
3798
+ "CONTRADICTION",
3799
+ "assumes Tier 3",
3800
+ "Lock: ?YES",
3801
+ "Lock: ?NO",
3802
+ "lock approvals?",
3803
+ "approves locks",
3804
+ "Conforms to lock",
3805
+ "Challenges lock",
3806
+ "checkDecisionNumbersFresh",
3807
+ String.raw`roles/team-leader\.md`,
3808
+ String.raw`\(,`,
3809
+ String.raw`,\)`,
3810
+ String.raw`\(\.\)`,
3811
+ ...PLAN_ON_DISK_PATTERNS
3812
+ ];
3813
+ var published = [
3814
+ ["decision-id", "a decision id", /\bD-\d{3,}\b/],
3815
+ ["section-ref", "a section reference", /§/],
3816
+ ["forge-number", "a forge number", /#\d+/],
3817
+ ["retired-name", "the retired public name", /\bAEG\b/],
3818
+ ["tranche-slug", "a tranche slug", /\b[a-z][a-z0-9]*(?:-[a-z0-9]+)+-v\d+\b/],
3819
+ [
3820
+ "label-vocabulary",
3821
+ "forge label vocabulary",
3822
+ /(?:vinaya\/)?\b(?:tranche|iteration|tier|needs|waiver|project|aeg):(?![/\s]|$)/
3823
+ ],
3824
+ ["internal-path", "a repo-internal path", /\b(?:packages|apps|aeg-root|tools|scripts)\//],
3825
+ ["internal-path", "a repo-internal path", /\.(?:claude|husky|github)\//],
3826
+ [
3827
+ "internal-path",
3828
+ "a repo-internal file",
3829
+ /(?:^|[\s(`"'[])[\w.-]+(?:\/[\w.-]+)*\.(?:ts|tsx|js|jsx|mjs|cjs|sh|ya?ml|json|md)\b/
3830
+ ]
3831
+ ];
3832
+ var DEFAULT_PROSE_RULES = [
3833
+ {
3834
+ id: "forge-number",
3835
+ group: "reader-resolvable",
3836
+ scopes: ["ships", "reader-facing", "spec"],
3837
+ patterns: { prose: /#[0-9]{2,4}/g },
3838
+ flags: ["global"],
3839
+ message: "a forge number",
3840
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
3841
+ exemptions: []
3842
+ },
3843
+ {
3844
+ id: "tranche-slug",
3845
+ group: "reader-resolvable",
3846
+ scopes: ["ships", "reader-facing", "product", "spec"],
3847
+ patterns: { prose: /[a-z][a-z-]+-v[0-9]/g },
3848
+ flags: ["global"],
3849
+ message: "an internal tranche slug",
3850
+ severity: { ships: "warning", "reader-facing": "warning", product: "error", spec: "error" },
3851
+ exemptions: []
3852
+ },
3853
+ {
3854
+ id: "task-number",
3855
+ group: "reader-resolvable",
3856
+ scopes: ["spec"],
3857
+ patterns: { prose: /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi },
3858
+ flags: ["global", "ignore-case"],
3859
+ message: "a task number",
3860
+ severity: { spec: "error" },
3861
+ exemptions: []
3862
+ },
3863
+ {
3864
+ id: "source-comment-tranche-slug",
3865
+ group: "reader-resolvable",
3866
+ scopes: ["source-comment"],
3867
+ patterns: { comment: /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g },
3868
+ flags: ["global"],
3869
+ message: "a tranche-slug citation",
3870
+ severity: { "source-comment": "warning" },
3871
+ exemptions: []
3872
+ },
3873
+ {
3874
+ id: "source-comment-forge-number",
3875
+ group: "reader-resolvable",
3876
+ scopes: ["source-comment"],
3877
+ patterns: { comment: /#[0-9]{2,}/g },
3878
+ flags: ["global"],
3879
+ message: "a forge-number citation",
3880
+ severity: { "source-comment": "warning" },
3881
+ exemptions: []
3882
+ },
3883
+ {
3884
+ id: "legacy-batch-name",
3885
+ group: "reader-resolvable",
3886
+ scopes: ["ships", "reader-facing", "spec"],
3887
+ patterns: {},
3888
+ flags: ["built-in"],
3889
+ message: "an internal tranche slug",
3890
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
3891
+ exemptions: [],
3892
+ builtIn: true
3893
+ },
3894
+ {
3895
+ id: "coined-term",
3896
+ group: "reader-resolvable",
3897
+ scopes: ["ships", "reader-facing"],
3898
+ patterns: {},
3899
+ flags: ["built-in"],
3900
+ message: "uses coined term without defining it inline or linking the glossary",
3901
+ severity: { ships: "warning", "reader-facing": "warning" },
3902
+ exemptions: [],
3903
+ builtIn: true
3904
+ },
3905
+ ...retiredPatterns.map((pattern, index) => ({
3906
+ id: `retired-vocabulary-${index + 1}`,
3907
+ group: "retired-vocabulary",
3908
+ scopes: ["repository"],
3909
+ patterns: { repository: pattern },
3910
+ flags: [],
3911
+ message: "retired vocabulary",
3912
+ severity: { repository: "error" },
3913
+ exemptions: RETIRED_GLOBAL_EXEMPTIONS,
3914
+ patternExemptions: RETIRED_PATTERN_EXEMPTIONS
3915
+ })),
3916
+ ...published.map(([id, message, pattern]) => ({
3917
+ id,
3918
+ group: "published-prose",
3919
+ scopes: ["published"],
3920
+ patterns: { published: pattern },
3921
+ flags: [],
3922
+ message,
3923
+ severity: { published: "error" },
3924
+ exemptions: [".worktrees/task/<tranche>/<n>", "task/<tranche>/<n>", ".worktrees/"]
3925
+ }))
3926
+ ];
3927
+ var rulesForGroup = (group) => DEFAULT_PROSE_RULES.filter((rule) => rule.group === group);
3928
+ var RESOLVABLE_SCOPES = ["ships", "reader-facing", "product", "spec", "source-comment"];
3929
+ var RETIRED_SCOPES = ["repository"];
3930
+ var CONFIGURABLE_PROSE_SCOPES = [...RESOLVABLE_SCOPES, ...RETIRED_SCOPES];
3931
+ function groupOfScope(scope) {
3932
+ if (RESOLVABLE_SCOPES.includes(scope))
3933
+ return "reader-resolvable";
3934
+ if (RETIRED_SCOPES.includes(scope))
3935
+ return "retired-vocabulary";
3936
+ return;
3937
+ }
3938
+ var CONFIGURED_PROSE_FLAGS = ["i", "u"];
3939
+ var CONFIGURED_PATTERN_MAX_LENGTH = 200;
3940
+ var CONFIGURABLE_DEFAULT_RULES = DEFAULT_PROSE_RULES.filter((rule) => rule.group !== "published-prose");
3941
+ function allowedScopesFor(rule) {
3942
+ if (rule.builtIn)
3943
+ return rule.scopes;
3944
+ return rule.group === "retired-vocabulary" ? RETIRED_SCOPES : RESOLVABLE_SCOPES;
3945
+ }
3946
+ function normalizeRepoPath(entry) {
3947
+ let out = entry.replace(/\\/g, "/");
3948
+ while (out.startsWith("./"))
3949
+ out = out.slice(2);
3950
+ out = out.replace(/\/{2,}/g, "/");
3951
+ while (out.endsWith("/"))
3952
+ out = out.slice(0, -1);
3953
+ return out;
3954
+ }
3955
+ function isConfiguredExempt(path, exempt, repoRoot) {
3956
+ if (exempt.length === 0)
3957
+ return false;
3958
+ const root = repoRoot === undefined ? undefined : normalizeRepoPath(repoRoot);
3959
+ let rel = normalizeRepoPath(path);
3960
+ if (root && rel.startsWith(`${root}/`))
3961
+ rel = rel.slice(root.length + 1);
3962
+ return exempt.some((entry) => {
3963
+ const e = normalizeRepoPath(entry);
3964
+ return rel === e || rel.startsWith(`${e}/`);
3965
+ });
3966
+ }
3967
+ function ruleReads(set, rule, path) {
3968
+ return !isConfiguredExempt(path, set.exempt, set.repoRoot) && !isConfiguredExempt(path, rule.exempt, set.repoRoot);
3969
+ }
3970
+ var RESOLVABLE_RUN_ORDER = [
3971
+ "forge-number",
3972
+ "tranche-slug",
3973
+ "legacy-batch-name",
3974
+ "task-number",
3975
+ "source-comment-tranche-slug",
3976
+ "source-comment-forge-number",
3977
+ "coined-term"
3978
+ ];
3979
+ var REPORT_GROUPS = { "task-number": 2, "legacy-batch-name": 2 };
3980
+ function scopeDefaultSeverity(scope, sourceCommentSeverity) {
3981
+ if (scope === "source-comment")
3982
+ return sourceCommentSeverity ?? "warning";
3983
+ if (scope === "repository")
3984
+ return "error";
3985
+ return "warning";
3986
+ }
3987
+ function applySeverity(scopes, base, setting) {
3988
+ const out = {};
3989
+ for (const scope of scopes) {
3990
+ const configured = typeof setting === "string" ? setting : setting?.[scope];
3991
+ const value = configured ?? base[scope];
3992
+ if (value !== undefined)
3993
+ out[scope] = value;
3994
+ }
3995
+ return out;
3996
+ }
3997
+ function defaultPatternFor(rule) {
3998
+ const cache = new Map;
3999
+ return (scope) => {
4000
+ if (cache.has(scope))
4001
+ return cache.get(scope) ?? null;
4002
+ const own = rule.patterns[scope] ?? (scope === "source-comment" ? rule.patterns.comment : rule.patterns.prose) ?? Object.values(rule.patterns)[0];
4003
+ const compiled = own === undefined ? null : own instanceof RegExp ? own : new RegExp(own);
4004
+ cache.set(scope, compiled);
4005
+ return compiled;
4006
+ };
4007
+ }
4008
+ function customPatternFor(rule, global) {
4009
+ const cache = new Map;
4010
+ return (scope) => {
4011
+ if (cache.has(scope))
4012
+ return cache.get(scope) ?? null;
4013
+ const source = rule.patterns?.[scope] ?? rule.pattern;
4014
+ const compiled = source === undefined ? null : new RegExp(source, `${rule.flags ?? ""}${global ? "g" : ""}`);
4015
+ cache.set(scope, compiled);
4016
+ return compiled;
4017
+ };
4018
+ }
4019
+ function resolveProseRules(config = undefined, options = {}) {
4020
+ const rules = [];
4021
+ const defaults = config?.defaults ?? {};
4022
+ for (const rule of CONFIGURABLE_DEFAULT_RULES) {
4023
+ const override = defaults[rule.id];
4024
+ if (override === "off")
4025
+ continue;
4026
+ const group = rule.group;
4027
+ const scopes = override?.scopes ?? rule.scopes;
4028
+ const base = {};
4029
+ for (const scope of scopes) {
4030
+ base[scope] = scope === "source-comment" ? options.sourceCommentSeverity ?? rule.severity[scope] ?? "warning" : rule.severity[scope] ?? scopeDefaultSeverity(scope, options.sourceCommentSeverity);
4031
+ }
4032
+ rules.push({
4033
+ id: rule.id,
4034
+ group,
4035
+ custom: false,
4036
+ builtIn: rule.builtIn === true,
4037
+ scopes,
4038
+ message: rule.message,
4039
+ severity: applySeverity(scopes, base, override?.severity),
4040
+ exempt: override?.exempt ?? [],
4041
+ substringExempt: rule.exemptions,
4042
+ reportGroup: REPORT_GROUPS[rule.id],
4043
+ patternFor: defaultPatternFor(rule)
4044
+ });
4045
+ }
4046
+ for (const rule of config?.custom ?? []) {
4047
+ const group = groupOfScope(rule.scopes[0] ?? "") ?? "reader-resolvable";
4048
+ const base = {};
4049
+ for (const scope of rule.scopes)
4050
+ base[scope] = scopeDefaultSeverity(scope, options.sourceCommentSeverity);
4051
+ rules.push({
4052
+ id: rule.id,
4053
+ group,
4054
+ custom: true,
4055
+ builtIn: false,
4056
+ scopes: rule.scopes,
4057
+ message: rule.means,
4058
+ severity: applySeverity(rule.scopes, base, rule.severity),
4059
+ exempt: rule.exempt ?? [],
4060
+ substringExempt: [],
4061
+ patternFor: customPatternFor(rule, group === "reader-resolvable")
4062
+ });
4063
+ }
4064
+ if (options.decisionRecordsPath !== undefined)
4065
+ rules.push(decisionRecordCitationRule(options.decisionRecordsPath));
4066
+ const order = (rule) => {
4067
+ const at = RESOLVABLE_RUN_ORDER.indexOf(rule.id);
4068
+ return rule.custom || at === -1 ? RESOLVABLE_RUN_ORDER.length : at;
4069
+ };
4070
+ const resolvable = rules.filter((rule) => rule.group === "reader-resolvable");
4071
+ const sorted = resolvable.map((rule, index) => ({ rule, index })).sort((a, b) => order(a.rule) - order(b.rule) || a.index - b.index).map(({ rule }) => rule);
4072
+ return {
4073
+ rules: [...sorted, ...rules.filter((rule) => rule.group === "retired-vocabulary")],
4074
+ exempt: config?.exempt ?? [],
4075
+ repoRoot: options.repoRoot
4076
+ };
4077
+ }
4078
+ function rulesOfGroup(set, group) {
4079
+ return set.rules.filter((rule) => rule.group === group);
4080
+ }
4081
+ function rulesInScope(set, scope) {
4082
+ return set.rules.filter((rule) => rule.scopes.includes(scope));
4083
+ }
4084
+ var DEFAULT_PROSE_RULE_SET = resolveProseRules();
4085
+ var DECISION_RECORD_CITATION_ID = "decision-record-citation";
4086
+ var DECISION_RECORD_CITATION_SCOPES = ["ships", "product", "spec", "source-comment"];
4087
+ var DECISION_RECORD_CITATION_MESSAGE = "a decision-record number";
4088
+ function escapeRegExp(text) {
4089
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4090
+ }
4091
+ function decisionRecordCitationPattern(decisionRecordsPath) {
4092
+ const folder = escapeRegExp(normalizeRepoPath(decisionRecordsPath));
4093
+ return new RegExp(String.raw`\bADR[- ]?[0-9]+\b|(?<![A-Za-z0-9_-])${folder}/[0-9]+[A-Za-z0-9._-]*`, "g");
4094
+ }
4095
+ function decisionRecordCitationRule(decisionRecordsPath) {
4096
+ const folder = normalizeRepoPath(decisionRecordsPath);
4097
+ const pattern = decisionRecordCitationPattern(folder);
4098
+ const severity = {};
4099
+ for (const scope of DECISION_RECORD_CITATION_SCOPES)
4100
+ severity[scope] = "error";
4101
+ return {
4102
+ id: DECISION_RECORD_CITATION_ID,
4103
+ group: "reader-resolvable",
4104
+ custom: false,
4105
+ builtIn: false,
4106
+ scopes: DECISION_RECORD_CITATION_SCOPES,
4107
+ message: DECISION_RECORD_CITATION_MESSAGE,
4108
+ severity,
4109
+ exempt: [folder],
4110
+ substringExempt: [],
4111
+ patternFor: () => pattern
4112
+ };
4113
+ }
4114
+
3432
4115
  // ../../packages/aeg-core/src/reader-resolvable-prose.ts
3433
4116
  var PRODUCT_SLUG_SCOPE = [
3434
4117
  "apps/cli/src",
@@ -3440,8 +4123,8 @@ var PRODUCT_SLUG_SCOPE = [
3440
4123
  function isUnderOrEqual(path, prefix) {
3441
4124
  return path === prefix || path.startsWith(`${prefix}/`);
3442
4125
  }
3443
- function isProductScopeFile(path) {
3444
- return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
4126
+ function isProductScopeFile(path, productPaths) {
4127
+ return productPaths.some((prefix) => isUnderOrEqual(path, normalizeRepoPath(prefix)));
3445
4128
  }
3446
4129
  var SHIPS_PREFIX = "aeg-root/";
3447
4130
  function shipsArchivePrefix(shipsPrefix) {
@@ -3449,13 +4132,7 @@ function shipsArchivePrefix(shipsPrefix) {
3449
4132
  }
3450
4133
  var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
3451
4134
  function normalizeSpecPath(entry) {
3452
- let out = entry.replace(/\\/g, "/");
3453
- while (out.startsWith("./"))
3454
- out = out.slice(2);
3455
- out = out.replace(/\/{2,}/g, "/");
3456
- while (out.endsWith("/"))
3457
- out = out.slice(0, -1);
3458
- return out;
4135
+ return normalizeRepoPath(entry);
3459
4136
  }
3460
4137
  function isSpecFile2(path, specPaths) {
3461
4138
  if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
@@ -3467,7 +4144,7 @@ function isSpecFile2(path, specPaths) {
3467
4144
  function isClaudeMdFile(path) {
3468
4145
  return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
3469
4146
  }
3470
- function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
4147
+ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS, productPaths = PRODUCT_SLUG_SCOPE) {
3471
4148
  if (path.startsWith(shipsPrefix)) {
3472
4149
  return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
3473
4150
  }
@@ -3478,7 +4155,7 @@ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPr
3478
4155
  return "internal";
3479
4156
  if (isSpecFile2(path, specPaths))
3480
4157
  return "spec";
3481
- if (isProductScopeFile(path))
4158
+ if (isProductScopeFile(path, productPaths))
3482
4159
  return "product";
3483
4160
  return null;
3484
4161
  }
@@ -3503,9 +4180,16 @@ function lineAt(content, index) {
3503
4180
  }
3504
4181
  return line;
3505
4182
  }
3506
- var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
3507
- var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
3508
- var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
4183
+ var readerRules = rulesForGroup("reader-resolvable");
4184
+ var readerPattern = (id, scope = "prose") => {
4185
+ const pattern = readerRules.find((rule) => rule.id === id)?.patterns[scope];
4186
+ if (!(pattern instanceof RegExp))
4187
+ throw new Error(`default prose rule ${id} has no ${scope} pattern`);
4188
+ return pattern;
4189
+ };
4190
+ var FORGE_NUMBER_PATTERN = readerPattern("forge-number");
4191
+ var TRANCHE_SLUG_VN_PATTERN = readerPattern("tranche-slug");
4192
+ var TASK_NUMBER_PATTERN = readerPattern("task-number");
3509
4193
  function legacySlugPattern(legacySlugs) {
3510
4194
  if (legacySlugs.length === 0)
3511
4195
  return null;
@@ -3515,48 +4199,61 @@ function legacySlugPattern(legacySlugs) {
3515
4199
  function specGrandfatherPaths(specGrandfather) {
3516
4200
  return Array.isArray(specGrandfather) ? [...specGrandfather] : Object.keys(specGrandfather);
3517
4201
  }
3518
- function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4202
+ var REFERENCE_CLASSES = new Set(["ships", "reader-facing", "product", "spec"]);
4203
+ function referenceRulesFor(set, cls) {
4204
+ return rulesInScope(set, cls).filter((rule) => rule.group === "reader-resolvable" && rule.id !== "coined-term");
4205
+ }
4206
+ function citations(pattern, text, group) {
4207
+ const out = [];
4208
+ const re = pattern.global ? pattern : new RegExp(pattern.source, `${pattern.flags}g`);
4209
+ re.lastIndex = 0;
4210
+ let match = re.exec(text);
4211
+ while (match !== null) {
4212
+ if (match[0] === "") {
4213
+ re.lastIndex++;
4214
+ } else {
4215
+ const cited = group !== undefined ? match[group] ?? match[0] : match[0];
4216
+ out.push({ cited, index: match.index + match[0].indexOf(cited) });
4217
+ }
4218
+ match = re.exec(text);
4219
+ }
4220
+ re.lastIndex = 0;
4221
+ return out;
4222
+ }
4223
+ function customMessage(rule, cited) {
4224
+ return `${rule.id}: ${rule.message} ("${cited}")`;
4225
+ }
4226
+ function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS, options = {}) {
4227
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4228
+ const productPaths = options.productPaths ?? PRODUCT_SLUG_SCOPE;
3519
4229
  const findings = [];
3520
4230
  const legacyPattern = legacySlugPattern(legacySlugs);
3521
4231
  const grandfatheredWhole = new Set(Array.isArray(specGrandfather) ? specGrandfather : []);
3522
4232
  const limits = new Map(Array.isArray(specGrandfather) ? [] : Object.entries(specGrandfather));
3523
- const patterns = [
3524
- { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
3525
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
3526
- ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
3527
- ];
3528
- const productPatterns = [
3529
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
3530
- ];
3531
- const specPatterns = [
3532
- ...patterns,
3533
- { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
3534
- ];
3535
4233
  for (const file of files) {
3536
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
3537
- if (!cls || cls === "internal")
3538
- continue;
3539
- if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
4234
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths, productPaths);
4235
+ if (!cls || !REFERENCE_CLASSES.has(cls))
3540
4236
  continue;
3541
4237
  if (cls === "spec" && grandfatheredWhole.has(file.path))
3542
4238
  continue;
3543
- const blocking = cls === "product" || cls === "spec";
3544
4239
  const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
3545
- const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
3546
4240
  const fileFindings = [];
3547
- for (const { pattern, what, group } of patternsToRun) {
3548
- pattern.lastIndex = 0;
3549
- let match = pattern.exec(scrubbed);
3550
- while (match !== null) {
3551
- const cited = group !== undefined ? match[group] ?? match[0] : match[0];
3552
- const citedIndex = match.index + match[0].indexOf(cited);
4241
+ for (const rule of referenceRulesFor(set, cls)) {
4242
+ if (!ruleReads(set, rule, file.path))
4243
+ continue;
4244
+ const pattern = !rule.custom && rule.id === "legacy-batch-name" ? legacyPattern : rule.patternFor(cls);
4245
+ if (!pattern)
4246
+ continue;
4247
+ const blocking = rule.severity[cls] === "error";
4248
+ const what = cls === "product" ? `${rule.message} in product code` : rule.message;
4249
+ for (const { cited, index } of citations(pattern, scrubbed, rule.custom ? undefined : rule.reportGroup)) {
3553
4250
  fileFindings.push({
3554
4251
  file: file.path,
3555
- line: lineAt(scrubbed, citedIndex),
3556
- message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
3557
- blocking
4252
+ line: lineAt(scrubbed, index),
4253
+ message: rule.custom ? customMessage(rule, cited) : `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4254
+ blocking,
4255
+ rule: rule.id
3558
4256
  });
3559
- match = pattern.exec(scrubbed);
3560
4257
  }
3561
4258
  }
3562
4259
  const limit = cls === "spec" ? limits.get(file.path) : undefined;
@@ -3597,11 +4294,17 @@ function definesOrLinksGlossary(content, term) {
3597
4294
  return true;
3598
4295
  return /docs\/glossary|glossary\.md/i.test(content);
3599
4296
  }
3600
- function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
4297
+ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, options = {}) {
3601
4298
  const findings = [];
4299
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4300
+ const rule = set.rules.find((r) => !r.custom && r.id === "coined-term");
4301
+ if (!rule)
4302
+ return findings;
3602
4303
  for (const file of files) {
3603
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3604
- if (!cls || !SWEPT_CLASSES.has(cls))
4304
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, DEFAULT_SPEC_PATHS, options.productPaths);
4305
+ if (!cls || !SWEPT_CLASSES.has(cls) || !rule.scopes.includes(cls))
4306
+ continue;
4307
+ if (!ruleReads(set, rule, file.path))
3605
4308
  continue;
3606
4309
  const scrubbed = stripNonProse(file.path, file.content);
3607
4310
  for (const term of glossaryTerms) {
@@ -3614,14 +4317,15 @@ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, read
3614
4317
  file: file.path,
3615
4318
  line,
3616
4319
  message: `uses coined term "${term}" without defining it inline or linking the glossary`,
3617
- blocking: false
4320
+ blocking: rule.severity[cls] === "error",
4321
+ rule: rule.id
3618
4322
  });
3619
4323
  }
3620
4324
  }
3621
4325
  return findings;
3622
4326
  }
3623
- var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
3624
- var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
4327
+ var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = readerPattern("source-comment-tranche-slug", "comment");
4328
+ var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = readerPattern("source-comment-forge-number", "comment");
3625
4329
  function extractComments(path, content) {
3626
4330
  if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
3627
4331
  return content.replace(/[^\n]/g, "");
@@ -3718,39 +4422,40 @@ function extractComments(path, content) {
3718
4422
  }
3719
4423
  return out;
3720
4424
  }
3721
- function checkSourceComments(files, allowlist = []) {
4425
+ function checkSourceComments(files, allowlist = [], options = {}) {
3722
4426
  const findings = [];
3723
4427
  const allowed = new Set(allowlist);
3724
- const patterns = [
3725
- { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
3726
- { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
3727
- ];
4428
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4429
+ const rules = rulesInScope(set, "source-comment").filter((rule) => rule.group === "reader-resolvable");
3728
4430
  for (const file of files) {
3729
4431
  if (!file.path.endsWith(".ts"))
3730
4432
  continue;
3731
4433
  if (allowed.has(file.path))
3732
4434
  continue;
3733
4435
  const comments = extractComments(file.path, file.content);
3734
- for (const { pattern, what } of patterns) {
3735
- pattern.lastIndex = 0;
3736
- let match = pattern.exec(comments);
3737
- while (match !== null) {
4436
+ for (const rule of rules) {
4437
+ if (!ruleReads(set, rule, file.path))
4438
+ continue;
4439
+ const pattern = rule.patternFor("source-comment");
4440
+ if (!pattern)
4441
+ continue;
4442
+ for (const { cited, index } of citations(pattern, comments)) {
3738
4443
  findings.push({
3739
4444
  file: file.path,
3740
- line: lineAt(comments, match.index),
3741
- message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
3742
- blocking: false
4445
+ line: lineAt(comments, index),
4446
+ message: rule.custom ? customMessage(rule, cited) : `comment cites ${rule.message} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4447
+ blocking: rule.severity["source-comment"] === "error",
4448
+ rule: rule.id
3743
4449
  });
3744
- match = pattern.exec(comments);
3745
4450
  }
3746
4451
  }
3747
4452
  }
3748
4453
  return findings;
3749
4454
  }
3750
- function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4455
+ function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS, options = {}) {
3751
4456
  return [
3752
- ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
3753
- ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
4457
+ ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths, options),
4458
+ ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix, options)
3754
4459
  ];
3755
4460
  }
3756
4461
  function parseGlossaryTerms(glossaryContent) {
@@ -3953,6 +4658,17 @@ function checkDocClaims(files, fileReader) {
3953
4658
  };
3954
4659
  }
3955
4660
 
4661
+ // ../../packages/aeg-core/src/protected-paths.ts
4662
+ import { posix as posixPath } from "node:path";
4663
+ var PROTECTED_ADMIN_PATHS = ["vinaya.config.json", ".vinaya/doc-owners", ".github/", "aeg-root/"];
4664
+ function normalizeTouchedPath(path) {
4665
+ return posixPath.resolve("/", path.replace(/\\/g, "/")).replace(/^\/+/, "");
4666
+ }
4667
+ function isProtectedAdminPath(path) {
4668
+ const normalized = normalizeTouchedPath(path);
4669
+ return PROTECTED_ADMIN_PATHS.some((prefix) => normalized === prefix || normalized.startsWith(prefix));
4670
+ }
4671
+
3956
4672
  // ../../packages/aeg-core/src/issue-validation.ts
3957
4673
  function hasRationaleField(body, labelPattern) {
3958
4674
  const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
@@ -4072,13 +4788,20 @@ function globCoversPath(glob, path) {
4072
4788
  return !p.includes("/");
4073
4789
  return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
4074
4790
  }
4075
- function checkSurfaceGlobsResolve(body, resolvesToFile) {
4791
+ function surfaceEntryResolves(entry, resolvesToFile, pinnedFiles) {
4792
+ if (resolvesToFile(entry))
4793
+ return true;
4794
+ const directory = entry.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
4795
+ return pinnedFiles.some((path) => path.startsWith(`${directory}/`));
4796
+ }
4797
+ function checkSurfaceGlobsResolve(body, resolvesToFile) {
4076
4798
  const surface = parseIssueSurface(body);
4077
4799
  if (!surface.ok)
4078
4800
  return { status: "pass", errors: [] };
4801
+ const pinnedFiles = boundaryPinnedFiles(body);
4079
4802
  const errors = [];
4080
4803
  for (const glob of surface.value.in) {
4081
- if (!resolvesToFile(glob)) {
4804
+ if (!surfaceEntryResolves(glob, resolvesToFile, pinnedFiles)) {
4082
4805
  errors.push(`issue-validation Surface: \`${glob}\` in \`## Surface\`'s \`in:\` list matches no tracked file — a Surface that cannot resolve cannot render a brief's file list.`);
4083
4806
  }
4084
4807
  }
@@ -4108,6 +4831,14 @@ function recordedBeyondSurfacePaths(body) {
4108
4831
  return paths;
4109
4832
  }
4110
4833
  function checkSurfaceScope(changedFiles, surface, recorded) {
4834
+ for (const path of changedFiles) {
4835
+ if (!isProtectedAdminPath(path))
4836
+ continue;
4837
+ const normalized = normalizeTouchedPath(path);
4838
+ if (!surface.in.some((glob) => globCoversPath(glob, normalized))) {
4839
+ return { ok: false, violation: { path, reason: "protected" } };
4840
+ }
4841
+ }
4111
4842
  const listed = new Set(recorded);
4112
4843
  const violation = beyondSurfacePaths(changedFiles, surface).find((entry) => !listed.has(entry.path));
4113
4844
  return violation ? { ok: false, violation } : { ok: true };
@@ -4163,12 +4894,22 @@ function checkPartsCiteDefinedObjectives(body) {
4163
4894
  }
4164
4895
  return { status: errors.length > 0 ? "fail" : "pass", errors };
4165
4896
  }
4897
+ var ISSUE_LIVE_LINE_RE = /^-\s*\*{2}\[live\]\*{2}(.*)$/gim;
4898
+ function liveCommand(text) {
4899
+ const trimmed = text.trim();
4900
+ const span = /^(`+)(.+)\1$/.exec(trimmed);
4901
+ return span ? span[2].trim() : trimmed;
4902
+ }
4903
+ function liveItemsIn(region) {
4904
+ return [...region.matchAll(ISSUE_LIVE_LINE_RE)].map((m) => liveCommand(m[1] ?? "")).filter(Boolean);
4905
+ }
4906
+ function parseLiveTestPlanItems(body) {
4907
+ const located = locateTestPlanSection(body);
4908
+ return located.found ? liveItemsIn(located.section) : [];
4909
+ }
4166
4910
  function isTaskIssueLabelSet(labels) {
4167
4911
  return hasLabel("tranche", labels);
4168
4912
  }
4169
- function checkTrancheLabelPresence(_body, _labels) {
4170
- return { status: "pass", errors: [] };
4171
- }
4172
4913
  function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
4173
4914
  if (!isTaskIssueLabelSet(labels))
4174
4915
  return { status: "pass", errors: [] };
@@ -4184,6 +4925,7 @@ function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTi
4184
4925
  };
4185
4926
  }
4186
4927
  var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
4928
+ var PATH_TEXT = (body) => stripCode(body, { inlineSpans: "keep" });
4187
4929
  function isControlCodePoint(codePoint) {
4188
4930
  return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
4189
4931
  }
@@ -4244,8 +4986,14 @@ function checkProjectsRegistered(body, _labels, registeredNames) {
4244
4986
  }
4245
4987
  return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
4246
4988
  }
4989
+ function rationaleFieldText(text, labelPattern) {
4990
+ const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})[^\\n]*\\n?([\\s\\S]*?)(?=\\n\\s*(?:\\*\\*[A-Z]|#{1,4}\\s)|(?![\\s\\S]))`, "im");
4991
+ const m = re.exec(text);
4992
+ return m ? m[0] : "";
4993
+ }
4247
4994
  var DOC_PATH_RE = /(?:(?:aeg-root|apps|packages|specs|docs|tools|\.claude|\.github)\/[\w./@-]*\.(?:md|mdx)|\.claude\/(?:skills|rules)\/[\w./-]+|\b(?:docs-index|decisions|projects|state-machine|enforcement|process|README|CLAUDE)\.md\b|\b[\w-]+-(?:spec|decisions|backlog)\.md\b)/i;
4248
4995
  var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
4996
+ var RATIONALE_PATH_RE_GLOBAL = /`([\w.@-]+(?:\/[\w.@-]+)+)`/g;
4249
4997
  function normalizeEdgeId(s) {
4250
4998
  const qualified = splitSlugQualifiedEdge(s);
4251
4999
  return (qualified ? qualified.bareId : s).replace(/^#/, "").trim();
@@ -4253,6 +5001,15 @@ function normalizeEdgeId(s) {
4253
5001
  function edgesNameEachOther(a, b) {
4254
5002
  return a.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(b.ref)) || b.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(a.ref));
4255
5003
  }
5004
+ var BOUNDARY_OUT_RE = /\bOut\s*:\s*([\s\S]*)$/im;
5005
+ function boundaryOutText(body) {
5006
+ const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
5007
+ const m = BOUNDARY_OUT_RE.exec(boundary);
5008
+ return m ? m[1] : "";
5009
+ }
5010
+ function namedPathsIn(text) {
5011
+ return [...new Set([...text.matchAll(RATIONALE_PATH_RE_GLOBAL)].map((m) => m[1]))].filter((p) => !/^https?:\/\//i.test(p));
5012
+ }
4256
5013
  var FILE_EXTENSIONS = new Set([
4257
5014
  "ts",
4258
5015
  "tsx",
@@ -4274,6 +5031,11 @@ var FILE_EXTENSIONS = new Set([
4274
5031
  "html",
4275
5032
  "css"
4276
5033
  ]);
5034
+ function boundaryPinnedFiles(body) {
5035
+ const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
5036
+ const excluded = new Set(namedPathsIn(boundaryOutText(body)));
5037
+ return namedPathsIn(boundary).filter((p) => looksLikeFilePath(p) && !excluded.has(p));
5038
+ }
4277
5039
  var CI_SHARD_DIR = "apps/cli/tests/ci-shards";
4278
5040
  var CI_SHARD_PROBE = `${CI_SHARD_DIR}/shard-1.txt`;
4279
5041
 
@@ -4298,7 +5060,7 @@ function isGrandfathered(isoDate) {
4298
5060
  return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
4299
5061
  }
4300
5062
  var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
4301
- function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
5063
+ function checkA1(entries, principalAllowlist) {
4302
5064
  const failures = [];
4303
5065
  for (const e of entries) {
4304
5066
  if (!e.facts)
@@ -4328,6 +5090,37 @@ function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
4328
5090
  note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4329
5091
  };
4330
5092
  }
5093
+ function checkA2(entries, hasProvenanceByKey) {
5094
+ const failures = [];
5095
+ for (const e of entries) {
5096
+ if (!e.facts)
5097
+ continue;
5098
+ if (e.facts.issueState !== "closed" || e.facts.prState !== "merged")
5099
+ continue;
5100
+ const key = `${e.trancheSlug}/${e.task.id}`;
5101
+ const hasProvenance = hasProvenanceByKey.get(key);
5102
+ if (hasProvenance === undefined)
5103
+ continue;
5104
+ if (!hasProvenance) {
5105
+ failures.push({
5106
+ code: "archived-without-provenance",
5107
+ issue: e.task.issue,
5108
+ tranche: e.trancheSlug,
5109
+ task: e.task.id,
5110
+ reason: "Closing PR has no `### AEG provenance` comment (Archivist close-out missing)",
5111
+ grandfathered: isGrandfathered(e.facts.mergedAt)
5112
+ });
5113
+ }
5114
+ }
5115
+ const activeFails = failures.filter((f) => !f.grandfathered);
5116
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
5117
+ return {
5118
+ check: "A2",
5119
+ status,
5120
+ failures,
5121
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
5122
+ };
5123
+ }
4331
5124
  function checkA3(entries) {
4332
5125
  const failures = [];
4333
5126
  for (const e of entries) {
@@ -4543,6 +5336,33 @@ function checkL1(files, entriesBySlug) {
4543
5336
  note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
4544
5337
  };
4545
5338
  }
5339
+ function checkL2(files, entriesBySlug) {
5340
+ const failures = [];
5341
+ for (const f of files) {
5342
+ if (!f.archived)
5343
+ continue;
5344
+ const entries = entriesBySlug.get(f.slug) ?? [];
5345
+ for (const e of entries) {
5346
+ if (!e.facts)
5347
+ continue;
5348
+ if (e.facts.issueState === "open") {
5349
+ failures.push({
5350
+ code: "premature-archive",
5351
+ issue: e.task.issue,
5352
+ tranche: f.slug,
5353
+ task: e.task.id,
5354
+ reason: `Archived tranche has open task-Issue #${e.task.issue ?? "?"} (premature archive)`
5355
+ });
5356
+ }
5357
+ }
5358
+ }
5359
+ return {
5360
+ check: "L2",
5361
+ status: "info",
5362
+ failures,
5363
+ note: failures.length > 0 ? `${failures.length} archived tranche(s) with an open task-Issue — investigate (advisory)` : undefined
5364
+ };
5365
+ }
4546
5366
  function checkL3(files) {
4547
5367
  const active = files.filter((f) => !f.archived);
4548
5368
  return {
@@ -4552,6 +5372,51 @@ function checkL3(files) {
4552
5372
  note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
4553
5373
  };
4554
5374
  }
5375
+ function checkL4(activeTrancheSlugs, issueMilestones) {
5376
+ const activeSet = new Set(activeTrancheSlugs);
5377
+ const failures = [];
5378
+ for (const f of issueMilestones) {
5379
+ if (!activeSet.has(f.tranche))
5380
+ continue;
5381
+ if (f.milestoneTitle === f.tranche)
5382
+ continue;
5383
+ failures.push({
5384
+ code: "milestone-drift",
5385
+ issue: f.issue,
5386
+ tranche: f.tranche,
5387
+ 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`
5388
+ });
5389
+ }
5390
+ return {
5391
+ check: "L4",
5392
+ status: "info",
5393
+ failures,
5394
+ 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
5395
+ };
5396
+ }
5397
+ function checkL5(activeTrancheSlugs, entriesBySlug) {
5398
+ const failures = [];
5399
+ for (const slug of activeTrancheSlugs) {
5400
+ const entries = entriesBySlug.get(slug) ?? [];
5401
+ const withFacts = entries.filter((e) => e.facts !== undefined);
5402
+ if (withFacts.length === 0)
5403
+ continue;
5404
+ const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
5405
+ if (allClosed) {
5406
+ failures.push({
5407
+ code: "tranche-not-archived",
5408
+ tranche: slug,
5409
+ reason: "Every task Issue is closed but the tranche is not recorded as complete — archive it"
5410
+ });
5411
+ }
5412
+ }
5413
+ return {
5414
+ check: "L5",
5415
+ status: failures.length > 0 ? "fail" : "pass",
5416
+ failures,
5417
+ note: failures.length > 0 ? `${failures.length} tranche(s) whose task Issues are all closed but were never archived` : undefined
5418
+ };
5419
+ }
4555
5420
  function extractClosesReferences(prBody) {
4556
5421
  const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
4557
5422
  const stripped = stripCode(prBody);
@@ -4647,6 +5512,58 @@ function extractIssue(body) {
4647
5512
  }
4648
5513
  // ../../packages/aeg-core/src/review-input-manifest.ts
4649
5514
  import { createHash as createHash4 } from "node:crypto";
5515
+
5516
+ // ../../packages/aeg-core/src/ruling-ordinal.ts
5517
+ var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
5518
+ function newestPrincipalRulingOrdinal(comments, allowlist) {
5519
+ let best = 0;
5520
+ for (const c of comments) {
5521
+ if (!isPrincipal(c.author, allowlist))
5522
+ continue;
5523
+ const firstLine = (c.body.split(`
5524
+ `)[0] ?? "").trim();
5525
+ const m = RULING_MARKER_ORDINAL.exec(firstLine);
5526
+ if (!m)
5527
+ continue;
5528
+ const k = Number.parseInt(m[1], 10);
5529
+ if (k > best)
5530
+ best = k;
5531
+ }
5532
+ return best;
5533
+ }
5534
+ function parseRulingIdentity(rulingId) {
5535
+ const m = /^(issue-)?(\d+)-(\d+)$/.exec(rulingId);
5536
+ if (!m)
5537
+ return null;
5538
+ const ref = Number.parseInt(m[2], 10);
5539
+ const ordinal = Number.parseInt(m[3], 10);
5540
+ if (ref <= 0 || ordinal <= 0)
5541
+ return null;
5542
+ return { target: m[1] ? "issue" : "pr", ref, ordinal };
5543
+ }
5544
+ function principalRulingTextById(comments, allowlist, rulingId) {
5545
+ const identity = parseRulingIdentity(rulingId);
5546
+ if (identity === null)
5547
+ return null;
5548
+ const matches = comments.filter((c) => {
5549
+ if (!isPrincipal(c.author, allowlist))
5550
+ return false;
5551
+ const m = RULING_MARKER_ORDINAL.exec((c.body.split(`
5552
+ `)[0] ?? "").trim());
5553
+ return m !== null && Number.parseInt(m[1], 10) === identity.ordinal;
5554
+ });
5555
+ if (matches.length !== 1)
5556
+ return null;
5557
+ const body = matches[0].body;
5558
+ const idx = body.indexOf(`
5559
+ `);
5560
+ return idx === -1 ? "" : body.slice(idx + 1).trim();
5561
+ }
5562
+
5563
+ // ../../packages/aeg-core/src/review-input-manifest.ts
5564
+ function pauseBoundRulingDigest(rulingText) {
5565
+ return createHash4("sha256").update(rulingText).digest("hex");
5566
+ }
4650
5567
  function briefHash(brief) {
4651
5568
  return createHash4("sha256").update(`${brief}
4652
5569
  `).digest("hex");
@@ -4707,14 +5624,19 @@ function compareManifest(echoed, current, patchIdOf) {
4707
5624
  const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4708
5625
  const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4709
5626
  const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
5627
+ const legacyCurrent = current.manifestVersion === undefined;
5628
+ const manifestVersion = legacyCurrent ? echoed.manifestVersion === undefined || echoed.manifestVersion === null : echoed.manifestVersion === current.manifestVersion;
5629
+ const pauseBoundRuling = legacyCurrent ? true : Object.hasOwn(echoed, "pauseBoundRuling") && JSON.stringify(echoed.pauseBoundRuling) === JSON.stringify(current.pauseBoundRuling);
4710
5630
  const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4711
5631
  return {
4712
- bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
5632
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && pauseBoundRuling && manifestVersion && policyDigestBound,
4713
5633
  head,
4714
5634
  base,
4715
5635
  briefHash: briefHashBound,
4716
5636
  objectivesVersion,
4717
5637
  rulingOrdinal,
5638
+ pauseBoundRuling,
5639
+ manifestVersion,
4718
5640
  policyDigest: policyDigestBound
4719
5641
  };
4720
5642
  }
@@ -4730,7 +5652,7 @@ function renderGateDeferred(deferred) {
4730
5652
  return ` ${deferred.length} finding(s) deferred, not blocking this round: ${items}.`;
4731
5653
  }
4732
5654
  function checkReviewGate(input) {
4733
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
5655
+ const { principalAllowlist } = input;
4734
5656
  const waived = isWaiverLabelActorVerified({
4735
5657
  label: WAIVER_LABEL_REVIEW,
4736
5658
  labels: input.labels,
@@ -4769,27 +5691,33 @@ function checkReviewGate(input) {
4769
5691
  const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4770
5692
  const securityClean = securityTextClean && securityPolicyClean;
4771
5693
  const currentManifest = {
5694
+ ...input.manifestVersion === undefined ? {} : { manifestVersion: input.manifestVersion },
4772
5695
  headSha: input.headSha,
4773
5696
  baseSha: input.baseSha ?? null,
4774
5697
  briefHash: input.briefHash ?? null,
4775
5698
  objectivesVersion: input.objectivesVersion,
4776
5699
  rulingOrdinal: input.rulingOrdinal,
5700
+ pauseBoundRuling: input.pauseBoundRuling ?? null,
4777
5701
  policyDigest: policyDigest(policy)
4778
5702
  };
4779
5703
  const codeReviewEchoed = {
5704
+ manifestVersion: codeReview.manifestVersion,
4780
5705
  headSha: codeReview.headSha,
4781
5706
  baseSha: codeReview.baseSha,
4782
5707
  briefHash: codeReview.briefHash,
4783
5708
  objectivesVersion: codeReview.objectivesVersion,
4784
5709
  rulingOrdinal: codeReview.rulingOrdinal,
5710
+ pauseBoundRuling: codeReview.pauseBoundRuling,
4785
5711
  policyDigest: codeReview.policyDigest
4786
5712
  };
4787
5713
  const securityEchoed = {
5714
+ manifestVersion: security.manifestVersion,
4788
5715
  headSha: security.headSha,
4789
5716
  baseSha: security.baseSha,
4790
5717
  briefHash: security.briefHash,
4791
5718
  objectivesVersion: security.objectivesVersion,
4792
5719
  rulingOrdinal: security.rulingOrdinal,
5720
+ pauseBoundRuling: security.pauseBoundRuling,
4793
5721
  policyDigest: security.policyDigest
4794
5722
  };
4795
5723
  const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
@@ -4828,6 +5756,10 @@ function checkReviewGate(input) {
4828
5756
  problems.push(`the newest code-review verdict was cast against brief hash ${codeReview.briefHash ?? "none"}, the frozen brief's current hash is ${currentManifest.briefHash ?? "none"}`);
4829
5757
  } else if (!codeReviewBinding.policyDigest) {
4830
5758
  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}`);
5759
+ } else if (!codeReviewBinding.manifestVersion) {
5760
+ problems.push(`the newest code-review verdict echoes manifest version ${codeReview.manifestVersion ?? "none"}, the frozen review-input manifest is version ${currentManifest.manifestVersion ?? "unversioned"}`);
5761
+ } else if (!codeReviewBinding.pauseBoundRuling) {
5762
+ problems.push(`the newest code-review verdict echoes pauseBoundRuling ${renderBinding(codeReview.pauseBoundRuling)}, the frozen review-input manifest binds ${renderBinding(currentManifest.pauseBoundRuling)}`);
4831
5763
  }
4832
5764
  if (!securityTextClean) {
4833
5765
  problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
@@ -4845,6 +5777,10 @@ function checkReviewGate(input) {
4845
5777
  problems.push(`the newest security-review verdict was cast against brief hash ${security.briefHash ?? "none"}, the frozen brief's current hash is ${currentManifest.briefHash ?? "none"}`);
4846
5778
  } else if (!securityBinding.policyDigest) {
4847
5779
  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}`);
5780
+ } else if (!securityBinding.manifestVersion) {
5781
+ problems.push(`the newest security-review verdict echoes manifest version ${security.manifestVersion ?? "none"}, the frozen review-input manifest is version ${currentManifest.manifestVersion ?? "unversioned"}`);
5782
+ } else if (!securityBinding.pauseBoundRuling) {
5783
+ problems.push(`the newest security-review verdict echoes pauseBoundRuling ${renderBinding(security.pauseBoundRuling)}, the frozen review-input manifest binds ${renderBinding(currentManifest.pauseBoundRuling)}`);
4848
5784
  }
4849
5785
  const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4850
5786
  return {
@@ -4853,29 +5789,16 @@ function checkReviewGate(input) {
4853
5789
  waived: false
4854
5790
  };
4855
5791
  }
5792
+ function renderBinding(binding) {
5793
+ if (binding === undefined)
5794
+ return "(absent)";
5795
+ return binding === null ? "(none)" : `${binding.rulingId}|${binding.pauseId}|${binding.contentDigest}`;
5796
+ }
4856
5797
  var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4857
5798
  var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4858
5799
  function isChangesetsReleasePr(branch, author, expectedAuthor) {
4859
5800
  return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4860
5801
  }
4861
- // ../../packages/aeg-core/src/ruling-ordinal.ts
4862
- var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4863
- function newestPrincipalRulingOrdinal(comments, allowlist) {
4864
- let best = 0;
4865
- for (const c of comments) {
4866
- if (!isPrincipal(c.author, allowlist))
4867
- continue;
4868
- const firstLine = (c.body.split(`
4869
- `)[0] ?? "").trim();
4870
- const m = RULING_MARKER_ORDINAL.exec(firstLine);
4871
- if (!m)
4872
- continue;
4873
- const k = Number.parseInt(m[1], 10);
4874
- if (k > best)
4875
- best = k;
4876
- }
4877
- return best;
4878
- }
4879
5802
  // ../../packages/aeg-core/src/markdown-table.ts
4880
5803
  function splitRow(line) {
4881
5804
  const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
@@ -5027,7 +5950,6 @@ var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
5027
5950
  var NON_GATE_BIN_NAMES = NON_GATE_BINS;
5028
5951
  var TWIN_CANDIDATE_EXCEPTIONS = {
5029
5952
  "apps/cli/src/checks/bin/check-dead-branch-push.ts": 'Ring 0 "Pushing to a branch whose pull request already resolved" (implementation: check-push-target.ts)',
5030
- "apps/cli/src/checks/bin/check-issue-assignment.ts": `Ring 0 "A task branch's first push (Issue self-assignment)" (implementation: assign-task-issue.ts)`,
5031
5953
  "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
5032
5954
  };
5033
5955
  var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
@@ -5251,72 +6173,10 @@ function compareToBaseline(current, baseline) {
5251
6173
  };
5252
6174
  }
5253
6175
  // ../../packages/aeg-core/src/retired-vocabulary.ts
5254
- var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
5255
- var RETIRED_PATTERNS = [
5256
- String.raw`\bD-[0-9]{3}\b`,
5257
- "D-(###|NNN|nnn|xxx)",
5258
- "decision (entry|logged)",
5259
- "decision-log entry",
5260
- "decision log entry",
5261
- "decision log(s|ged|ging)?([^a-z]|$)",
5262
- "decision-log",
5263
- "decision entr",
5264
- "decisions? (are |is )?logged",
5265
- "log entries",
5266
- String.raw`decisions\.md`,
5267
- "decisions-legacy",
5268
- "CONTRADICTION",
5269
- "assumes Tier 3",
5270
- "Lock: ?YES",
5271
- "Lock: ?NO",
5272
- "lock approvals?",
5273
- "approves locks",
5274
- "Conforms to lock",
5275
- "Challenges lock",
5276
- "checkDecisionNumbersFresh",
5277
- String.raw`roles/team-leader\.md`,
5278
- String.raw`\(,`,
5279
- String.raw`,\)`,
5280
- String.raw`\(\.\)`,
5281
- ...PLAN_ON_DISK_PATTERNS
5282
- ];
5283
- var TRANCHE_MODEL_FILE = "/tranche-model.md";
5284
- var RETIRED_EXEMPT_SUBSTRINGS = [
5285
- "docs/decisions-legacy.md",
5286
- "apps/herald-ai/docs/",
5287
- "apps/vada-ai/docs/",
5288
- "aeg-root/tranches/completed/",
5289
- "packages/aeg-core/src/docs/published-prose",
5290
- "packages/aeg-core/src/retired-vocabulary.test.ts",
5291
- "packages/aeg-core/src/retired-vocabulary.ts",
5292
- "/fixtures/",
5293
- "/node_modules/",
5294
- "/.next/",
5295
- "/.turbo/"
5296
- ];
5297
- var PATTERN_EXEMPT = {
5298
- [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
5299
- [String.raw`decisions\.md`]: [
5300
- "docs-index.md",
5301
- "apps/vada-ai/specs/legacy/README.md",
5302
- "apps/vada-ai/specs/vada-product-spec.md",
5303
- "apps/vada-ai/web/CLAUDE.md",
5304
- "apps/vada-ai/CLAUDE.md"
5305
- ],
5306
- "decisions-legacy": [
5307
- "packages/aeg-core/src/file-classify.ts",
5308
- "packages/aeg-core/src/file-classify.test.ts",
5309
- "packages/aeg-core/src/pr-tier.test.ts",
5310
- "docs-index.md",
5311
- ".claude/skills/database/SKILL.md",
5312
- ".claude/skills/vada-architecture/SKILL.md",
5313
- "apps/vada-ai/specs/vada-byok-principles.md",
5314
- "apps/vada-ai/web/CLAUDE.md",
5315
- "apps/vada-ai/CLAUDE.md"
5316
- ],
5317
- CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
5318
- ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
5319
- };
6176
+ var retiredRules = rulesForGroup("retired-vocabulary");
6177
+ var RETIRED_PATTERNS = retiredRules.map((rule) => rule.patterns.repository);
6178
+ var PATTERN_EXEMPT = RETIRED_PATTERN_EXEMPTIONS;
6179
+ var DEFAULT_PATTERN_OF = new Map(retiredRules.map((rule) => [rule.id, rule.patterns.repository]));
5320
6180
  function lineNumbers(content, pattern) {
5321
6181
  const out = [];
5322
6182
  const lines = content.split(`
@@ -5327,22 +6187,29 @@ function lineNumbers(content, pattern) {
5327
6187
  }
5328
6188
  return out;
5329
6189
  }
5330
- function scanRetiredVocabulary(files) {
6190
+ function scanRetiredVocabulary(files, rules = DEFAULT_PROSE_RULE_SET) {
5331
6191
  const findings = [];
6192
+ const retired = rulesOfGroup(rules, "retired-vocabulary");
5332
6193
  for (const file of files) {
5333
- if (RETIRED_EXEMPT_SUBSTRINGS.some((e) => file.path.includes(e)))
5334
- continue;
5335
- for (const pattern of RETIRED_PATTERNS) {
5336
- const patternExempt = PATTERN_EXEMPT[pattern] ?? [];
5337
- if (patternExempt.some((e) => file.path.includes(e)))
6194
+ for (const rule of retired) {
6195
+ if (rule.substringExempt.some((e) => file.path.includes(e)))
6196
+ continue;
6197
+ if (!ruleReads(rules, rule, file.path))
6198
+ continue;
6199
+ const re = rule.patternFor("repository");
6200
+ if (!re)
6201
+ continue;
6202
+ const pattern = rule.custom ? re.source : DEFAULT_PATTERN_OF.get(rule.id) ?? re.source;
6203
+ if (!rule.custom && (PATTERN_EXEMPT[pattern] ?? []).some((e) => file.path.includes(e)))
5338
6204
  continue;
5339
- const re = new RegExp(pattern);
5340
6205
  for (const line of lineNumbers(file.content, re)) {
5341
6206
  findings.push({
5342
6207
  file: file.path,
5343
6208
  line,
5344
6209
  pattern,
5345
- message: `claims a retired AEG mechanism is still live (matches /${pattern}/)`
6210
+ message: rule.custom ? `${rule.id}: ${rule.message} (matches /${pattern}/)` : `claims a retired AEG mechanism is still live (matches /${pattern}/)`,
6211
+ rule: rule.id,
6212
+ blocking: rule.severity.repository === "error"
5346
6213
  });
5347
6214
  }
5348
6215
  }
@@ -5366,7 +6233,7 @@ function isSelfDependency(dep, task, issue) {
5366
6233
  function checkDispatchReadiness(input) {
5367
6234
  const { trancheSlug, task } = input;
5368
6235
  const taskLabel = `task ${task.id} (tranche ${trancheSlug})`;
5369
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
6236
+ const { principalAllowlist } = input;
5370
6237
  const blockerDetails = [];
5371
6238
  const push = (blockerClass, message) => {
5372
6239
  blockerDetails.push({ class: blockerClass, message });
@@ -5458,6 +6325,16 @@ function pushesAnyBranchRef(pushRefs) {
5458
6325
  return pushRefs.split(`
5459
6326
  `).map((line) => line.trim()).filter((line) => line.length > 0).some((line) => line.split(/\s+/)[2]?.startsWith("refs/heads/") === true);
5460
6327
  }
6328
+ function resolveDefaultBranch(facts) {
6329
+ const { originHead, hasOriginMain, hasOriginMaster } = facts;
6330
+ if (originHead !== null && originHead !== "")
6331
+ return originHead;
6332
+ if (hasOriginMain)
6333
+ return "main";
6334
+ if (hasOriginMaster)
6335
+ return "master";
6336
+ return null;
6337
+ }
5461
6338
  function checkMainBranchRefusal(facts) {
5462
6339
  const { currentSymbolicBranch, defaultBranch, pushRefs = null } = facts;
5463
6340
  if (currentSymbolicBranch === null)
@@ -5718,54 +6595,61 @@ function checkFirstPushDispatchGate(input) {
5718
6595
  reason: `verify-dispatch reports READY TO DISPATCH for \`${branch}\`.`
5719
6596
  };
5720
6597
  }
5721
- // ../../packages/aeg-core/src/issue-assignment.ts
5722
- function decideIssueAssignment(input) {
5723
- const { branch, remoteRefExists, issue, assignees, login } = input;
5724
- if (parseTaskBranch(branch) === null) {
5725
- return {
5726
- action: "skip",
5727
- reason: `Branch \`${branch}\` is not a task/<tranche>/<n> branch — Issue self-assignment only applies to task branches.`
5728
- };
5729
- }
5730
- if (remoteRefExists) {
5731
- return {
5732
- action: "skip",
5733
- reason: `Branch \`${branch}\` already exists on the remote — not its first push, nothing to assign.`
5734
- };
5735
- }
5736
- if (issue === null) {
5737
- return {
5738
- action: "skip",
5739
- reason: `No Issue resolved for \`${branch}\` from its topology row — skipping self-assignment (the gate owns refusing an unplanned branch).`
5740
- };
5741
- }
5742
- if (assignees === null) {
5743
- return {
5744
- action: "skip",
5745
- reason: `Could not read Issue #${issue}'s current assignees — skipping rather than risking a double-assign (fail-open, never a guess).`
5746
- };
5747
- }
5748
- if (assignees.length > 0) {
5749
- return {
5750
- action: "skip",
5751
- reason: `Issue #${issue} is already assigned (${assignees.join(", ")}) — no-op.`
5752
- };
5753
- }
5754
- if (login === null) {
5755
- return {
5756
- action: "skip",
5757
- reason: "Could not resolve the authenticated `gh` login — never assigning anyone other than the actual pusher, so skipping."
5758
- };
6598
+ // ../../packages/aeg-core/src/live-record.ts
6599
+ var RECORD_LINE_RE = /^-\s*\[([ xX])\]\s*\*\*\[live\]\*\*\s+(`+) ?(.+?) ?\2(?!`)\s+—\s+(passed|failed|unverified)\s+at\s+`([^`]+)`/;
6600
+ function liveMarkers(body) {
6601
+ const masked = maskCode(body);
6602
+ return [...masked.matchAll(/<!--\s*AEG:LIVE:(?:START|END)\s*-->/g)].map((m) => ({
6603
+ start: m.index,
6604
+ end: m.index + m[0].length
6605
+ }));
6606
+ }
6607
+ var AMBIGUOUS_RECORD_LINE = {
6608
+ line: "- [ ] **[live]** the pull request body carries more than one `AEG:LIVE` marker pair, so the driver's record cannot be told apart",
6609
+ ticked: false,
6610
+ command: "",
6611
+ outcome: "failed",
6612
+ head: ""
6613
+ };
6614
+ function readLiveRecord(body) {
6615
+ const markers = liveMarkers(body).length;
6616
+ if (markers === 0)
6617
+ return [];
6618
+ if (markers !== 2)
6619
+ return [AMBIGUOUS_RECORD_LINE];
6620
+ const region = anchoredRegion(body, "LIVE");
6621
+ if (region === null)
6622
+ return [];
6623
+ const lines = [];
6624
+ for (const raw of region.split(`
6625
+ `)) {
6626
+ const line = raw.trim();
6627
+ const m = RECORD_LINE_RE.exec(line);
6628
+ if (!m)
6629
+ continue;
6630
+ lines.push({
6631
+ line,
6632
+ ticked: m[1].toLowerCase() === "x",
6633
+ command: m[3],
6634
+ outcome: m[4],
6635
+ head: m[5]
6636
+ });
5759
6637
  }
5760
- return {
5761
- action: "assign",
5762
- issue,
5763
- login,
5764
- reason: `First push of \`${branch}\` — assigning Issue #${issue} to @${login} (the authenticated pusher).`
5765
- };
6638
+ return lines;
5766
6639
  }
5767
6640
  // ../../packages/aeg-core/src/test-plan-gate.ts
5768
- function evaluateTestPlanGate(body, branch) {
6641
+ function gradedLiveLines(record, live) {
6642
+ if (live === undefined)
6643
+ return record.map((entry) => entry.line);
6644
+ const commands = new Set(live.liveCommands);
6645
+ const others = record.filter((entry) => !commands.has(entry.command)).map((entry) => entry.line);
6646
+ const graded = live.liveCommands.map((command) => {
6647
+ const atHead = record.filter((entry) => entry.command === command && entry.head === live.head);
6648
+ return (atHead.find((entry) => entry.ticked) ?? atHead[0])?.line ?? `- [ ] **[live]** \`${command}\` — no passed run recorded at \`${live.head || "an unknown head"}\``;
6649
+ });
6650
+ return [...others, ...graded];
6651
+ }
6652
+ function evaluateTestPlanGate(body, branch, live) {
5769
6653
  if (!body) {
5770
6654
  return {
5771
6655
  verdict: "pass",
@@ -5776,7 +6660,9 @@ function evaluateTestPlanGate(body, branch) {
5776
6660
  };
5777
6661
  }
5778
6662
  const located = locateTestPlanSection(body);
5779
- if (!located.found) {
6663
+ const liveLines = gradedLiveLines(readLiveRecord(body), live);
6664
+ const liveUnticked = liveLines.some((line) => /^[-*]\s+\[\s\]/.test(line));
6665
+ if (!located.found && !liveUnticked) {
5780
6666
  if (parseTaskBranchIdentity(branch) !== null) {
5781
6667
  return {
5782
6668
  verdict: "fail",
@@ -5796,15 +6682,18 @@ function evaluateTestPlanGate(body, branch) {
5796
6682
  ]
5797
6683
  };
5798
6684
  }
5799
- const section = located.section;
5800
- if (/unit-tests-only/i.test(section)) {
6685
+ const section = located.found ? located.section : "";
6686
+ if (/unit-tests-only/i.test(section) && !liveUnticked) {
5801
6687
  return {
5802
6688
  verdict: "pass",
5803
6689
  messages: ["Test Plan: unit-tests-only — pure-logic brief, CI unit-tests are the proof.", "PASS."]
5804
6690
  };
5805
6691
  }
5806
- const checkboxLines = section.split(`
5807
- `).map((line) => line.trimStart()).filter((line) => /^[-*]\s+\[[ xX]\]\s*\*{0,2}\[principal\]\*{0,2}/i.test(line));
6692
+ const checkboxLines = [
6693
+ ...section.split(`
6694
+ `).map((line) => line.trimStart()).filter((line) => /^[-*]\s+\[[ xX]\]\s*\*{0,2}\[principal\]\*{0,2}/i.test(line)),
6695
+ ...liveLines
6696
+ ];
5808
6697
  if (checkboxLines.length === 0) {
5809
6698
  return {
5810
6699
  verdict: "pass",
@@ -5821,7 +6710,9 @@ function evaluateTestPlanGate(body, branch) {
5821
6710
  messages.push("", "FAIL — the following [principal] Test Plan items are unticked:");
5822
6711
  for (const line of unchecked)
5823
6712
  messages.push(` ${line}`);
5824
- messages.push("", "Per aeg-root/roles/developer.md (Verification), a PR is not mergeable while any [principal] Test Plan box is unticked.", "The Principal runs the item in a real signed-in browser and ticks the box.", "Note: editing the PR body does not retrigger most workflows. If your PR body changes do not surface here, push an empty commit to re-run.");
6713
+ 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 ? [
6714
+ "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."
6715
+ ] : [], "Note: editing the PR body does not retrigger most workflows. If your PR body changes do not surface here, push an empty commit to re-run.");
5825
6716
  return { verdict: "fail", messages };
5826
6717
  }
5827
6718
  messages.push("All [principal] Test Plan items ticked — runtime verification complete.", "PASS.");
@@ -6010,9 +6901,11 @@ var LineageSchema = z3.object({
6010
6901
  parent: z3.string().nullable()
6011
6902
  }).strict();
6012
6903
  var InputVersionsSchema = z3.object({
6904
+ manifest_version: z3.literal(2).nullable().optional(),
6013
6905
  objectives_version: z3.string().nullable(),
6014
6906
  brief_hash: z3.string().nullable(),
6015
6907
  ruling_ordinal: z3.number().int().nullable(),
6908
+ pause_bound_ruling: z3.object({ rulingId: z3.string().min(1), pauseId: z3.string().min(1), contentDigest: z3.string().min(1) }).strict().nullable().optional(),
6016
6909
  policy_digest: z3.string().nullable()
6017
6910
  }).strict();
6018
6911
  var ProvenanceSchema = z3.enum(["parent_attributed", "env_correlated", "self_reported", "unavailable"]);
@@ -6050,7 +6943,17 @@ var HeaderMetaV3Schema = z3.object({
6050
6943
  runtime: z3.string().nullable(),
6051
6944
  source: z3.string().nullable()
6052
6945
  }).strict();
6053
- var HeaderMetaSchema = z3.discriminatedUnion("schema", [HeaderMetaV1Schema, HeaderMetaV2Schema, HeaderMetaV3Schema]);
6946
+ var HeaderMetaV4Schema = HeaderMetaV3Schema.extend({
6947
+ schema: z3.literal(4),
6948
+ process: z3.object({ id: z3.string(), version: z3.string().nullable(), digest: z3.string().nullable() }).strict(),
6949
+ runner: z3.object({ id: z3.string(), version: z3.string().nullable() }).strict()
6950
+ }).strict();
6951
+ var HeaderMetaSchema = z3.discriminatedUnion("schema", [
6952
+ HeaderMetaV1Schema,
6953
+ HeaderMetaV2Schema,
6954
+ HeaderMetaV3Schema,
6955
+ HeaderMetaV4Schema
6956
+ ]);
6054
6957
  var SubjectSchema = z3.object({
6055
6958
  issue: z3.number().int().nullable(),
6056
6959
  pr: z3.number().int().optional(),
@@ -6270,6 +7173,75 @@ var DevReviewLoopEventSchema = z3.discriminatedUnion("event", [
6270
7173
  round: z3.number().int(),
6271
7174
  phase: z3.string()
6272
7175
  }).strict(),
7176
+ z3.object({
7177
+ ...loopShared,
7178
+ event: z3.literal("conflict_reentry"),
7179
+ task: z3.number().int(),
7180
+ pr: z3.number().int().positive(),
7181
+ attempt: z3.number().int().positive(),
7182
+ bound: z3.number().int().positive()
7183
+ }).strict(),
7184
+ z3.object({
7185
+ ...loopShared,
7186
+ event: z3.literal("storage_push"),
7187
+ round: z3.number().int(),
7188
+ branch: z3.string(),
7189
+ head: z3.string()
7190
+ }).strict(),
7191
+ z3.object({
7192
+ ...loopShared,
7193
+ event: z3.literal("local_checks_run"),
7194
+ round: z3.number().int(),
7195
+ head: z3.string().nullable(),
7196
+ passed: z3.boolean(),
7197
+ wall_ms: z3.number().nonnegative()
7198
+ }).strict(),
7199
+ z3.object({
7200
+ ...loopShared,
7201
+ event: z3.literal("ready_push"),
7202
+ round: z3.number().int(),
7203
+ head: z3.string(),
7204
+ outcome: z3.enum(["passed", "refused"]),
7205
+ selected: z3.number().int().nonnegative(),
7206
+ failed: z3.number().int().nonnegative(),
7207
+ rerun: z3.boolean(),
7208
+ wall_ms: z3.number().nonnegative()
7209
+ }).strict(),
7210
+ z3.object({
7211
+ ...loopShared,
7212
+ event: z3.literal("failed_tests_rerun"),
7213
+ round: z3.number().int(),
7214
+ head: z3.string(),
7215
+ rerun_of: z3.string(),
7216
+ failed_files: z3.number().int().nonnegative(),
7217
+ affected_files: z3.number().int().nonnegative(),
7218
+ full_count: z3.number().int().nonnegative()
7219
+ }).strict(),
7220
+ z3.object({
7221
+ ...loopShared,
7222
+ event: z3.literal("pr_opened"),
7223
+ round: z3.number().int(),
7224
+ pr: z3.number().int().positive(),
7225
+ head: z3.string()
7226
+ }).strict(),
7227
+ z3.object({
7228
+ ...loopShared,
7229
+ event: z3.literal("ci_result_read"),
7230
+ round: z3.number().int(),
7231
+ pr: z3.number().int().positive(),
7232
+ head: z3.string(),
7233
+ conclusion: z3.enum(["green", "red", "pending", "skipped"]),
7234
+ failing_checks: z3.array(z3.string()),
7235
+ wait_ms: z3.number().nonnegative()
7236
+ }).strict(),
7237
+ z3.object({
7238
+ ...loopShared,
7239
+ event: z3.literal("phase_time"),
7240
+ round: z3.number().int(),
7241
+ phase: z3.enum(["developer", "local_checks", "review", "push", "ci", "other"]),
7242
+ step: z3.string(),
7243
+ wall_ms: z3.number().nonnegative()
7244
+ }).strict(),
6273
7245
  z3.object({
6274
7246
  ...loopShared,
6275
7247
  event: z3.literal("driver_exited"),
@@ -6457,7 +7429,7 @@ var EffectEventSchema = z3.discriminatedUnion("event", [
6457
7429
  ]);
6458
7430
  var CustomFieldValueSchema = z3.union([z3.string().max(CUSTOM_TEXT_MAX_LENGTH), z3.number().finite(), z3.boolean()]);
6459
7431
  var customShared = {
6460
- meta: HeaderMetaV3Schema,
7432
+ meta: HeaderMetaSchema,
6461
7433
  subject: SubjectSchema,
6462
7434
  kind: z3.literal("custom"),
6463
7435
  ...envelopeTail
@@ -6542,7 +7514,7 @@ function buildHeader(input) {
6542
7514
  const issue = subject.issue;
6543
7515
  return {
6544
7516
  meta: {
6545
- schema: 3,
7517
+ schema: 4,
6546
7518
  ts: input.now.toISOString(),
6547
7519
  run_id: input.runId,
6548
7520
  seq: input.seq,
@@ -6560,23 +7532,34 @@ function buildHeader(input) {
6560
7532
  parent: lineageFieldFromEnv(input.env.parent)
6561
7533
  },
6562
7534
  input_versions: {
7535
+ manifest_version: input.inputVersions?.manifestVersion ?? null,
6563
7536
  objectives_version: input.inputVersions?.objectivesVersion ?? null,
6564
7537
  brief_hash: input.inputVersions?.briefHash ?? null,
6565
7538
  ruling_ordinal: input.inputVersions?.rulingOrdinal ?? null,
7539
+ pause_bound_ruling: input.inputVersions?.pauseBoundRuling ?? null,
6566
7540
  policy_digest: input.inputVersions?.policyDigest ?? null
6567
7541
  },
6568
7542
  provenance: provenanceFor(input),
6569
7543
  work: {
6570
7544
  ref: lineageFieldFromEnv(input.env.workRef) ?? (issue === null ? null : String(issue)),
6571
7545
  repo: input.repo,
6572
- change: null,
6573
- revision: null
7546
+ change: pr === undefined ? null : String(pr),
7547
+ revision: input.revision ?? null
6574
7548
  },
6575
7549
  flow: {
6576
7550
  id: lineageFieldFromEnv(input.env.flow) ?? "vinaya",
6577
7551
  version: lineageFieldFromEnv(input.env.flowVersion)
6578
7552
  },
6579
7553
  runtime: lineageFieldFromEnv(input.env.runtime),
7554
+ process: {
7555
+ id: lineageFieldFromEnv(input.env.processId) ?? "vinaya",
7556
+ version: lineageFieldFromEnv(input.env.processVersion),
7557
+ digest: lineageFieldFromEnv(input.env.processDigest)
7558
+ },
7559
+ runner: {
7560
+ id: lineageFieldFromEnv(input.env.runnerId) ?? "standalone",
7561
+ version: lineageFieldFromEnv(input.env.runnerVersion)
7562
+ },
6580
7563
  source: lineageFieldFromEnv(input.env.source)
6581
7564
  },
6582
7565
  subject
@@ -6620,7 +7603,7 @@ function redact(value, home) {
6620
7603
  return value;
6621
7604
  }
6622
7605
  // ../../packages/aeg-core/src/log/store.ts
6623
- var KNOWN_SCHEMA_VERSIONS = [1, 2, 3];
7606
+ var KNOWN_SCHEMA_VERSIONS = [1, 2, 3, 4];
6624
7607
  function metaOf(obj) {
6625
7608
  if (obj === null || typeof obj !== "object")
6626
7609
  return null;
@@ -6758,6 +7741,12 @@ var ManifestRecordSchema = z4.object({
6758
7741
  briefHash: z4.string().min(1).nullable(),
6759
7742
  objectivesVersion: z4.string().min(1).nullable(),
6760
7743
  rulingOrdinal: epochNumber,
7744
+ manifestVersion: z4.literal(2).optional(),
7745
+ pauseBoundRuling: z4.object({
7746
+ rulingId: z4.string().min(1),
7747
+ pauseId: z4.string().min(1),
7748
+ contentDigest: z4.string().min(1)
7749
+ }).strict().nullable().optional(),
6761
7750
  policyDigest: z4.string().min(1),
6762
7751
  recordedAt: isoTimestamp
6763
7752
  }).strict();
@@ -6779,7 +7768,11 @@ var LoopStateRecordSchema = z4.object({
6779
7768
  deliveredFindings: roundHeadIdentity.nullable(),
6780
7769
  repeatMemory: z4.object({
6781
7770
  blockingFindings: z4.array(z4.string()),
6782
- lastFailure: z4.object({ signature: z4.string(), message: z4.string() }).nullable()
7771
+ lastFailure: z4.object({ signature: z4.string(), message: z4.string(), developerAttemptedSince: z4.boolean().optional() }).nullable()
7772
+ }).strict().optional(),
7773
+ developerHandoff: z4.object({
7774
+ findings: z4.array(z4.object({ id: z4.string().min(1), description: z4.string().min(1) }).strict()),
7775
+ failingChecks: z4.array(z4.string().min(1))
6783
7776
  }).strict().optional(),
6784
7777
  publicationExpectedBase: z4.string().regex(/^[0-9a-f]{40}$/).nullable().optional(),
6785
7778
  taskStartedAt: isoTimestamp.optional(),
@@ -6834,37 +7827,338 @@ var ResolutionRecordSchema = z4.object({
6834
7827
  authenticatedFrom: z4.string().min(1),
6835
7828
  consumedAt: isoTimestamp
6836
7829
  }).strict();
7830
+ var ExecutionRoundMirrorRecordSchema = z4.object({
7831
+ version: z4.literal(1),
7832
+ kind: z4.literal("execution_round"),
7833
+ task: taskId,
7834
+ repository: z4.string().min(1),
7835
+ threadId: z4.string().min(1),
7836
+ checkpointId: z4.string().min(1),
7837
+ round: z4.number().int().positive(),
7838
+ recordedAt: isoTimestamp
7839
+ }).strict();
6837
7840
  // ../../packages/aeg-core/src/control-store/local.ts
6838
7841
  var CONTROL_AREA_DIRNAME = "control";
6839
7842
  // src/lib/config.ts
6840
7843
  import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
6841
7844
  import { promisify as promisify4 } from "node:util";
6842
- import { existsSync, mkdirSync, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync } from "node:fs";
7845
+ import { existsSync, lstatSync, mkdirSync, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync } from "node:fs";
6843
7846
  import { homedir } from "node:os";
6844
- import { dirname, isAbsolute, join, resolve } from "node:path";
6845
- import { z as z5 } from "zod";
7847
+ import { basename as basename3, dirname, isAbsolute, join, resolve } from "node:path";
7848
+ import { z as z6 } from "zod";
7849
+
7850
+ // src/checks/contract.ts
7851
+ var CHECK_SCHEMA_VERSION = 1;
7852
+ function emitCheckError(error) {
7853
+ process.stderr.write(`${JSON.stringify(error)}
7854
+ `);
7855
+ }
6846
7856
 
6847
7857
  // src/lib/agent-vendors.ts
6848
7858
  var AGENT_VENDORS = ["skills", "claude", "gemini"];
6849
7859
 
7860
+ // src/lib/prose-rules-config.ts
7861
+ import safeRegex from "safe-regex2";
7862
+ import { z as z5 } from "zod";
7863
+ var SEVERITIES = ["error", "warning"];
7864
+ var OVERRIDE_KEYS = ["scopes", "severity", "exempt"];
7865
+ var FIXED_DEFAULT_KEYS = ["pattern", "patterns", "flags", "means", "message", "id"];
7866
+ var CUSTOM_KEYS = ["id", "pattern", "patterns", "flags", "means", "scopes", "severity", "exempt"];
7867
+ var DEFAULT_IDS = new Set([...DEFAULT_PROSE_RULES.map((rule) => rule.id), DECISION_RECORD_CITATION_ID]);
7868
+ function isPlainObject3(value) {
7869
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7870
+ }
7871
+ function outsideRepositoryReason(entry) {
7872
+ if (entry.startsWith("/") || /^[A-Za-z]:/.test(entry))
7873
+ return "must be a repository-relative path, not an absolute one";
7874
+ if (entry.split(/[\\/]/).includes(".."))
7875
+ return "must stay inside the repository — no `..` segment";
7876
+ return null;
7877
+ }
7878
+ var RepoRelativePathSchema = z5.string().min(1).superRefine((entry, ctx) => {
7879
+ const reason = outsideRepositoryReason(entry);
7880
+ if (reason)
7881
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, message: reason });
7882
+ });
7883
+ function pathListIssues(value, path, issues) {
7884
+ if (!Array.isArray(value)) {
7885
+ issues.push({ path, message: "must be a list of repository-relative paths" });
7886
+ return;
7887
+ }
7888
+ value.forEach((entry, index) => {
7889
+ if (typeof entry !== "string" || entry.length === 0) {
7890
+ issues.push({ path: [...path, index], message: "must be a non-empty repository-relative path" });
7891
+ return;
7892
+ }
7893
+ const reason = outsideRepositoryReason(entry);
7894
+ if (reason)
7895
+ issues.push({ path: [...path, index], message: reason });
7896
+ });
7897
+ }
7898
+ function scopeListIssues(value, path, allowed, issues) {
7899
+ if (!Array.isArray(value) || value.length === 0) {
7900
+ issues.push({ path, message: "must name at least one scope" });
7901
+ return null;
7902
+ }
7903
+ const scopes = [];
7904
+ value.forEach((scope, index) => {
7905
+ if (typeof scope !== "string" || !CONFIGURABLE_PROSE_SCOPES.includes(scope)) {
7906
+ issues.push({
7907
+ path: [...path, index],
7908
+ 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(", ")}`
7909
+ });
7910
+ return;
7911
+ }
7912
+ if (!allowed.includes(scope)) {
7913
+ issues.push({
7914
+ path: [...path, index],
7915
+ message: `scope "${scope}" is not one this rule can run in — it can run in: ${allowed.join(", ")}`
7916
+ });
7917
+ return;
7918
+ }
7919
+ scopes.push(scope);
7920
+ });
7921
+ return scopes;
7922
+ }
7923
+ function severityIssues(value, path, scopes, issues) {
7924
+ if (typeof value === "string") {
7925
+ if (!SEVERITIES.includes(value)) {
7926
+ issues.push({ path, message: `unknown severity ${JSON.stringify(value)} — use "error" or "warning"` });
7927
+ }
7928
+ return;
7929
+ }
7930
+ if (!isPlainObject3(value)) {
7931
+ issues.push({ path, message: 'must be "error", "warning", or a map from scope to one of them' });
7932
+ return;
7933
+ }
7934
+ for (const [scope, severity] of Object.entries(value)) {
7935
+ if (!scopes.includes(scope)) {
7936
+ issues.push({ path: [...path, scope], message: `names scope "${scope}", which this rule's scopes do not cover` });
7937
+ }
7938
+ if (typeof severity !== "string" || !SEVERITIES.includes(severity)) {
7939
+ issues.push({
7940
+ path: [...path, scope],
7941
+ message: `unknown severity ${JSON.stringify(severity)} — use "error" or "warning"`
7942
+ });
7943
+ }
7944
+ }
7945
+ }
7946
+ function patternIssues(source, flags, path, issues) {
7947
+ if (typeof source !== "string" || source.length === 0) {
7948
+ issues.push({ path, message: "must be a non-empty regular expression" });
7949
+ return;
7950
+ }
7951
+ if (source.length > CONFIGURED_PATTERN_MAX_LENGTH) {
7952
+ issues.push({
7953
+ path,
7954
+ message: `is ${source.length} characters, over the ${CONFIGURED_PATTERN_MAX_LENGTH}-character limit for a configured pattern`
7955
+ });
7956
+ return;
7957
+ }
7958
+ try {
7959
+ new RegExp(source, flags);
7960
+ } catch (err) {
7961
+ issues.push({ path, message: `does not compile: ${err.message}` });
7962
+ return;
7963
+ }
7964
+ if (!safeRegex(source, { limit: Number.MAX_SAFE_INTEGER })) {
7965
+ issues.push({
7966
+ path,
7967
+ 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."
7968
+ });
7969
+ }
7970
+ }
7971
+ function flagIssues(value, path, issues) {
7972
+ if (value === undefined)
7973
+ return "";
7974
+ if (typeof value !== "string") {
7975
+ issues.push({ path, message: 'must be a string of flags, e.g. "i"' });
7976
+ return "";
7977
+ }
7978
+ const seen = new Set;
7979
+ for (const flag of value) {
7980
+ if (!CONFIGURED_PROSE_FLAGS.includes(flag)) {
7981
+ issues.push({
7982
+ path,
7983
+ message: `unknown flag ${JSON.stringify(flag)} — only ${CONFIGURED_PROSE_FLAGS.map((f) => `"${f}"`).join(" and ")} are allowed`
7984
+ });
7985
+ return "";
7986
+ }
7987
+ if (seen.has(flag)) {
7988
+ issues.push({ path, message: `repeats the flag "${flag}"` });
7989
+ return "";
7990
+ }
7991
+ seen.add(flag);
7992
+ }
7993
+ return value;
7994
+ }
7995
+ function defaultsIssues(value, issues) {
7996
+ const base = ["defaults"];
7997
+ if (!isPlainObject3(value)) {
7998
+ issues.push({ path: base, message: 'must map a default rule id to "off" or an override' });
7999
+ return;
8000
+ }
8001
+ for (const [id, override] of Object.entries(value)) {
8002
+ const path = [...base, id];
8003
+ const rule = CONFIGURABLE_DEFAULT_RULES.find((candidate) => candidate.id === id);
8004
+ if (!rule) {
8005
+ issues.push({
8006
+ path,
8007
+ message: `unknown default rule id "${id}" — \`vinaya check --plan\` lists the rules each prose check runs`
8008
+ });
8009
+ continue;
8010
+ }
8011
+ if (override === "off")
8012
+ continue;
8013
+ if (!isPlainObject3(override)) {
8014
+ issues.push({ path, message: 'must be "off" or an object with any of scopes, severity, exempt' });
8015
+ continue;
8016
+ }
8017
+ for (const key of Object.keys(override)) {
8018
+ if (OVERRIDE_KEYS.includes(key))
8019
+ continue;
8020
+ issues.push({
8021
+ path: [...path, key],
8022
+ 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`
8023
+ });
8024
+ }
8025
+ const scopes = override.scopes === undefined ? [...rule.scopes] : scopeListIssues(override.scopes, [...path, "scopes"], allowedScopesFor(rule), issues);
8026
+ if (override.severity !== undefined && scopes)
8027
+ severityIssues(override.severity, [...path, "severity"], scopes, issues);
8028
+ if (override.exempt !== undefined)
8029
+ pathListIssues(override.exempt, [...path, "exempt"], issues);
8030
+ }
8031
+ }
8032
+ function customIssues(value, issues) {
8033
+ if (!Array.isArray(value)) {
8034
+ issues.push({ path: ["custom"], message: "must be a list of rules" });
8035
+ return;
8036
+ }
8037
+ const ids = new Set;
8038
+ value.forEach((rule, index) => {
8039
+ const path = ["custom", index];
8040
+ if (!isPlainObject3(rule)) {
8041
+ issues.push({ path, message: "must be a rule object" });
8042
+ return;
8043
+ }
8044
+ for (const key of Object.keys(rule)) {
8045
+ if (!CUSTOM_KEYS.includes(key)) {
8046
+ issues.push({ path: [...path, key], message: `unknown key "${key}" — a rule takes ${CUSTOM_KEYS.join(", ")}` });
8047
+ }
8048
+ }
8049
+ if (typeof rule.id !== "string" || rule.id.length === 0) {
8050
+ issues.push({ path: [...path, "id"], message: "a custom rule needs an id" });
8051
+ } else if (DEFAULT_IDS.has(rule.id)) {
8052
+ issues.push({
8053
+ path: [...path, "id"],
8054
+ message: `"${rule.id}" is a default rule id — a custom rule needs its own id; retune the default under proseGates.rules.defaults instead`
8055
+ });
8056
+ } else if (ids.has(rule.id)) {
8057
+ issues.push({ path: [...path, "id"], message: `"${rule.id}" is used by an earlier custom rule` });
8058
+ } else {
8059
+ ids.add(rule.id);
8060
+ }
8061
+ if (typeof rule.means !== "string" || rule.means.trim().length === 0) {
8062
+ issues.push({ path: [...path, "means"], message: "a custom rule needs a message (`means`)" });
8063
+ }
8064
+ let scopes = null;
8065
+ if (rule.scopes === undefined) {
8066
+ issues.push({ path: [...path, "scopes"], message: "a custom rule needs at least one scope (`scopes`)" });
8067
+ } else {
8068
+ scopes = scopeListIssues(rule.scopes, [...path, "scopes"], CONFIGURABLE_PROSE_SCOPES, issues);
8069
+ }
8070
+ if (scopes && new Set(scopes.map(groupOfScope)).size > 1) {
8071
+ issues.push({
8072
+ path: [...path, "scopes"],
8073
+ 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'
8074
+ });
8075
+ }
8076
+ const flags = flagIssues(rule.flags, [...path, "flags"], issues);
8077
+ if (rule.pattern === undefined && rule.patterns === undefined) {
8078
+ issues.push({
8079
+ path: [...path, "pattern"],
8080
+ message: "a custom rule needs a `pattern` or a per-scope `patterns` map"
8081
+ });
8082
+ }
8083
+ if (rule.pattern !== undefined)
8084
+ patternIssues(rule.pattern, flags, [...path, "pattern"], issues);
8085
+ if (rule.patterns !== undefined) {
8086
+ if (!isPlainObject3(rule.patterns)) {
8087
+ issues.push({ path: [...path, "patterns"], message: "must map a scope to a regular expression" });
8088
+ } else {
8089
+ for (const [scope, source] of Object.entries(rule.patterns)) {
8090
+ if (scopes && !scopes.includes(scope)) {
8091
+ issues.push({
8092
+ path: [...path, "patterns", scope],
8093
+ message: `names scope "${scope}", which this rule's scopes do not cover`
8094
+ });
8095
+ continue;
8096
+ }
8097
+ patternIssues(source, flags, [...path, "patterns", scope], issues);
8098
+ }
8099
+ if (rule.pattern === undefined && scopes) {
8100
+ for (const scope of scopes) {
8101
+ if (!(scope in rule.patterns)) {
8102
+ issues.push({
8103
+ path: [...path, "patterns"],
8104
+ message: `has no pattern for scope "${scope}" — add one, or a \`pattern\` every other scope uses`
8105
+ });
8106
+ }
8107
+ }
8108
+ }
8109
+ }
8110
+ }
8111
+ if (rule.severity !== undefined && scopes)
8112
+ severityIssues(rule.severity, [...path, "severity"], scopes, issues);
8113
+ if (rule.exempt !== undefined)
8114
+ pathListIssues(rule.exempt, [...path, "exempt"], issues);
8115
+ });
8116
+ }
8117
+ function proseRulesIssues(value) {
8118
+ const issues = [];
8119
+ if (!isPlainObject3(value))
8120
+ return [{ path: [], message: "must be an object with any of exempt, defaults, custom" }];
8121
+ for (const key of Object.keys(value)) {
8122
+ if (!["exempt", "defaults", "custom"].includes(key)) {
8123
+ issues.push({ path: [key], message: `unknown key "${key}" — proseGates.rules takes exempt, defaults and custom` });
8124
+ }
8125
+ }
8126
+ if (value.exempt !== undefined)
8127
+ pathListIssues(value.exempt, ["exempt"], issues);
8128
+ if (value.defaults !== undefined)
8129
+ defaultsIssues(value.defaults, issues);
8130
+ if (value.custom !== undefined)
8131
+ customIssues(value.custom, issues);
8132
+ return issues;
8133
+ }
8134
+ var ProseRulesSchema = z5.unknown().superRefine((value, ctx) => {
8135
+ for (const issue of proseRulesIssues(value)) {
8136
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, path: issue.path, message: issue.message });
8137
+ }
8138
+ }).transform((value) => value);
8139
+ var PublishedProseSchema = z5.object({
8140
+ allow: z5.array(z5.string().min(1)).optional()
8141
+ }).strict();
8142
+
6850
8143
  // src/lib/config.ts
6851
- var EnvEntrySchema = z5.union([
6852
- z5.literal(true),
6853
- z5.object({ optional: z5.literal(true) }),
6854
- z5.object({ anyOf: z5.array(z5.string()).min(2) }),
6855
- z5.string()
8144
+ var EnvEntrySchema = z6.union([
8145
+ z6.literal(true),
8146
+ z6.object({ optional: z6.literal(true) }),
8147
+ z6.object({ anyOf: z6.array(z6.string()).min(2) }),
8148
+ z6.string()
6856
8149
  ]);
6857
- var CheckEntrySchema = z5.object({
6858
- run: z5.string(),
6859
- scope: z5.enum(["diff", "full"]),
6860
- include: z5.array(z5.string()).optional(),
6861
- args: z5.array(z5.string()).optional(),
6862
- timeoutMs: z5.number().optional(),
6863
- env: z5.record(z5.string(), EnvEntrySchema).optional(),
6864
- requiresOpenPr: z5.boolean().optional(),
6865
- ownWorkflow: z5.boolean().optional(),
6866
- principalOwed: z5.literal(true).optional(),
6867
- validates: z5.enum(["body", "issue"]).optional()
8150
+ var CheckEntrySchema = z6.object({
8151
+ run: z6.string(),
8152
+ scope: z6.enum(["diff", "full"]),
8153
+ include: z6.array(z6.string()).optional(),
8154
+ args: z6.array(z6.string()).optional(),
8155
+ timeoutMs: z6.number().optional(),
8156
+ env: z6.record(z6.string(), EnvEntrySchema).optional(),
8157
+ requiresOpenPr: z6.boolean().optional(),
8158
+ ownWorkflow: z6.boolean().optional(),
8159
+ principalOwed: z6.literal(true).optional(),
8160
+ validates: z6.enum(["body", "issue"]).optional(),
8161
+ advisory: z6.literal(true).optional()
6868
8162
  }).superRefine((entry, ctx) => {
6869
8163
  if (!entry.env)
6870
8164
  return;
@@ -6874,22 +8168,22 @@ var CheckEntrySchema = z5.object({
6874
8168
  const members = value.anyOf;
6875
8169
  if (new Set(members).size !== members.length) {
6876
8170
  ctx.addIssue({
6877
- code: z5.ZodIssueCode.custom,
8171
+ code: z6.ZodIssueCode.custom,
6878
8172
  message: `env.${key}.anyOf has duplicate members`,
6879
8173
  path: ["env", key, "anyOf"]
6880
8174
  });
6881
8175
  }
6882
8176
  if (!members.includes(key)) {
6883
8177
  ctx.addIssue({
6884
- code: z5.ZodIssueCode.custom,
8178
+ code: z6.ZodIssueCode.custom,
6885
8179
  message: `env.${key}.anyOf must include "${key}" itself as a member`,
6886
8180
  path: ["env", key, "anyOf"]
6887
8181
  });
6888
8182
  }
6889
8183
  }
6890
8184
  });
6891
- var RoleEntrySchema = z5.object({
6892
- contract: z5.string().refine((p) => p.includes("/"), {
8185
+ var RoleEntrySchema = z6.object({
8186
+ contract: z6.string().refine((p) => p.includes("/"), {
6893
8187
  message: 'must be a path (contain at least one "/"), not a bare filename'
6894
8188
  })
6895
8189
  });
@@ -6913,17 +8207,17 @@ var BRIEF_BUILTINS = [
6913
8207
  "briefSections",
6914
8208
  "milestoneShape"
6915
8209
  ];
6916
- var BriefSectionSchema = z5.union([
6917
- z5.object({ builtin: z5.enum(BRIEF_BUILTINS) }),
6918
- z5.object({ heading: z5.string().min(1), name: z5.string().optional() }),
6919
- z5.object({ field: z5.string().min(1), name: z5.string().optional() }),
6920
- z5.object({ phrase: z5.string().min(1), name: z5.string().optional() })
8210
+ var BriefSectionSchema = z6.union([
8211
+ z6.object({ builtin: z6.enum(BRIEF_BUILTINS) }),
8212
+ z6.object({ heading: z6.string().min(1), name: z6.string().optional() }),
8213
+ z6.object({ field: z6.string().min(1), name: z6.string().optional() }),
8214
+ z6.object({ phrase: z6.string().min(1), name: z6.string().optional() })
6921
8215
  ]);
6922
- var BriefSchemaSchema = z5.object({
6923
- pr: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6924
- issue: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6925
- milestone: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6926
- ack: z5.array(z5.enum(BRIEF_BUILTINS)).optional()
8216
+ var BriefSchemaSchema = z6.object({
8217
+ pr: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8218
+ issue: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8219
+ milestone: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8220
+ ack: z6.array(z6.enum(BRIEF_BUILTINS)).optional()
6927
8221
  });
6928
8222
  function isSafeRepoRelPath(p) {
6929
8223
  if (p.length === 0)
@@ -6932,7 +8226,7 @@ function isSafeRepoRelPath(p) {
6932
8226
  return false;
6933
8227
  return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
6934
8228
  }
6935
- var SafeRepoRelPath = z5.string().refine(isSafeRepoRelPath, {
8229
+ var SafeRepoRelPath = z6.string().refine(isSafeRepoRelPath, {
6936
8230
  message: "must be a repo-root-relative path with no `..` segment or absolute root"
6937
8231
  });
6938
8232
  var CANONICAL_HOOK_BLOCK_PREFIXES = [".git/", ".husky/", ".vinaya/hooks/", ".claude/hooks/"];
@@ -6942,22 +8236,22 @@ function isCanonicalHookBlockPath(p) {
6942
8236
  var ManagedHookBlockPath = SafeRepoRelPath.refine(isCanonicalHookBlockPath, {
6943
8237
  message: `must start with one of ${CANONICAL_HOOK_BLOCK_PREFIXES.join(", ")} (byte-exact, case-sensitive)`
6944
8238
  });
6945
- var ManagedBlockRecordSchema = z5.object({
8239
+ var ManagedBlockRecordSchema = z6.object({
6946
8240
  path: ManagedHookBlockPath,
6947
- marker: z5.string(),
6948
- comment: z5.enum(["hash", "html"])
8241
+ marker: z6.string(),
8242
+ comment: z6.enum(["hash", "html"])
6949
8243
  });
6950
- var ManagedManifestSchema = z5.object({
6951
- version: z5.number().int().positive(),
6952
- files: z5.array(SafeRepoRelPath),
6953
- blocks: z5.array(ManagedBlockRecordSchema),
6954
- labels: z5.array(z5.string()),
6955
- agents: z5.array(z5.enum(AGENT_VENDORS)).optional()
8244
+ var ManagedManifestSchema = z6.object({
8245
+ version: z6.number().int().positive(),
8246
+ files: z6.array(SafeRepoRelPath),
8247
+ blocks: z6.array(ManagedBlockRecordSchema),
8248
+ labels: z6.array(z6.string()),
8249
+ agents: z6.array(z6.enum(AGENT_VENDORS)).optional()
6956
8250
  });
6957
- var ProjectEntrySchema = z5.object({
6958
- name: z5.string().min(1),
6959
- description: z5.string().min(1).optional(),
6960
- path: z5.string().min(1).optional()
8251
+ var ProjectEntrySchema = z6.object({
8252
+ name: z6.string().min(1),
8253
+ description: z6.string().min(1).optional(),
8254
+ path: z6.string().min(1).optional()
6961
8255
  });
6962
8256
  function parseTokensCollectDeclaration(value) {
6963
8257
  const m = value.trim().match(/^(\S+)\s+(\S+)$/);
@@ -6968,90 +8262,101 @@ function parseTokensCollectDeclaration(value) {
6968
8262
  return null;
6969
8263
  return { interpreter, script };
6970
8264
  }
6971
- var VinayaConfigSchema = z5.object({
6972
- rings: z5.object({
6973
- ring1_forgeWriteInterception: z5.boolean(),
6974
- ring2_asyncAudits: z5.boolean()
8265
+ var VinayaConfigObjectSchema = z6.object({
8266
+ rings: z6.object({
8267
+ ring1_forgeWriteInterception: z6.boolean(),
8268
+ ring2_asyncAudits: z6.boolean()
6975
8269
  }).optional(),
6976
- checks: z5.record(z5.string(), CheckEntrySchema).optional(),
6977
- roles: z5.record(z5.string(), RoleEntrySchema).optional(),
8270
+ checks: z6.record(z6.string(), CheckEntrySchema).optional(),
8271
+ roles: z6.record(z6.string(), RoleEntrySchema).optional(),
6978
8272
  briefSchema: BriefSchemaSchema.optional(),
6979
8273
  managed: ManagedManifestSchema.optional(),
6980
- principals: z5.array(z5.string()).min(1).optional(),
6981
- releaseActor: z5.string().min(1).optional(),
6982
- ci: z5.object({ setup: z5.string().min(1) }).optional(),
6983
- tokens: z5.object({
6984
- collect: z5.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
8274
+ principals: z6.array(z6.string()).min(1).optional(),
8275
+ releaseActor: z6.string().min(1).optional(),
8276
+ ci: z6.object({ setup: z6.string().min(1) }).optional(),
8277
+ tokens: z6.object({
8278
+ collect: z6.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
6985
8279
  message: 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
6986
8280
  })
6987
8281
  }).optional(),
6988
- blastRadius: z5.object({ extraDomains: z5.array(z5.string()).optional() }).optional(),
6989
- proseGates: z5.object({
6990
- doctrineRoot: z5.string().min(1).optional(),
6991
- readerFacingPrefix: z5.string().min(1).optional(),
6992
- readerFacingSuffix: z5.string().min(1).optional(),
6993
- legacySlugDir: z5.string().min(1).optional(),
6994
- sourceComments: z5.object({
6995
- globs: z5.array(z5.string().min(1)).optional(),
6996
- allowlist: z5.array(z5.string().min(1)).optional(),
6997
- severity: z5.enum(["warning", "error"]).optional()
8282
+ blastRadius: z6.object({ extraDomains: z6.array(z6.string()).optional() }).optional(),
8283
+ proseGates: z6.object({
8284
+ doctrineRoot: z6.string().min(1).optional(),
8285
+ readerFacingPrefix: z6.string().min(1).optional(),
8286
+ readerFacingSuffix: z6.string().min(1).optional(),
8287
+ legacySlugDir: z6.string().min(1).optional(),
8288
+ sourceComments: z6.object({
8289
+ globs: z6.array(z6.string().min(1)).optional(),
8290
+ allowlist: z6.array(z6.string().min(1)).optional(),
8291
+ severity: z6.enum(["warning", "error"]).optional()
6998
8292
  }).optional(),
6999
- specGrandfather: z5.union([z5.array(z5.string().min(1)), z5.record(z5.string().min(1), z5.number().int().min(0))]).optional(),
7000
- specPaths: z5.array(z5.string().min(1).refine((entry) => !entry.startsWith("/") && !/^[A-Za-z]:/.test(entry), {
7001
- message: "must be a repository-relative path, not an absolute one"
7002
- }).refine((entry) => !entry.split(/[\\/]/).includes(".."), {
7003
- message: "must stay inside the repository — no `..` segment"
7004
- })).optional()
8293
+ specGrandfather: z6.union([z6.array(z6.string().min(1)), z6.record(z6.string().min(1), z6.number().int().min(0))]).optional(),
8294
+ specPaths: z6.array(RepoRelativePathSchema).optional(),
8295
+ productPaths: z6.array(RepoRelativePathSchema).optional(),
8296
+ published: PublishedProseSchema.optional(),
8297
+ rules: ProseRulesSchema.optional()
7005
8298
  }).optional(),
7006
- projects: z5.array(ProjectEntrySchema).optional(),
7007
- dispatch: z5.object({
7008
- timeoutMs: z5.number().int().positive().optional(),
7009
- killGraceMs: z5.number().int().positive().optional(),
7010
- agent: z5.enum(["claude", "codex", "gemini"]).optional()
8299
+ projects: z6.array(ProjectEntrySchema).optional(),
8300
+ dispatch: z6.object({
8301
+ timeoutMs: z6.number().int().positive().optional(),
8302
+ reviewerTimeoutMs: z6.number().int().positive().optional(),
8303
+ killGraceMs: z6.number().int().positive().optional(),
8304
+ agent: z6.enum(["claude", "codex"]).optional()
7011
8305
  }).optional(),
7012
- reviewPolicy: z5.object({
7013
- codeReviewThreshold: z5.string().min(1).optional(),
7014
- securityThreshold: z5.string().min(1).optional(),
7015
- maxRounds: z5.number().optional(),
7016
- maxTaskMinutes: z5.number().optional()
8306
+ reviewPolicy: z6.object({
8307
+ codeReviewThreshold: z6.string().min(1).optional(),
8308
+ securityThreshold: z6.string().min(1).optional(),
8309
+ maxRounds: z6.number().optional(),
8310
+ maxTaskMinutes: z6.number().optional(),
8311
+ readyPushTimeoutMinutes: z6.number().optional()
7017
8312
  }).optional(),
7018
- securityScan: z5.object({
7019
- command: z5.array(z5.string().min(1)).min(1)
8313
+ securityScan: z6.object({
8314
+ command: z6.array(z6.string().min(1)).min(1)
7020
8315
  }).optional(),
7021
- gateCutovers: z5.object({
7022
- objectivesSinceIssue: z5.number().int().nonnegative().optional(),
7023
- briefSectionsSinceIssue: z5.number().int().nonnegative().optional(),
7024
- documentationSinceIssue: z5.number().int().nonnegative().optional(),
7025
- briefRulesSincePr: z5.number().int().nonnegative().optional(),
7026
- agentBoxesRefusedSincePr: z5.number().int().nonnegative().optional()
8316
+ gateCutovers: z6.object({
8317
+ objectivesSinceIssue: z6.number().int().nonnegative().optional(),
8318
+ briefSectionsSinceIssue: z6.number().int().nonnegative().optional(),
8319
+ documentationSinceIssue: z6.number().int().nonnegative().optional(),
8320
+ briefRulesSincePr: z6.number().int().nonnegative().optional(),
8321
+ agentBoxesRefusedSincePr: z6.number().int().nonnegative().optional()
7027
8322
  }).optional(),
7028
- planning: z5.object({
7029
- collisionThreshold: z5.number().int().nonnegative().optional()
8323
+ planning: z6.object({
8324
+ collisionThreshold: z6.number().int().nonnegative().optional()
7030
8325
  }).optional(),
7031
- prePush: z5.object({
7032
- alwaysRun: z5.array(z5.string()).optional()
8326
+ prePush: z6.object({
8327
+ alwaysRun: z6.array(z6.string()).optional(),
8328
+ readyTests: z6.object({
8329
+ mode: z6.literal("ci"),
8330
+ workflow: z6.literal(".github/workflows/ci.yml"),
8331
+ check: z6.literal("Vinaya CI")
8332
+ }).strict().optional(),
8333
+ requiredCi: z6.object({
8334
+ workflow: z6.literal(".github/workflows/ci.yml"),
8335
+ check: z6.literal("Vinaya CI")
8336
+ }).strict().optional()
7033
8337
  }).optional(),
7034
- report: z5.object({
7035
- commandTimeoutMs: z5.number().int().positive().optional()
8338
+ report: z6.object({
8339
+ commandTimeoutMs: z6.number().int().positive().optional()
7036
8340
  }).superRefine((report, ctx) => {
7037
8341
  const commandTimeoutMs = report.commandTimeoutMs;
7038
8342
  if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
7039
8343
  ctx.addIssue({
7040
- code: z5.ZodIssueCode.custom,
8344
+ code: z6.ZodIssueCode.custom,
7041
8345
  path: ["commandTimeoutMs"],
7042
8346
  message: "must be at most 3600000 (1 hour)"
7043
8347
  });
7044
8348
  }
7045
8349
  }).optional(),
7046
- logPublish: z5.unknown().refine((v) => v === undefined, {
8350
+ logPublish: z6.unknown().refine((v) => v === undefined, {
7047
8351
  message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
7048
8352
  }),
7049
- runtimeDir: z5.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
7050
- logs: z5.object({
7051
- folder: z5.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
7052
- url: z5.string().url().optional(),
7053
- headers: z5.record(z5.string()).optional(),
7054
- readHeaders: z5.record(z5.string()).optional(),
8353
+ runtimeDir: z6.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
8354
+ runner: z6.enum(["standalone", "atta-engine"]).optional(),
8355
+ logs: z6.object({
8356
+ folder: z6.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
8357
+ url: z6.string().url().optional(),
8358
+ headers: z6.record(z6.string()).optional(),
8359
+ readHeaders: z6.record(z6.string()).optional(),
7055
8360
  events: CustomEventDeclarationsSchema.optional()
7056
8361
  }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
7057
8362
  message: "logs: set at most one of folder/url"
@@ -7059,8 +8364,33 @@ var VinayaConfigSchema = z5.object({
7059
8364
  message: "logs: headers requires url"
7060
8365
  }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
7061
8366
  message: "logs: readHeaders requires url"
7062
- }).optional()
8367
+ }).or(z6.literal(false)).optional(),
8368
+ decisionRecords: z6.object({
8369
+ path: RepoRelativePathSchema
8370
+ }).strict().optional()
8371
+ });
8372
+ function decisionRecordsPathIssue(path, doctrineRoot) {
8373
+ const reason = outsideRepositoryReason(path);
8374
+ if (reason)
8375
+ return reason;
8376
+ const folder = normalizeSpecPath(path);
8377
+ if (folder === "" || folder === ".")
8378
+ return "must name a folder, not the repository root";
8379
+ const root = normalizeSpecPath(doctrineRoot ?? "aeg-root");
8380
+ if (folder === root || folder.startsWith(`${root}/`)) {
8381
+ return `must be outside the doctrine tree "${root}" — decision records belong to this repository, not to the doctrine it ships`;
8382
+ }
8383
+ return null;
8384
+ }
8385
+ var VinayaConfigSchema = VinayaConfigObjectSchema.superRefine((config, ctx) => {
8386
+ const path = config.decisionRecords?.path;
8387
+ if (path === undefined || outsideRepositoryReason(path))
8388
+ return;
8389
+ const issue = decisionRecordsPathIssue(path, config.proseGates?.doctrineRoot);
8390
+ if (issue)
8391
+ ctx.addIssue({ code: z6.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
7063
8392
  });
8393
+ var VinayaConfigShape = VinayaConfigObjectSchema.shape;
7064
8394
  var GLOBAL_VINAYA_HOME = join(homedir(), ".vinaya");
7065
8395
  var GLOBAL_CONFIG_PATH = join(GLOBAL_VINAYA_HOME, "config.json");
7066
8396
  var LOCAL_CONFIG_FILENAME = "vinaya.config.json";
@@ -7141,9 +8471,6 @@ function stripGlobalOnlyKeys(config, path) {
7141
8471
  }
7142
8472
  return result;
7143
8473
  }
7144
- function resolvePrincipalAllowlist(config) {
7145
- return config?.principals ?? PRINCIPAL_ALLOWLIST;
7146
- }
7147
8474
  function resolveReleaseActor(config) {
7148
8475
  return config?.releaseActor ?? DEFAULT_RELEASE_ACTOR;
7149
8476
  }
@@ -7167,13 +8494,19 @@ function resolveReviewPolicy(config) {
7167
8494
  if (!Number.isInteger(maxTaskMinutes) || maxTaskMinutes < 0) {
7168
8495
  throw new Error(`vinaya.config.json: reviewPolicy.maxTaskMinutes "${maxTaskMinutes}" is not a non-negative integer (0 turns the budget off) — fix the config, this never falls back to a default.`);
7169
8496
  }
8497
+ const readyPushTimeoutMinutes = raw.readyPushTimeoutMinutes ?? DEFAULT_READY_PUSH_TIMEOUT_MINUTES;
8498
+ if (!Number.isInteger(readyPushTimeoutMinutes) || readyPushTimeoutMinutes < 1) {
8499
+ throw new Error(`vinaya.config.json: reviewPolicy.readyPushTimeoutMinutes "${readyPushTimeoutMinutes}" is not a positive integer — fix the config, this never falls back to a default.`);
8500
+ }
7170
8501
  return {
7171
8502
  codeReviewThreshold,
7172
8503
  securityThreshold,
7173
8504
  maxRounds,
7174
- maxTaskMinutes
8505
+ maxTaskMinutes,
8506
+ readyPushTimeoutMinutes
7175
8507
  };
7176
8508
  }
8509
+ var emittedLocalOverrideWarnings = new Set;
7177
8510
  function resolveGateCutovers(config) {
7178
8511
  const raw = config?.gateCutovers;
7179
8512
  if (!raw)
@@ -7279,13 +8612,14 @@ function readTrustAnchorConfigAtRef(ref) {
7279
8612
  });
7280
8613
  return Buffer.from(raw, "utf-8").toString("base64");
7281
8614
  }
8615
+ var NO_TRUST_ANCHOR_REPO_MESSAGE = "could not resolve repo identity for the trust-anchor read";
7282
8616
  function ghFetchTrustAnchorConfig() {
7283
8617
  const probeRef = resolveCiTrustAnchorProbeRef();
7284
8618
  if (probeRef)
7285
8619
  return readTrustAnchorConfigAtRef(probeRef);
7286
8620
  const repo = trustAnchorRepo();
7287
8621
  if (!repo)
7288
- throw new Error("could not resolve repo identity for the trust-anchor read");
8622
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
7289
8623
  return execFileSync2("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
7290
8624
  encoding: "utf-8",
7291
8625
  stdio: ["ignore", "pipe", "pipe"]
@@ -7302,7 +8636,7 @@ async function ghFetchTrustAnchorConfigAsync() {
7302
8636
  }
7303
8637
  const repo = await trustAnchorRepoAsync();
7304
8638
  if (!repo)
7305
- throw new Error("could not resolve repo identity for the trust-anchor read");
8639
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
7306
8640
  const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4, killSignal: "SIGKILL" });
7307
8641
  return stdout;
7308
8642
  }
@@ -7328,6 +8662,47 @@ function loadTrustAnchorConfig(fetcher = ghFetchTrustAnchorConfig) {
7328
8662
  }
7329
8663
  return parseTrustAnchorContent(base64);
7330
8664
  }
8665
+ class PrincipalsUnresolvedError extends Error {
8666
+ kind;
8667
+ constructor(kind, message) {
8668
+ super(message);
8669
+ this.name = "PrincipalsUnresolvedError";
8670
+ this.kind = kind;
8671
+ }
8672
+ }
8673
+ var PRINCIPALS_FIX = 'add "principals": [...] to vinaya.config.json on the default branch';
8674
+ function fetchFailureReason(err) {
8675
+ const stderr = err?.stderr;
8676
+ const text = (typeof stderr === "string" ? stderr : stderr?.toString() ?? "").trim();
8677
+ return text.split(`
8678
+ `)[0]?.trim() || firstLine(err);
8679
+ }
8680
+ function principalsNotConfigured(why) {
8681
+ return new PrincipalsUnresolvedError("not-configured", `no Principal is configured (${why}) — ${PRINCIPALS_FIX}.`);
8682
+ }
8683
+ function resolveTrustedPrincipals(fetcher = ghFetchTrustAnchorConfig) {
8684
+ let content;
8685
+ try {
8686
+ content = fetcher();
8687
+ } catch (err) {
8688
+ if (err?.message === NO_TRUST_ANCHOR_REPO_MESSAGE) {
8689
+ throw principalsNotConfigured("no repository resolves for the read");
8690
+ }
8691
+ if (isMissingFileError(err))
8692
+ throw principalsNotConfigured("the default branch has no vinaya.config.json");
8693
+ throw new PrincipalsUnresolvedError("read-failed", `could not read "principals" from vinaya.config.json on the default branch: ${fetchFailureReason(err)}`);
8694
+ }
8695
+ const unusable = { why: "" };
8696
+ const config = parseTrustAnchorContent(content, (why) => {
8697
+ unusable.why = why;
8698
+ });
8699
+ if (config === null) {
8700
+ throw principalsNotConfigured(`vinaya.config.json on the default branch ${unusable.why ? `is unusable: ${unusable.why}` : "is empty"}`);
8701
+ }
8702
+ if (!config.principals)
8703
+ throw principalsNotConfigured('vinaya.config.json on the default branch sets no "principals"');
8704
+ return config.principals;
8705
+ }
7331
8706
  async function loadTrustAnchorConfigAsync(fetcher = ghFetchTrustAnchorConfigAsync, options = {}) {
7332
8707
  const warn = options.quiet ? () => {} : warnTrustAnchorFallback;
7333
8708
  let base64;
@@ -7367,20 +8742,261 @@ function loadConfig() {
7367
8742
  const path = configPath();
7368
8743
  if (!path)
7369
8744
  return null;
8745
+ let text;
7370
8746
  try {
7371
- const raw = JSON.parse(readFileSync2(path, "utf-8"));
7372
- return stripGlobalOnlyKeys(VinayaConfigSchema.parse(raw), path);
7373
- } catch {
8747
+ text = readFileSync2(path, "utf-8");
8748
+ } catch (err) {
8749
+ reportInvalidConfigOnce(path, `unreadable: ${err.message}`);
8750
+ return null;
8751
+ }
8752
+ let raw;
8753
+ try {
8754
+ raw = JSON.parse(text);
8755
+ } catch (err) {
8756
+ reportInvalidConfigOnce(path, `invalid JSON: ${err.message}`);
8757
+ return null;
8758
+ }
8759
+ const parsed = VinayaConfigSchema.safeParse(raw);
8760
+ if (!parsed.success) {
8761
+ reportInvalidConfigOnce(path, schemaIssueDetail(parsed.error));
7374
8762
  return null;
7375
8763
  }
8764
+ return stripGlobalOnlyKeys(parsed.data, path);
8765
+ }
8766
+ function schemaIssueDetail(error) {
8767
+ return error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
8768
+ }
8769
+ var emittedInvalidConfigReports = new Set;
8770
+ function reportInvalidConfigOnce(path, detail) {
8771
+ const key = `${path}
8772
+ ${detail}`;
8773
+ if (emittedInvalidConfigReports.has(key))
8774
+ return;
8775
+ emittedInvalidConfigReports.add(key);
8776
+ const message = `${path} is not a valid Vinaya configuration (${detail}) — falling back to built-in defaults.`;
8777
+ const checkName = process.env.VINAYA_CHECK_NAME;
8778
+ if (checkName) {
8779
+ emitCheckError({
8780
+ schema: CHECK_SCHEMA_VERSION,
8781
+ check: checkName,
8782
+ severity: "warning",
8783
+ message,
8784
+ agent_recovery_prompt: `Fix the failing keys in ${path} (${detail}) so the file parses and satisfies the configuration schema, then re-run.`,
8785
+ file: path
8786
+ });
8787
+ return;
8788
+ }
8789
+ console.error(`⚠ ${message}`);
8790
+ }
8791
+ function loadConfigChecked() {
8792
+ const path = configPath();
8793
+ if (!path)
8794
+ return { ok: true, config: null };
8795
+ let raw;
8796
+ try {
8797
+ raw = JSON.parse(readFileSync2(path, "utf-8"));
8798
+ } catch (err) {
8799
+ return { ok: false, path, error: `invalid JSON: ${err.message}` };
8800
+ }
8801
+ const parsed = VinayaConfigSchema.safeParse(raw);
8802
+ if (!parsed.success) {
8803
+ return { ok: false, path, error: schemaIssueDetail(parsed.error) };
8804
+ }
8805
+ return { ok: true, config: stripGlobalOnlyKeys(parsed.data, path) };
7376
8806
  }
7377
8807
  var TOKENS_COLLECT_TRUST_PATH = join(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
7378
8808
 
7379
- // src/checks/contract.ts
7380
- var CHECK_SCHEMA_VERSION = 1;
7381
- function emitCheckError(error) {
7382
- process.stderr.write(`${JSON.stringify(error)}
7383
- `);
8809
+ // src/lib/forge-snapshot.ts
8810
+ import { existsSync as existsSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
8811
+ import { join as join2 } from "node:path";
8812
+
8813
+ // src/lib/forge-read.ts
8814
+ import { execFileSync as execFileSync3 } from "node:child_process";
8815
+ var FORGE_READ_CEILING_BYTES = 64 * 1024 * 1024;
8816
+ var PAGE_SIZE = 100;
8817
+ var ghRunner = (args, maxBuffer) => execFileSync3("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer });
8818
+
8819
+ class ForgeReadOversizeError extends Error {
8820
+ subject;
8821
+ ceilingBytes;
8822
+ observedBytes;
8823
+ constructor(subject, observedBytes, atLeast = false, ceilingBytes = FORGE_READ_CEILING_BYTES) {
8824
+ super(`The forge response for ${subject} is ${atLeast ? "at least " : ""}${observedBytes} bytes, above the ${ceilingBytes}-byte read ceiling (FORGE_READ_CEILING_BYTES) — refusing rather than buffering it.`);
8825
+ this.name = "ForgeReadOversizeError";
8826
+ this.subject = subject;
8827
+ this.ceilingBytes = ceilingBytes;
8828
+ this.observedBytes = observedBytes;
8829
+ }
8830
+ }
8831
+ function isForgeReadOversize(err) {
8832
+ return err instanceof ForgeReadOversizeError;
8833
+ }
8834
+ function isBufferOverflow(err) {
8835
+ return err?.code === "ENOBUFS";
8836
+ }
8837
+ function runBounded(runner, args, subject, usedBytes) {
8838
+ const remaining = FORGE_READ_CEILING_BYTES - usedBytes;
8839
+ let out;
8840
+ try {
8841
+ out = runner(args, remaining);
8842
+ } catch (err) {
8843
+ if (isBufferOverflow(err))
8844
+ throw new ForgeReadOversizeError(subject, FORGE_READ_CEILING_BYTES + 1, true);
8845
+ throw err;
8846
+ }
8847
+ const size = Buffer.byteLength(out, "utf8");
8848
+ if (usedBytes + size > FORGE_READ_CEILING_BYTES)
8849
+ throw new ForgeReadOversizeError(subject, usedBytes + size);
8850
+ return out;
8851
+ }
8852
+ function readRestCommentRows(number, subjectLabel = `Issue ${number}`, runner = ghRunner) {
8853
+ const rows = [];
8854
+ let used = 0;
8855
+ for (let page = 1;; page++) {
8856
+ const out = runBounded(runner, ["api", `repos/{owner}/{repo}/issues/${number}/comments?per_page=${PAGE_SIZE}&page=${page}`], subjectLabel, used);
8857
+ used += Buffer.byteLength(out, "utf8");
8858
+ const pageRows = JSON.parse(out);
8859
+ rows.push(...pageRows);
8860
+ if (pageRows.length < PAGE_SIZE)
8861
+ return rows;
8862
+ }
8863
+ }
8864
+ function readIssueComments(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
8865
+ const number = resolveNumber(issue, subjectLabel, runner);
8866
+ const fromSnapshot = snapshotComments(number);
8867
+ if (fromSnapshot !== null)
8868
+ return fromSnapshot;
8869
+ return readRestCommentRows(number, subjectLabel, runner).map((r) => ({
8870
+ body: r.body ?? "",
8871
+ url: r.html_url ?? "",
8872
+ author: r.user?.login ? { login: r.user.login } : null
8873
+ }));
8874
+ }
8875
+ function readIssueBody(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
8876
+ if (forgeSnapshotDir() !== null) {
8877
+ const fromSnapshot = snapshotBody(resolveNumber(issue, subjectLabel, runner));
8878
+ if (fromSnapshot !== null)
8879
+ return fromSnapshot;
8880
+ }
8881
+ const out = runBounded(runner, ["issue", "view", String(issue), "--json", "body"], subjectLabel, 0);
8882
+ return JSON.parse(out).body ?? "";
8883
+ }
8884
+ function readIssueFields(issue, fields, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
8885
+ return JSON.parse(runBounded(runner, ["issue", "view", String(issue), "--json", fields], subjectLabel, 0));
8886
+ }
8887
+ function resolveNumber(issue, subjectLabel, runner) {
8888
+ if (typeof issue === "number")
8889
+ return issue;
8890
+ if (/^\d+$/.test(issue))
8891
+ return Number(issue);
8892
+ return readIssueFields(issue, "number", subjectLabel, runner).number;
8893
+ }
8894
+
8895
+ // src/lib/forge-snapshot.ts
8896
+ var FORGE_SNAPSHOT_DIR_ENV = "VINAYA_FORGE_SNAPSHOT_DIR";
8897
+ var PULL_FILE = "pull.json";
8898
+ var PULL_COMMENTS_FILE = "pull-comments.json";
8899
+ var ISSUE_FILE = "issue.json";
8900
+ var ISSUE_COMMENTS_FILE = "issue-comments.json";
8901
+ function forgeSnapshotDir(env = process.env) {
8902
+ if (env.GITHUB_ACTIONS !== "true")
8903
+ return null;
8904
+ const dir = env[FORGE_SNAPSHOT_DIR_ENV];
8905
+ return dir ? dir : null;
8906
+ }
8907
+
8908
+ class ForgeSnapshotIncompleteError extends Error {
8909
+ constructor(dir, file) {
8910
+ 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.`);
8911
+ this.name = "ForgeSnapshotIncompleteError";
8912
+ }
8913
+ }
8914
+
8915
+ class ForgeSnapshotIssueNotFoundError extends Error {
8916
+ constructor(issue) {
8917
+ super(`Issue #${issue} did not resolve (HTTP 404) when this run's forge snapshot was read.`);
8918
+ this.name = "ForgeSnapshotIssueNotFoundError";
8919
+ }
8920
+ }
8921
+ function readSnapshotFile(dir, file) {
8922
+ let text;
8923
+ try {
8924
+ text = readFileSync3(join2(dir, file), "utf8");
8925
+ } catch {
8926
+ throw new ForgeSnapshotIncompleteError(dir, file);
8927
+ }
8928
+ return JSON.parse(text);
8929
+ }
8930
+ function readComments(dir, file, number) {
8931
+ const parsed = readSnapshotFile(dir, file);
8932
+ if (parsed.number !== number)
8933
+ throw new ForgeSnapshotIncompleteError(dir, `${file} for #${number}`);
8934
+ return parsed.comments;
8935
+ }
8936
+ function snapshotPullRequest(number, env = process.env) {
8937
+ const dir = forgeSnapshotDir(env);
8938
+ if (dir === null)
8939
+ return null;
8940
+ const pull = readSnapshotFile(dir, PULL_FILE);
8941
+ return pull.number === number ? pull : null;
8942
+ }
8943
+ function snapshotIssue(number, env = process.env) {
8944
+ const dir = forgeSnapshotDir(env);
8945
+ if (dir === null)
8946
+ return null;
8947
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
8948
+ if (issue.number !== number)
8949
+ return null;
8950
+ if ("notFound" in issue)
8951
+ throw new ForgeSnapshotIssueNotFoundError(number);
8952
+ return issue;
8953
+ }
8954
+ function snapshotComments(number, env = process.env) {
8955
+ const dir = forgeSnapshotDir(env);
8956
+ if (dir === null)
8957
+ return null;
8958
+ if (snapshotPullRequest(number, env) !== null)
8959
+ return readComments(dir, PULL_COMMENTS_FILE, number);
8960
+ if (snapshotIssue(number, env) !== null)
8961
+ return readComments(dir, ISSUE_COMMENTS_FILE, number);
8962
+ return null;
8963
+ }
8964
+ function snapshotBody(number, env = process.env) {
8965
+ const pull = snapshotPullRequest(number, env);
8966
+ if (pull !== null)
8967
+ return pull.body;
8968
+ return snapshotIssue(number, env)?.body ?? null;
8969
+ }
8970
+ function incompleteForgeSnapshot(env = process.env) {
8971
+ const dir = forgeSnapshotDir(env);
8972
+ if (dir === null)
8973
+ return null;
8974
+ for (const file of [PULL_FILE, PULL_COMMENTS_FILE, ISSUE_FILE]) {
8975
+ if (!existsSync2(join2(dir, file)))
8976
+ return new ForgeSnapshotIncompleteError(dir, file).message;
8977
+ }
8978
+ try {
8979
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
8980
+ if (typeof issue.number === "number" && !("notFound" in issue) && !existsSync2(join2(dir, ISSUE_COMMENTS_FILE))) {
8981
+ return new ForgeSnapshotIncompleteError(dir, ISSUE_COMMENTS_FILE).message;
8982
+ }
8983
+ } catch (err) {
8984
+ return `the forge snapshot ${dir} has an unreadable ${ISSUE_FILE}: ${err.message}`;
8985
+ }
8986
+ return null;
8987
+ }
8988
+ function exitOnIncompleteForgeSnapshot(checkName, env = process.env) {
8989
+ const reason = incompleteForgeSnapshot(env);
8990
+ if (reason === null)
8991
+ return;
8992
+ emitCheckError({
8993
+ schema: CHECK_SCHEMA_VERSION,
8994
+ check: checkName,
8995
+ severity: "error",
8996
+ message: `${checkName}: ${reason}`,
8997
+ 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.`
8998
+ });
8999
+ process.exit(1);
7384
9000
  }
7385
9001
 
7386
9002
  // src/lib/numstat.ts
@@ -7694,8 +9310,11 @@ function checkBareDigits(rawBody) {
7694
9310
  // src/checks/bin/check-body-bare-digits.ts
7695
9311
  var CHECK_NAME = "body-bare-digits";
7696
9312
  function fetchPr(prNumber) {
9313
+ const fromSnapshot = snapshotPullRequest(prNumber);
9314
+ if (fromSnapshot !== null)
9315
+ return fromSnapshot;
7697
9316
  try {
7698
- const out = execFileSync3("gh", ["pr", "view", String(prNumber), "--json", "number,headRefName,author"], {
9317
+ const out = execFileSync4("gh", ["pr", "view", String(prNumber), "--json", "number,headRefName,author"], {
7699
9318
  encoding: "utf8",
7700
9319
  stdio: ["ignore", "pipe", "pipe"]
7701
9320
  });
@@ -7716,6 +9335,7 @@ function isExemptChangesetsReleasePr(prNumberStr) {
7716
9335
  return isChangesetsReleasePr(pr.headRefName, pr.author?.login ?? null, resolveReleaseActor(loadTrustAnchorConfig()));
7717
9336
  }
7718
9337
  function main() {
9338
+ exitOnIncompleteForgeSnapshot(CHECK_NAME);
7719
9339
  if (isExemptChangesetsReleasePr(process.env.PR_NUMBER)) {
7720
9340
  process.exit(0);
7721
9341
  }