@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
@@ -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 = (fetch2) => options.retryFailedReads ? retryOnce(fetch2) : fetch2();
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(fetch2) {
834
+ try {
835
+ return await fetch2();
836
+ } catch {
837
+ return fetch2();
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) {
3738
- findings.push({
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)) {
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
  }
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
+ }
4075
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,11 +7827,21 @@ 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/pr-report-engine.ts
6840
- import { execFile as execFile6 } from "node:child_process";
6841
- import { promisify as promisify6 } from "node:util";
7843
+ import { execFile as execFile7 } from "node:child_process";
7844
+ import { promisify as promisify7 } from "node:util";
6842
7845
 
6843
7846
  // src/checks/registry.ts
6844
7847
  import { join as join2, relative, sep } from "node:path";
@@ -6878,6 +7881,7 @@ var REGISTRY = [
6878
7881
  {
6879
7882
  name: "brief-shape",
6880
7883
  validates: "body",
7884
+ requiresOpenPr: true,
6881
7885
  run: bin("check-brief-shape"),
6882
7886
  scope: "diff",
6883
7887
  timeoutMs: 15000,
@@ -6886,7 +7890,9 @@ var REGISTRY = [
6886
7890
  BRANCH: { optional: true },
6887
7891
  PR_NUMBER: { optional: true },
6888
7892
  GITHUB_TOKEN: { optional: true },
6889
- GH_TOKEN: { optional: true }
7893
+ GH_TOKEN: { optional: true },
7894
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
7895
+ GITHUB_ACTIONS: { optional: true }
6890
7896
  }
6891
7897
  },
6892
7898
  0
@@ -6895,6 +7901,7 @@ var REGISTRY = [
6895
7901
  {
6896
7902
  name: "pr-report-density",
6897
7903
  validates: "body",
7904
+ requiresOpenPr: true,
6898
7905
  run: bin("check-pr-report-density"),
6899
7906
  scope: "diff",
6900
7907
  timeoutMs: 15000,
@@ -6920,7 +7927,9 @@ var REGISTRY = [
6920
7927
  PR_NUMBER: { optional: true },
6921
7928
  GITHUB_REPOSITORY: { optional: true },
6922
7929
  GITHUB_TOKEN: { optional: true },
6923
- GH_TOKEN: { optional: true }
7930
+ GH_TOKEN: { optional: true },
7931
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
7932
+ GITHUB_ACTIONS: { optional: true }
6924
7933
  }
6925
7934
  },
6926
7935
  0
@@ -6944,6 +7953,7 @@ var REGISTRY = [
6944
7953
  {
6945
7954
  name: "pr-premise-reassert",
6946
7955
  validates: "body",
7956
+ requiresOpenPr: true,
6947
7957
  run: bin("check-pr-premise-reassert"),
6948
7958
  scope: "diff",
6949
7959
  timeoutMs: 15000,
@@ -6964,7 +7974,9 @@ var REGISTRY = [
6964
7974
  BRANCH: { optional: true },
6965
7975
  GITHUB_TOKEN: { optional: true },
6966
7976
  GH_TOKEN: { optional: true },
6967
- PREMISE_FILE: { optional: true }
7977
+ PREMISE_FILE: { optional: true },
7978
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
7979
+ GITHUB_ACTIONS: { optional: true }
6968
7980
  }
6969
7981
  },
6970
7982
  0
@@ -7016,7 +8028,9 @@ var REGISTRY = [
7016
8028
  PR_BODY: { optional: true },
7017
8029
  PR_BODY_FILE: { optional: true },
7018
8030
  GITHUB_TOKEN: { optional: true },
7019
- GH_TOKEN: { optional: true }
8031
+ GH_TOKEN: { optional: true },
8032
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
8033
+ GITHUB_ACTIONS: { optional: true }
7020
8034
  }
7021
8035
  },
7022
8036
  1
@@ -7032,7 +8046,13 @@ var REGISTRY = [
7032
8046
  principalOwed: true,
7033
8047
  env: {
7034
8048
  PR_BODY: { optional: true },
7035
- BRANCH: { optional: true }
8049
+ BRANCH: { optional: true },
8050
+ PULL_REQUEST_HEAD_SHA: { optional: true },
8051
+ GITHUB_REPOSITORY: { optional: true },
8052
+ GITHUB_TOKEN: { optional: true },
8053
+ GH_TOKEN: { optional: true },
8054
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
8055
+ GITHUB_ACTIONS: { optional: true }
7036
8056
  }
7037
8057
  },
7038
8058
  1
@@ -7048,7 +8068,13 @@ var REGISTRY = [
7048
8068
  ownWorkflow: true,
7049
8069
  env: {
7050
8070
  PR_BODY: { optional: true },
7051
- BRANCH: { optional: true }
8071
+ BRANCH: { optional: true },
8072
+ PULL_REQUEST_HEAD_SHA: { optional: true },
8073
+ GITHUB_REPOSITORY: { optional: true },
8074
+ GITHUB_TOKEN: { optional: true },
8075
+ GH_TOKEN: { optional: true },
8076
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
8077
+ GITHUB_ACTIONS: { optional: true }
7052
8078
  }
7053
8079
  },
7054
8080
  1
@@ -7067,7 +8093,9 @@ var REGISTRY = [
7067
8093
  PR_NUMBER: { optional: true },
7068
8094
  GITHUB_REPOSITORY: { optional: true },
7069
8095
  GITHUB_TOKEN: { optional: true },
7070
- GH_TOKEN: { optional: true }
8096
+ GH_TOKEN: { optional: true },
8097
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
8098
+ GITHUB_ACTIONS: { optional: true }
7071
8099
  }
7072
8100
  },
7073
8101
  1
@@ -7107,7 +8135,9 @@ var REGISTRY = [
7107
8135
  PR_NUMBER: { optional: true },
7108
8136
  GITHUB_REPOSITORY: { optional: true },
7109
8137
  GITHUB_TOKEN: { optional: true },
7110
- GH_TOKEN: { optional: true }
8138
+ GH_TOKEN: { optional: true },
8139
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
8140
+ GITHUB_ACTIONS: { optional: true }
7111
8141
  }
7112
8142
  },
7113
8143
  1
@@ -7160,12 +8190,15 @@ var REGISTRY = [
7160
8190
  {
7161
8191
  name: "doc-coverage-push",
7162
8192
  validates: "body",
8193
+ advisory: true,
7163
8194
  run: bin("check-doc-coverage-push"),
7164
8195
  scope: "diff",
7165
8196
  timeoutMs: 15000,
7166
8197
  env: {
7167
8198
  OVERRIDE_DOCS: { optional: true },
7168
8199
  BASE_SHA: { optional: true },
8200
+ GIT_INDEX_FILE: { optional: true },
8201
+ VINAYA_COMMIT_HOOK: { optional: true },
7169
8202
  PR_BODY: { optional: true },
7170
8203
  PR_BODY_FILE: { optional: true },
7171
8204
  PR_LABELS: { optional: true },
@@ -7177,21 +8210,6 @@ var REGISTRY = [
7177
8210
  },
7178
8211
  0
7179
8212
  ],
7180
- [
7181
- {
7182
- name: "issue-assignment",
7183
- run: bin("check-issue-assignment"),
7184
- scope: "full",
7185
- timeoutMs: 30000,
7186
- env: {
7187
- AEG_REPO: { optional: true },
7188
- BRANCH: { optional: true },
7189
- GITHUB_TOKEN: { optional: true },
7190
- GH_TOKEN: { optional: true }
7191
- }
7192
- },
7193
- 0
7194
- ],
7195
8213
  [
7196
8214
  {
7197
8215
  name: "evidence-fresh",
@@ -7205,7 +8223,9 @@ var REGISTRY = [
7205
8223
  PR_BODY: { optional: true },
7206
8224
  BASE_SHA: { optional: true },
7207
8225
  GITHUB_TOKEN: { optional: true },
7208
- GH_TOKEN: { optional: true }
8226
+ GH_TOKEN: { optional: true },
8227
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
8228
+ GITHUB_ACTIONS: { optional: true }
7209
8229
  }
7210
8230
  },
7211
8231
  1
@@ -7216,7 +8236,11 @@ var REGISTRY = [
7216
8236
  run: bin("check-reader-resolvable-prose"),
7217
8237
  scope: "full",
7218
8238
  timeoutMs: 30000,
7219
- env: {},
8239
+ env: {
8240
+ BASE_SHA: { optional: true },
8241
+ GIT_INDEX_FILE: { optional: true },
8242
+ VINAYA_COMMIT_HOOK: { optional: true }
8243
+ },
7220
8244
  include: [
7221
8245
  "aeg-root/**/*.md",
7222
8246
  "apps/cli/src/**",
@@ -7234,7 +8258,11 @@ var REGISTRY = [
7234
8258
  run: bin("check-retired-vocabulary"),
7235
8259
  scope: "full",
7236
8260
  timeoutMs: 30000,
7237
- env: {},
8261
+ env: {
8262
+ BASE_SHA: { optional: true },
8263
+ GIT_INDEX_FILE: { optional: true },
8264
+ VINAYA_COMMIT_HOOK: { optional: true }
8265
+ },
7238
8266
  include: ["aeg-root/**/*.md"]
7239
8267
  },
7240
8268
  0
@@ -7242,10 +8270,15 @@ var REGISTRY = [
7242
8270
  [
7243
8271
  {
7244
8272
  name: "doctrine-portability",
8273
+ advisory: true,
7245
8274
  run: bin("check-doctrine-portability"),
7246
8275
  scope: "full",
7247
8276
  timeoutMs: 30000,
7248
- env: { BASE_SHA: { optional: true } },
8277
+ env: {
8278
+ BASE_SHA: { optional: true },
8279
+ GIT_INDEX_FILE: { optional: true },
8280
+ VINAYA_COMMIT_HOOK: { optional: true }
8281
+ },
7249
8282
  include: ["aeg-root/**/*.md"]
7250
8283
  },
7251
8284
  0
@@ -7278,7 +8311,11 @@ var REGISTRY = [
7278
8311
  run: bin("check-exec-bits"),
7279
8312
  scope: "diff",
7280
8313
  timeoutMs: 30000,
7281
- env: {}
8314
+ env: {
8315
+ BASE_SHA: { optional: true },
8316
+ GIT_INDEX_FILE: { optional: true },
8317
+ VINAYA_COMMIT_HOOK: { optional: true }
8318
+ }
7282
8319
  },
7283
8320
  0
7284
8321
  ],
@@ -7288,17 +8325,26 @@ var REGISTRY = [
7288
8325
  run: bin("check-ci-shard-coverage"),
7289
8326
  scope: "diff",
7290
8327
  timeoutMs: 15000,
7291
- env: {}
8328
+ env: {
8329
+ BASE_SHA: { optional: true },
8330
+ GIT_INDEX_FILE: { optional: true },
8331
+ VINAYA_COMMIT_HOOK: { optional: true }
8332
+ }
7292
8333
  },
7293
8334
  0
7294
8335
  ],
7295
8336
  [
7296
8337
  {
7297
8338
  name: "workspace-escape",
8339
+ advisory: true,
7298
8340
  run: bin("check-workspace-escape"),
7299
8341
  scope: "full",
7300
8342
  timeoutMs: 30000,
7301
- env: {},
8343
+ env: {
8344
+ BASE_SHA: { optional: true },
8345
+ GIT_INDEX_FILE: { optional: true },
8346
+ VINAYA_COMMIT_HOOK: { optional: true }
8347
+ },
7302
8348
  include: ["aeg-root/**/*.md"]
7303
8349
  },
7304
8350
  0
@@ -7309,17 +8355,23 @@ var REGISTRY = [
7309
8355
  run: bin("check-changeset-coverage"),
7310
8356
  scope: "diff",
7311
8357
  timeoutMs: 15000,
7312
- env: {}
8358
+ env: {
8359
+ BASE_SHA: { optional: true },
8360
+ GIT_INDEX_FILE: { optional: true },
8361
+ VINAYA_COMMIT_HOOK: { optional: true }
8362
+ }
7313
8363
  },
7314
8364
  0
7315
8365
  ],
7316
8366
  [
7317
8367
  {
7318
8368
  name: "quoted-command",
8369
+ advisory: true,
7319
8370
  run: bin("check-quoted-command"),
7320
- scope: "diff",
8371
+ scope: "full",
7321
8372
  timeoutMs: 15000,
7322
- env: {}
8373
+ env: {},
8374
+ include: ["aeg-root/**/*.md"]
7323
8375
  },
7324
8376
  0
7325
8377
  ],
@@ -7327,7 +8379,7 @@ var REGISTRY = [
7327
8379
  {
7328
8380
  name: "main-branch-refusal",
7329
8381
  run: bin("check-main-branch-refusal"),
7330
- scope: "full",
8382
+ scope: "diff",
7331
8383
  timeoutMs: 15000,
7332
8384
  env: { VINAYA_PUSH_REFS: { optional: true } }
7333
8385
  },
@@ -7394,18 +8446,6 @@ var REGISTRY = [
7394
8446
  },
7395
8447
  1
7396
8448
  ],
7397
- [
7398
- {
7399
- name: "issue-tranche-label",
7400
- run: bin("check-issue-tranche-label"),
7401
- validates: "issue",
7402
- scope: "full",
7403
- ownWorkflow: true,
7404
- timeoutMs: 15000,
7405
- env: { ISSUE_BODY: { optional: true }, ISSUE_LABELS: { optional: true } }
7406
- },
7407
- 1
7408
- ],
7409
8449
  [
7410
8450
  {
7411
8451
  name: "issue-milestone-attach",
@@ -7438,7 +8478,7 @@ import {
7438
8478
  existsSync as existsSync5,
7439
8479
  fstatSync as fstatSync3,
7440
8480
  mkdirSync as mkdirSync4,
7441
- lstatSync as lstatSync2,
8481
+ lstatSync as lstatSync3,
7442
8482
  openSync as openSync4,
7443
8483
  readFileSync as readFileSync5,
7444
8484
  renameSync as renameSync2,
@@ -7452,32 +8492,323 @@ import { promisify as promisify5 } from "node:util";
7452
8492
  // src/lib/config.ts
7453
8493
  import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
7454
8494
  import { promisify as promisify4 } from "node:util";
7455
- import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync } from "node:fs";
8495
+ import { existsSync as existsSync2, lstatSync, mkdirSync, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync } from "node:fs";
7456
8496
  import { homedir } from "node:os";
7457
- import { dirname as dirname2, isAbsolute, join as join3, resolve } from "node:path";
7458
- import { z as z5 } from "zod";
8497
+ import { basename as basename3, dirname as dirname2, isAbsolute, join as join3, resolve } from "node:path";
8498
+ import { z as z6 } from "zod";
8499
+
8500
+ // src/checks/contract.ts
8501
+ var CHECK_SCHEMA_VERSION = 1;
8502
+ function emitCheckError(error) {
8503
+ process.stderr.write(`${JSON.stringify(error)}
8504
+ `);
8505
+ }
7459
8506
 
7460
8507
  // src/lib/agent-vendors.ts
7461
8508
  var AGENT_VENDORS = ["skills", "claude", "gemini"];
7462
8509
 
8510
+ // src/lib/prose-rules-config.ts
8511
+ import safeRegex from "safe-regex2";
8512
+ import { z as z5 } from "zod";
8513
+ var SEVERITIES = ["error", "warning"];
8514
+ var OVERRIDE_KEYS = ["scopes", "severity", "exempt"];
8515
+ var FIXED_DEFAULT_KEYS = ["pattern", "patterns", "flags", "means", "message", "id"];
8516
+ var CUSTOM_KEYS = ["id", "pattern", "patterns", "flags", "means", "scopes", "severity", "exempt"];
8517
+ var DEFAULT_IDS = new Set([...DEFAULT_PROSE_RULES.map((rule) => rule.id), DECISION_RECORD_CITATION_ID]);
8518
+ function isPlainObject3(value) {
8519
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8520
+ }
8521
+ function outsideRepositoryReason(entry) {
8522
+ if (entry.startsWith("/") || /^[A-Za-z]:/.test(entry))
8523
+ return "must be a repository-relative path, not an absolute one";
8524
+ if (entry.split(/[\\/]/).includes(".."))
8525
+ return "must stay inside the repository — no `..` segment";
8526
+ return null;
8527
+ }
8528
+ var RepoRelativePathSchema = z5.string().min(1).superRefine((entry, ctx) => {
8529
+ const reason = outsideRepositoryReason(entry);
8530
+ if (reason)
8531
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, message: reason });
8532
+ });
8533
+ function pathListIssues(value, path, issues) {
8534
+ if (!Array.isArray(value)) {
8535
+ issues.push({ path, message: "must be a list of repository-relative paths" });
8536
+ return;
8537
+ }
8538
+ value.forEach((entry, index) => {
8539
+ if (typeof entry !== "string" || entry.length === 0) {
8540
+ issues.push({ path: [...path, index], message: "must be a non-empty repository-relative path" });
8541
+ return;
8542
+ }
8543
+ const reason = outsideRepositoryReason(entry);
8544
+ if (reason)
8545
+ issues.push({ path: [...path, index], message: reason });
8546
+ });
8547
+ }
8548
+ function scopeListIssues(value, path, allowed, issues) {
8549
+ if (!Array.isArray(value) || value.length === 0) {
8550
+ issues.push({ path, message: "must name at least one scope" });
8551
+ return null;
8552
+ }
8553
+ const scopes = [];
8554
+ value.forEach((scope, index) => {
8555
+ if (typeof scope !== "string" || !CONFIGURABLE_PROSE_SCOPES.includes(scope)) {
8556
+ issues.push({
8557
+ path: [...path, index],
8558
+ 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(", ")}`
8559
+ });
8560
+ return;
8561
+ }
8562
+ if (!allowed.includes(scope)) {
8563
+ issues.push({
8564
+ path: [...path, index],
8565
+ message: `scope "${scope}" is not one this rule can run in — it can run in: ${allowed.join(", ")}`
8566
+ });
8567
+ return;
8568
+ }
8569
+ scopes.push(scope);
8570
+ });
8571
+ return scopes;
8572
+ }
8573
+ function severityIssues(value, path, scopes, issues) {
8574
+ if (typeof value === "string") {
8575
+ if (!SEVERITIES.includes(value)) {
8576
+ issues.push({ path, message: `unknown severity ${JSON.stringify(value)} — use "error" or "warning"` });
8577
+ }
8578
+ return;
8579
+ }
8580
+ if (!isPlainObject3(value)) {
8581
+ issues.push({ path, message: 'must be "error", "warning", or a map from scope to one of them' });
8582
+ return;
8583
+ }
8584
+ for (const [scope, severity] of Object.entries(value)) {
8585
+ if (!scopes.includes(scope)) {
8586
+ issues.push({ path: [...path, scope], message: `names scope "${scope}", which this rule's scopes do not cover` });
8587
+ }
8588
+ if (typeof severity !== "string" || !SEVERITIES.includes(severity)) {
8589
+ issues.push({
8590
+ path: [...path, scope],
8591
+ message: `unknown severity ${JSON.stringify(severity)} — use "error" or "warning"`
8592
+ });
8593
+ }
8594
+ }
8595
+ }
8596
+ function patternIssues(source, flags, path, issues) {
8597
+ if (typeof source !== "string" || source.length === 0) {
8598
+ issues.push({ path, message: "must be a non-empty regular expression" });
8599
+ return;
8600
+ }
8601
+ if (source.length > CONFIGURED_PATTERN_MAX_LENGTH) {
8602
+ issues.push({
8603
+ path,
8604
+ message: `is ${source.length} characters, over the ${CONFIGURED_PATTERN_MAX_LENGTH}-character limit for a configured pattern`
8605
+ });
8606
+ return;
8607
+ }
8608
+ try {
8609
+ new RegExp(source, flags);
8610
+ } catch (err) {
8611
+ issues.push({ path, message: `does not compile: ${err.message}` });
8612
+ return;
8613
+ }
8614
+ if (!safeRegex(source, { limit: Number.MAX_SAFE_INTEGER })) {
8615
+ issues.push({
8616
+ path,
8617
+ 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."
8618
+ });
8619
+ }
8620
+ }
8621
+ function flagIssues(value, path, issues) {
8622
+ if (value === undefined)
8623
+ return "";
8624
+ if (typeof value !== "string") {
8625
+ issues.push({ path, message: 'must be a string of flags, e.g. "i"' });
8626
+ return "";
8627
+ }
8628
+ const seen = new Set;
8629
+ for (const flag of value) {
8630
+ if (!CONFIGURED_PROSE_FLAGS.includes(flag)) {
8631
+ issues.push({
8632
+ path,
8633
+ message: `unknown flag ${JSON.stringify(flag)} — only ${CONFIGURED_PROSE_FLAGS.map((f) => `"${f}"`).join(" and ")} are allowed`
8634
+ });
8635
+ return "";
8636
+ }
8637
+ if (seen.has(flag)) {
8638
+ issues.push({ path, message: `repeats the flag "${flag}"` });
8639
+ return "";
8640
+ }
8641
+ seen.add(flag);
8642
+ }
8643
+ return value;
8644
+ }
8645
+ function defaultsIssues(value, issues) {
8646
+ const base = ["defaults"];
8647
+ if (!isPlainObject3(value)) {
8648
+ issues.push({ path: base, message: 'must map a default rule id to "off" or an override' });
8649
+ return;
8650
+ }
8651
+ for (const [id, override] of Object.entries(value)) {
8652
+ const path = [...base, id];
8653
+ const rule = CONFIGURABLE_DEFAULT_RULES.find((candidate) => candidate.id === id);
8654
+ if (!rule) {
8655
+ issues.push({
8656
+ path,
8657
+ message: `unknown default rule id "${id}" — \`vinaya check --plan\` lists the rules each prose check runs`
8658
+ });
8659
+ continue;
8660
+ }
8661
+ if (override === "off")
8662
+ continue;
8663
+ if (!isPlainObject3(override)) {
8664
+ issues.push({ path, message: 'must be "off" or an object with any of scopes, severity, exempt' });
8665
+ continue;
8666
+ }
8667
+ for (const key of Object.keys(override)) {
8668
+ if (OVERRIDE_KEYS.includes(key))
8669
+ continue;
8670
+ issues.push({
8671
+ path: [...path, key],
8672
+ 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`
8673
+ });
8674
+ }
8675
+ const scopes = override.scopes === undefined ? [...rule.scopes] : scopeListIssues(override.scopes, [...path, "scopes"], allowedScopesFor(rule), issues);
8676
+ if (override.severity !== undefined && scopes)
8677
+ severityIssues(override.severity, [...path, "severity"], scopes, issues);
8678
+ if (override.exempt !== undefined)
8679
+ pathListIssues(override.exempt, [...path, "exempt"], issues);
8680
+ }
8681
+ }
8682
+ function customIssues(value, issues) {
8683
+ if (!Array.isArray(value)) {
8684
+ issues.push({ path: ["custom"], message: "must be a list of rules" });
8685
+ return;
8686
+ }
8687
+ const ids = new Set;
8688
+ value.forEach((rule, index) => {
8689
+ const path = ["custom", index];
8690
+ if (!isPlainObject3(rule)) {
8691
+ issues.push({ path, message: "must be a rule object" });
8692
+ return;
8693
+ }
8694
+ for (const key of Object.keys(rule)) {
8695
+ if (!CUSTOM_KEYS.includes(key)) {
8696
+ issues.push({ path: [...path, key], message: `unknown key "${key}" — a rule takes ${CUSTOM_KEYS.join(", ")}` });
8697
+ }
8698
+ }
8699
+ if (typeof rule.id !== "string" || rule.id.length === 0) {
8700
+ issues.push({ path: [...path, "id"], message: "a custom rule needs an id" });
8701
+ } else if (DEFAULT_IDS.has(rule.id)) {
8702
+ issues.push({
8703
+ path: [...path, "id"],
8704
+ message: `"${rule.id}" is a default rule id — a custom rule needs its own id; retune the default under proseGates.rules.defaults instead`
8705
+ });
8706
+ } else if (ids.has(rule.id)) {
8707
+ issues.push({ path: [...path, "id"], message: `"${rule.id}" is used by an earlier custom rule` });
8708
+ } else {
8709
+ ids.add(rule.id);
8710
+ }
8711
+ if (typeof rule.means !== "string" || rule.means.trim().length === 0) {
8712
+ issues.push({ path: [...path, "means"], message: "a custom rule needs a message (`means`)" });
8713
+ }
8714
+ let scopes = null;
8715
+ if (rule.scopes === undefined) {
8716
+ issues.push({ path: [...path, "scopes"], message: "a custom rule needs at least one scope (`scopes`)" });
8717
+ } else {
8718
+ scopes = scopeListIssues(rule.scopes, [...path, "scopes"], CONFIGURABLE_PROSE_SCOPES, issues);
8719
+ }
8720
+ if (scopes && new Set(scopes.map(groupOfScope)).size > 1) {
8721
+ issues.push({
8722
+ path: [...path, "scopes"],
8723
+ 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'
8724
+ });
8725
+ }
8726
+ const flags = flagIssues(rule.flags, [...path, "flags"], issues);
8727
+ if (rule.pattern === undefined && rule.patterns === undefined) {
8728
+ issues.push({
8729
+ path: [...path, "pattern"],
8730
+ message: "a custom rule needs a `pattern` or a per-scope `patterns` map"
8731
+ });
8732
+ }
8733
+ if (rule.pattern !== undefined)
8734
+ patternIssues(rule.pattern, flags, [...path, "pattern"], issues);
8735
+ if (rule.patterns !== undefined) {
8736
+ if (!isPlainObject3(rule.patterns)) {
8737
+ issues.push({ path: [...path, "patterns"], message: "must map a scope to a regular expression" });
8738
+ } else {
8739
+ for (const [scope, source] of Object.entries(rule.patterns)) {
8740
+ if (scopes && !scopes.includes(scope)) {
8741
+ issues.push({
8742
+ path: [...path, "patterns", scope],
8743
+ message: `names scope "${scope}", which this rule's scopes do not cover`
8744
+ });
8745
+ continue;
8746
+ }
8747
+ patternIssues(source, flags, [...path, "patterns", scope], issues);
8748
+ }
8749
+ if (rule.pattern === undefined && scopes) {
8750
+ for (const scope of scopes) {
8751
+ if (!(scope in rule.patterns)) {
8752
+ issues.push({
8753
+ path: [...path, "patterns"],
8754
+ message: `has no pattern for scope "${scope}" — add one, or a \`pattern\` every other scope uses`
8755
+ });
8756
+ }
8757
+ }
8758
+ }
8759
+ }
8760
+ }
8761
+ if (rule.severity !== undefined && scopes)
8762
+ severityIssues(rule.severity, [...path, "severity"], scopes, issues);
8763
+ if (rule.exempt !== undefined)
8764
+ pathListIssues(rule.exempt, [...path, "exempt"], issues);
8765
+ });
8766
+ }
8767
+ function proseRulesIssues(value) {
8768
+ const issues = [];
8769
+ if (!isPlainObject3(value))
8770
+ return [{ path: [], message: "must be an object with any of exempt, defaults, custom" }];
8771
+ for (const key of Object.keys(value)) {
8772
+ if (!["exempt", "defaults", "custom"].includes(key)) {
8773
+ issues.push({ path: [key], message: `unknown key "${key}" — proseGates.rules takes exempt, defaults and custom` });
8774
+ }
8775
+ }
8776
+ if (value.exempt !== undefined)
8777
+ pathListIssues(value.exempt, ["exempt"], issues);
8778
+ if (value.defaults !== undefined)
8779
+ defaultsIssues(value.defaults, issues);
8780
+ if (value.custom !== undefined)
8781
+ customIssues(value.custom, issues);
8782
+ return issues;
8783
+ }
8784
+ var ProseRulesSchema = z5.unknown().superRefine((value, ctx) => {
8785
+ for (const issue of proseRulesIssues(value)) {
8786
+ ctx.addIssue({ code: z5.ZodIssueCode.custom, path: issue.path, message: issue.message });
8787
+ }
8788
+ }).transform((value) => value);
8789
+ var PublishedProseSchema = z5.object({
8790
+ allow: z5.array(z5.string().min(1)).optional()
8791
+ }).strict();
8792
+
7463
8793
  // src/lib/config.ts
7464
- var EnvEntrySchema = z5.union([
7465
- z5.literal(true),
7466
- z5.object({ optional: z5.literal(true) }),
7467
- z5.object({ anyOf: z5.array(z5.string()).min(2) }),
7468
- z5.string()
8794
+ var EnvEntrySchema = z6.union([
8795
+ z6.literal(true),
8796
+ z6.object({ optional: z6.literal(true) }),
8797
+ z6.object({ anyOf: z6.array(z6.string()).min(2) }),
8798
+ z6.string()
7469
8799
  ]);
7470
- var CheckEntrySchema = z5.object({
7471
- run: z5.string(),
7472
- scope: z5.enum(["diff", "full"]),
7473
- include: z5.array(z5.string()).optional(),
7474
- args: z5.array(z5.string()).optional(),
7475
- timeoutMs: z5.number().optional(),
7476
- env: z5.record(z5.string(), EnvEntrySchema).optional(),
7477
- requiresOpenPr: z5.boolean().optional(),
7478
- ownWorkflow: z5.boolean().optional(),
7479
- principalOwed: z5.literal(true).optional(),
7480
- validates: z5.enum(["body", "issue"]).optional()
8800
+ var CheckEntrySchema = z6.object({
8801
+ run: z6.string(),
8802
+ scope: z6.enum(["diff", "full"]),
8803
+ include: z6.array(z6.string()).optional(),
8804
+ args: z6.array(z6.string()).optional(),
8805
+ timeoutMs: z6.number().optional(),
8806
+ env: z6.record(z6.string(), EnvEntrySchema).optional(),
8807
+ requiresOpenPr: z6.boolean().optional(),
8808
+ ownWorkflow: z6.boolean().optional(),
8809
+ principalOwed: z6.literal(true).optional(),
8810
+ validates: z6.enum(["body", "issue"]).optional(),
8811
+ advisory: z6.literal(true).optional()
7481
8812
  }).superRefine((entry, ctx) => {
7482
8813
  if (!entry.env)
7483
8814
  return;
@@ -7487,22 +8818,22 @@ var CheckEntrySchema = z5.object({
7487
8818
  const members = value.anyOf;
7488
8819
  if (new Set(members).size !== members.length) {
7489
8820
  ctx.addIssue({
7490
- code: z5.ZodIssueCode.custom,
8821
+ code: z6.ZodIssueCode.custom,
7491
8822
  message: `env.${key}.anyOf has duplicate members`,
7492
8823
  path: ["env", key, "anyOf"]
7493
8824
  });
7494
8825
  }
7495
8826
  if (!members.includes(key)) {
7496
8827
  ctx.addIssue({
7497
- code: z5.ZodIssueCode.custom,
8828
+ code: z6.ZodIssueCode.custom,
7498
8829
  message: `env.${key}.anyOf must include "${key}" itself as a member`,
7499
8830
  path: ["env", key, "anyOf"]
7500
8831
  });
7501
8832
  }
7502
8833
  }
7503
8834
  });
7504
- var RoleEntrySchema = z5.object({
7505
- contract: z5.string().refine((p) => p.includes("/"), {
8835
+ var RoleEntrySchema = z6.object({
8836
+ contract: z6.string().refine((p) => p.includes("/"), {
7506
8837
  message: 'must be a path (contain at least one "/"), not a bare filename'
7507
8838
  })
7508
8839
  });
@@ -7526,17 +8857,17 @@ var BRIEF_BUILTINS = [
7526
8857
  "briefSections",
7527
8858
  "milestoneShape"
7528
8859
  ];
7529
- var BriefSectionSchema = z5.union([
7530
- z5.object({ builtin: z5.enum(BRIEF_BUILTINS) }),
7531
- z5.object({ heading: z5.string().min(1), name: z5.string().optional() }),
7532
- z5.object({ field: z5.string().min(1), name: z5.string().optional() }),
7533
- z5.object({ phrase: z5.string().min(1), name: z5.string().optional() })
8860
+ var BriefSectionSchema = z6.union([
8861
+ z6.object({ builtin: z6.enum(BRIEF_BUILTINS) }),
8862
+ z6.object({ heading: z6.string().min(1), name: z6.string().optional() }),
8863
+ z6.object({ field: z6.string().min(1), name: z6.string().optional() }),
8864
+ z6.object({ phrase: z6.string().min(1), name: z6.string().optional() })
7534
8865
  ]);
7535
- var BriefSchemaSchema = z5.object({
7536
- pr: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
7537
- issue: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
7538
- milestone: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
7539
- ack: z5.array(z5.enum(BRIEF_BUILTINS)).optional()
8866
+ var BriefSchemaSchema = z6.object({
8867
+ pr: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8868
+ issue: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8869
+ milestone: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
8870
+ ack: z6.array(z6.enum(BRIEF_BUILTINS)).optional()
7540
8871
  });
7541
8872
  function isSafeRepoRelPath(p) {
7542
8873
  if (p.length === 0)
@@ -7545,7 +8876,7 @@ function isSafeRepoRelPath(p) {
7545
8876
  return false;
7546
8877
  return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
7547
8878
  }
7548
- var SafeRepoRelPath = z5.string().refine(isSafeRepoRelPath, {
8879
+ var SafeRepoRelPath = z6.string().refine(isSafeRepoRelPath, {
7549
8880
  message: "must be a repo-root-relative path with no `..` segment or absolute root"
7550
8881
  });
7551
8882
  var CANONICAL_HOOK_BLOCK_PREFIXES = [".git/", ".husky/", ".vinaya/hooks/", ".claude/hooks/"];
@@ -7555,22 +8886,22 @@ function isCanonicalHookBlockPath(p) {
7555
8886
  var ManagedHookBlockPath = SafeRepoRelPath.refine(isCanonicalHookBlockPath, {
7556
8887
  message: `must start with one of ${CANONICAL_HOOK_BLOCK_PREFIXES.join(", ")} (byte-exact, case-sensitive)`
7557
8888
  });
7558
- var ManagedBlockRecordSchema = z5.object({
8889
+ var ManagedBlockRecordSchema = z6.object({
7559
8890
  path: ManagedHookBlockPath,
7560
- marker: z5.string(),
7561
- comment: z5.enum(["hash", "html"])
8891
+ marker: z6.string(),
8892
+ comment: z6.enum(["hash", "html"])
7562
8893
  });
7563
- var ManagedManifestSchema = z5.object({
7564
- version: z5.number().int().positive(),
7565
- files: z5.array(SafeRepoRelPath),
7566
- blocks: z5.array(ManagedBlockRecordSchema),
7567
- labels: z5.array(z5.string()),
7568
- agents: z5.array(z5.enum(AGENT_VENDORS)).optional()
8894
+ var ManagedManifestSchema = z6.object({
8895
+ version: z6.number().int().positive(),
8896
+ files: z6.array(SafeRepoRelPath),
8897
+ blocks: z6.array(ManagedBlockRecordSchema),
8898
+ labels: z6.array(z6.string()),
8899
+ agents: z6.array(z6.enum(AGENT_VENDORS)).optional()
7569
8900
  });
7570
- var ProjectEntrySchema = z5.object({
7571
- name: z5.string().min(1),
7572
- description: z5.string().min(1).optional(),
7573
- path: z5.string().min(1).optional()
8901
+ var ProjectEntrySchema = z6.object({
8902
+ name: z6.string().min(1),
8903
+ description: z6.string().min(1).optional(),
8904
+ path: z6.string().min(1).optional()
7574
8905
  });
7575
8906
  function parseTokensCollectDeclaration(value) {
7576
8907
  const m = value.trim().match(/^(\S+)\s+(\S+)$/);
@@ -7581,90 +8912,101 @@ function parseTokensCollectDeclaration(value) {
7581
8912
  return null;
7582
8913
  return { interpreter, script };
7583
8914
  }
7584
- var VinayaConfigSchema = z5.object({
7585
- rings: z5.object({
7586
- ring1_forgeWriteInterception: z5.boolean(),
7587
- ring2_asyncAudits: z5.boolean()
8915
+ var VinayaConfigObjectSchema = z6.object({
8916
+ rings: z6.object({
8917
+ ring1_forgeWriteInterception: z6.boolean(),
8918
+ ring2_asyncAudits: z6.boolean()
7588
8919
  }).optional(),
7589
- checks: z5.record(z5.string(), CheckEntrySchema).optional(),
7590
- roles: z5.record(z5.string(), RoleEntrySchema).optional(),
8920
+ checks: z6.record(z6.string(), CheckEntrySchema).optional(),
8921
+ roles: z6.record(z6.string(), RoleEntrySchema).optional(),
7591
8922
  briefSchema: BriefSchemaSchema.optional(),
7592
8923
  managed: ManagedManifestSchema.optional(),
7593
- principals: z5.array(z5.string()).min(1).optional(),
7594
- releaseActor: z5.string().min(1).optional(),
7595
- ci: z5.object({ setup: z5.string().min(1) }).optional(),
7596
- tokens: z5.object({
7597
- collect: z5.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
8924
+ principals: z6.array(z6.string()).min(1).optional(),
8925
+ releaseActor: z6.string().min(1).optional(),
8926
+ ci: z6.object({ setup: z6.string().min(1) }).optional(),
8927
+ tokens: z6.object({
8928
+ collect: z6.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
7598
8929
  message: 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
7599
8930
  })
7600
8931
  }).optional(),
7601
- blastRadius: z5.object({ extraDomains: z5.array(z5.string()).optional() }).optional(),
7602
- proseGates: z5.object({
7603
- doctrineRoot: z5.string().min(1).optional(),
7604
- readerFacingPrefix: z5.string().min(1).optional(),
7605
- readerFacingSuffix: z5.string().min(1).optional(),
7606
- legacySlugDir: z5.string().min(1).optional(),
7607
- sourceComments: z5.object({
7608
- globs: z5.array(z5.string().min(1)).optional(),
7609
- allowlist: z5.array(z5.string().min(1)).optional(),
7610
- severity: z5.enum(["warning", "error"]).optional()
8932
+ blastRadius: z6.object({ extraDomains: z6.array(z6.string()).optional() }).optional(),
8933
+ proseGates: z6.object({
8934
+ doctrineRoot: z6.string().min(1).optional(),
8935
+ readerFacingPrefix: z6.string().min(1).optional(),
8936
+ readerFacingSuffix: z6.string().min(1).optional(),
8937
+ legacySlugDir: z6.string().min(1).optional(),
8938
+ sourceComments: z6.object({
8939
+ globs: z6.array(z6.string().min(1)).optional(),
8940
+ allowlist: z6.array(z6.string().min(1)).optional(),
8941
+ severity: z6.enum(["warning", "error"]).optional()
7611
8942
  }).optional(),
7612
- specGrandfather: z5.union([z5.array(z5.string().min(1)), z5.record(z5.string().min(1), z5.number().int().min(0))]).optional(),
7613
- specPaths: z5.array(z5.string().min(1).refine((entry) => !entry.startsWith("/") && !/^[A-Za-z]:/.test(entry), {
7614
- message: "must be a repository-relative path, not an absolute one"
7615
- }).refine((entry) => !entry.split(/[\\/]/).includes(".."), {
7616
- message: "must stay inside the repository — no `..` segment"
7617
- })).optional()
8943
+ specGrandfather: z6.union([z6.array(z6.string().min(1)), z6.record(z6.string().min(1), z6.number().int().min(0))]).optional(),
8944
+ specPaths: z6.array(RepoRelativePathSchema).optional(),
8945
+ productPaths: z6.array(RepoRelativePathSchema).optional(),
8946
+ published: PublishedProseSchema.optional(),
8947
+ rules: ProseRulesSchema.optional()
7618
8948
  }).optional(),
7619
- projects: z5.array(ProjectEntrySchema).optional(),
7620
- dispatch: z5.object({
7621
- timeoutMs: z5.number().int().positive().optional(),
7622
- killGraceMs: z5.number().int().positive().optional(),
7623
- agent: z5.enum(["claude", "codex", "gemini"]).optional()
8949
+ projects: z6.array(ProjectEntrySchema).optional(),
8950
+ dispatch: z6.object({
8951
+ timeoutMs: z6.number().int().positive().optional(),
8952
+ reviewerTimeoutMs: z6.number().int().positive().optional(),
8953
+ killGraceMs: z6.number().int().positive().optional(),
8954
+ agent: z6.enum(["claude", "codex"]).optional()
7624
8955
  }).optional(),
7625
- reviewPolicy: z5.object({
7626
- codeReviewThreshold: z5.string().min(1).optional(),
7627
- securityThreshold: z5.string().min(1).optional(),
7628
- maxRounds: z5.number().optional(),
7629
- maxTaskMinutes: z5.number().optional()
8956
+ reviewPolicy: z6.object({
8957
+ codeReviewThreshold: z6.string().min(1).optional(),
8958
+ securityThreshold: z6.string().min(1).optional(),
8959
+ maxRounds: z6.number().optional(),
8960
+ maxTaskMinutes: z6.number().optional(),
8961
+ readyPushTimeoutMinutes: z6.number().optional()
7630
8962
  }).optional(),
7631
- securityScan: z5.object({
7632
- command: z5.array(z5.string().min(1)).min(1)
8963
+ securityScan: z6.object({
8964
+ command: z6.array(z6.string().min(1)).min(1)
7633
8965
  }).optional(),
7634
- gateCutovers: z5.object({
7635
- objectivesSinceIssue: z5.number().int().nonnegative().optional(),
7636
- briefSectionsSinceIssue: z5.number().int().nonnegative().optional(),
7637
- documentationSinceIssue: z5.number().int().nonnegative().optional(),
7638
- briefRulesSincePr: z5.number().int().nonnegative().optional(),
7639
- agentBoxesRefusedSincePr: z5.number().int().nonnegative().optional()
8966
+ gateCutovers: z6.object({
8967
+ objectivesSinceIssue: z6.number().int().nonnegative().optional(),
8968
+ briefSectionsSinceIssue: z6.number().int().nonnegative().optional(),
8969
+ documentationSinceIssue: z6.number().int().nonnegative().optional(),
8970
+ briefRulesSincePr: z6.number().int().nonnegative().optional(),
8971
+ agentBoxesRefusedSincePr: z6.number().int().nonnegative().optional()
7640
8972
  }).optional(),
7641
- planning: z5.object({
7642
- collisionThreshold: z5.number().int().nonnegative().optional()
8973
+ planning: z6.object({
8974
+ collisionThreshold: z6.number().int().nonnegative().optional()
7643
8975
  }).optional(),
7644
- prePush: z5.object({
7645
- alwaysRun: z5.array(z5.string()).optional()
8976
+ prePush: z6.object({
8977
+ alwaysRun: z6.array(z6.string()).optional(),
8978
+ readyTests: z6.object({
8979
+ mode: z6.literal("ci"),
8980
+ workflow: z6.literal(".github/workflows/ci.yml"),
8981
+ check: z6.literal("Vinaya CI")
8982
+ }).strict().optional(),
8983
+ requiredCi: z6.object({
8984
+ workflow: z6.literal(".github/workflows/ci.yml"),
8985
+ check: z6.literal("Vinaya CI")
8986
+ }).strict().optional()
7646
8987
  }).optional(),
7647
- report: z5.object({
7648
- commandTimeoutMs: z5.number().int().positive().optional()
8988
+ report: z6.object({
8989
+ commandTimeoutMs: z6.number().int().positive().optional()
7649
8990
  }).superRefine((report, ctx) => {
7650
8991
  const commandTimeoutMs = report.commandTimeoutMs;
7651
8992
  if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
7652
8993
  ctx.addIssue({
7653
- code: z5.ZodIssueCode.custom,
8994
+ code: z6.ZodIssueCode.custom,
7654
8995
  path: ["commandTimeoutMs"],
7655
8996
  message: "must be at most 3600000 (1 hour)"
7656
8997
  });
7657
8998
  }
7658
8999
  }).optional(),
7659
- logPublish: z5.unknown().refine((v) => v === undefined, {
9000
+ logPublish: z6.unknown().refine((v) => v === undefined, {
7660
9001
  message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
7661
9002
  }),
7662
- runtimeDir: z5.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
7663
- logs: z5.object({
7664
- folder: z5.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
7665
- url: z5.string().url().optional(),
7666
- headers: z5.record(z5.string()).optional(),
7667
- readHeaders: z5.record(z5.string()).optional(),
9003
+ runtimeDir: z6.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
9004
+ runner: z6.enum(["standalone", "atta-engine"]).optional(),
9005
+ logs: z6.object({
9006
+ folder: z6.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
9007
+ url: z6.string().url().optional(),
9008
+ headers: z6.record(z6.string()).optional(),
9009
+ readHeaders: z6.record(z6.string()).optional(),
7668
9010
  events: CustomEventDeclarationsSchema.optional()
7669
9011
  }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
7670
9012
  message: "logs: set at most one of folder/url"
@@ -7672,8 +9014,33 @@ var VinayaConfigSchema = z5.object({
7672
9014
  message: "logs: headers requires url"
7673
9015
  }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
7674
9016
  message: "logs: readHeaders requires url"
7675
- }).optional()
9017
+ }).or(z6.literal(false)).optional(),
9018
+ decisionRecords: z6.object({
9019
+ path: RepoRelativePathSchema
9020
+ }).strict().optional()
9021
+ });
9022
+ function decisionRecordsPathIssue(path, doctrineRoot) {
9023
+ const reason = outsideRepositoryReason(path);
9024
+ if (reason)
9025
+ return reason;
9026
+ const folder = normalizeSpecPath(path);
9027
+ if (folder === "" || folder === ".")
9028
+ return "must name a folder, not the repository root";
9029
+ const root = normalizeSpecPath(doctrineRoot ?? "aeg-root");
9030
+ if (folder === root || folder.startsWith(`${root}/`)) {
9031
+ return `must be outside the doctrine tree "${root}" — decision records belong to this repository, not to the doctrine it ships`;
9032
+ }
9033
+ return null;
9034
+ }
9035
+ var VinayaConfigSchema = VinayaConfigObjectSchema.superRefine((config, ctx) => {
9036
+ const path = config.decisionRecords?.path;
9037
+ if (path === undefined || outsideRepositoryReason(path))
9038
+ return;
9039
+ const issue = decisionRecordsPathIssue(path, config.proseGates?.doctrineRoot);
9040
+ if (issue)
9041
+ ctx.addIssue({ code: z6.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
7676
9042
  });
9043
+ var VinayaConfigShape = VinayaConfigObjectSchema.shape;
7677
9044
  var GLOBAL_VINAYA_HOME = join3(homedir(), ".vinaya");
7678
9045
  var GLOBAL_CONFIG_PATH = join3(GLOBAL_VINAYA_HOME, "config.json");
7679
9046
  var LOCAL_CONFIG_FILENAME = "vinaya.config.json";
@@ -7754,9 +9121,6 @@ function stripGlobalOnlyKeys(config, path) {
7754
9121
  }
7755
9122
  return result;
7756
9123
  }
7757
- function resolvePrincipalAllowlist(config) {
7758
- return config?.principals ?? PRINCIPAL_ALLOWLIST;
7759
- }
7760
9124
  function resolveReleaseActor(config) {
7761
9125
  return config?.releaseActor ?? DEFAULT_RELEASE_ACTOR;
7762
9126
  }
@@ -7780,13 +9144,19 @@ function resolveReviewPolicy(config) {
7780
9144
  if (!Number.isInteger(maxTaskMinutes) || maxTaskMinutes < 0) {
7781
9145
  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.`);
7782
9146
  }
9147
+ const readyPushTimeoutMinutes = raw.readyPushTimeoutMinutes ?? DEFAULT_READY_PUSH_TIMEOUT_MINUTES;
9148
+ if (!Number.isInteger(readyPushTimeoutMinutes) || readyPushTimeoutMinutes < 1) {
9149
+ throw new Error(`vinaya.config.json: reviewPolicy.readyPushTimeoutMinutes "${readyPushTimeoutMinutes}" is not a positive integer — fix the config, this never falls back to a default.`);
9150
+ }
7783
9151
  return {
7784
9152
  codeReviewThreshold,
7785
9153
  securityThreshold,
7786
9154
  maxRounds,
7787
- maxTaskMinutes
9155
+ maxTaskMinutes,
9156
+ readyPushTimeoutMinutes
7788
9157
  };
7789
9158
  }
9159
+ var emittedLocalOverrideWarnings = new Set;
7790
9160
  function resolveGateCutovers(config) {
7791
9161
  const raw = config?.gateCutovers;
7792
9162
  if (!raw)
@@ -7892,13 +9262,14 @@ function readTrustAnchorConfigAtRef(ref) {
7892
9262
  });
7893
9263
  return Buffer.from(raw, "utf-8").toString("base64");
7894
9264
  }
9265
+ var NO_TRUST_ANCHOR_REPO_MESSAGE = "could not resolve repo identity for the trust-anchor read";
7895
9266
  function ghFetchTrustAnchorConfig() {
7896
9267
  const probeRef = resolveCiTrustAnchorProbeRef();
7897
9268
  if (probeRef)
7898
9269
  return readTrustAnchorConfigAtRef(probeRef);
7899
9270
  const repo = trustAnchorRepo();
7900
9271
  if (!repo)
7901
- throw new Error("could not resolve repo identity for the trust-anchor read");
9272
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
7902
9273
  return execFileSync2("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
7903
9274
  encoding: "utf-8",
7904
9275
  stdio: ["ignore", "pipe", "pipe"]
@@ -7915,7 +9286,7 @@ async function ghFetchTrustAnchorConfigAsync() {
7915
9286
  }
7916
9287
  const repo = await trustAnchorRepoAsync();
7917
9288
  if (!repo)
7918
- throw new Error("could not resolve repo identity for the trust-anchor read");
9289
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
7919
9290
  const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4, killSignal: "SIGKILL" });
7920
9291
  return stdout;
7921
9292
  }
@@ -7941,6 +9312,47 @@ function loadTrustAnchorConfig(fetcher = ghFetchTrustAnchorConfig) {
7941
9312
  }
7942
9313
  return parseTrustAnchorContent(base64);
7943
9314
  }
9315
+ class PrincipalsUnresolvedError extends Error {
9316
+ kind;
9317
+ constructor(kind, message) {
9318
+ super(message);
9319
+ this.name = "PrincipalsUnresolvedError";
9320
+ this.kind = kind;
9321
+ }
9322
+ }
9323
+ var PRINCIPALS_FIX = 'add "principals": [...] to vinaya.config.json on the default branch';
9324
+ function fetchFailureReason(err) {
9325
+ const stderr = err?.stderr;
9326
+ const text = (typeof stderr === "string" ? stderr : stderr?.toString() ?? "").trim();
9327
+ return text.split(`
9328
+ `)[0]?.trim() || firstLine(err);
9329
+ }
9330
+ function principalsNotConfigured(why) {
9331
+ return new PrincipalsUnresolvedError("not-configured", `no Principal is configured (${why}) — ${PRINCIPALS_FIX}.`);
9332
+ }
9333
+ function resolveTrustedPrincipals(fetcher = ghFetchTrustAnchorConfig) {
9334
+ let content;
9335
+ try {
9336
+ content = fetcher();
9337
+ } catch (err) {
9338
+ if (err?.message === NO_TRUST_ANCHOR_REPO_MESSAGE) {
9339
+ throw principalsNotConfigured("no repository resolves for the read");
9340
+ }
9341
+ if (isMissingFileError(err))
9342
+ throw principalsNotConfigured("the default branch has no vinaya.config.json");
9343
+ throw new PrincipalsUnresolvedError("read-failed", `could not read "principals" from vinaya.config.json on the default branch: ${fetchFailureReason(err)}`);
9344
+ }
9345
+ const unusable = { why: "" };
9346
+ const config = parseTrustAnchorContent(content, (why) => {
9347
+ unusable.why = why;
9348
+ });
9349
+ if (config === null) {
9350
+ throw principalsNotConfigured(`vinaya.config.json on the default branch ${unusable.why ? `is unusable: ${unusable.why}` : "is empty"}`);
9351
+ }
9352
+ if (!config.principals)
9353
+ throw principalsNotConfigured('vinaya.config.json on the default branch sets no "principals"');
9354
+ return config.principals;
9355
+ }
7944
9356
  async function loadTrustAnchorConfigAsync(fetcher = ghFetchTrustAnchorConfigAsync, options = {}) {
7945
9357
  const warn = options.quiet ? () => {} : warnTrustAnchorFallback;
7946
9358
  let base64;
@@ -7980,12 +9392,67 @@ function loadConfig() {
7980
9392
  const path = configPath();
7981
9393
  if (!path)
7982
9394
  return null;
9395
+ let text;
7983
9396
  try {
7984
- const raw = JSON.parse(readFileSync2(path, "utf-8"));
7985
- return stripGlobalOnlyKeys(VinayaConfigSchema.parse(raw), path);
7986
- } catch {
9397
+ text = readFileSync2(path, "utf-8");
9398
+ } catch (err) {
9399
+ reportInvalidConfigOnce(path, `unreadable: ${err.message}`);
7987
9400
  return null;
7988
9401
  }
9402
+ let raw;
9403
+ try {
9404
+ raw = JSON.parse(text);
9405
+ } catch (err) {
9406
+ reportInvalidConfigOnce(path, `invalid JSON: ${err.message}`);
9407
+ return null;
9408
+ }
9409
+ const parsed = VinayaConfigSchema.safeParse(raw);
9410
+ if (!parsed.success) {
9411
+ reportInvalidConfigOnce(path, schemaIssueDetail(parsed.error));
9412
+ return null;
9413
+ }
9414
+ return stripGlobalOnlyKeys(parsed.data, path);
9415
+ }
9416
+ function schemaIssueDetail(error) {
9417
+ return error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
9418
+ }
9419
+ var emittedInvalidConfigReports = new Set;
9420
+ function reportInvalidConfigOnce(path, detail) {
9421
+ const key = `${path}
9422
+ ${detail}`;
9423
+ if (emittedInvalidConfigReports.has(key))
9424
+ return;
9425
+ emittedInvalidConfigReports.add(key);
9426
+ const message = `${path} is not a valid Vinaya configuration (${detail}) — falling back to built-in defaults.`;
9427
+ const checkName = process.env.VINAYA_CHECK_NAME;
9428
+ if (checkName) {
9429
+ emitCheckError({
9430
+ schema: CHECK_SCHEMA_VERSION,
9431
+ check: checkName,
9432
+ severity: "warning",
9433
+ message,
9434
+ agent_recovery_prompt: `Fix the failing keys in ${path} (${detail}) so the file parses and satisfies the configuration schema, then re-run.`,
9435
+ file: path
9436
+ });
9437
+ return;
9438
+ }
9439
+ console.error(`⚠ ${message}`);
9440
+ }
9441
+ function loadConfigChecked() {
9442
+ const path = configPath();
9443
+ if (!path)
9444
+ return { ok: true, config: null };
9445
+ let raw;
9446
+ try {
9447
+ raw = JSON.parse(readFileSync2(path, "utf-8"));
9448
+ } catch (err) {
9449
+ return { ok: false, path, error: `invalid JSON: ${err.message}` };
9450
+ }
9451
+ const parsed = VinayaConfigSchema.safeParse(raw);
9452
+ if (!parsed.success) {
9453
+ return { ok: false, path, error: schemaIssueDetail(parsed.error) };
9454
+ }
9455
+ return { ok: true, config: stripGlobalOnlyKeys(parsed.data, path) };
7989
9456
  }
7990
9457
  var TOKENS_COLLECT_TRUST_PATH = join3(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
7991
9458
 
@@ -8202,7 +9669,7 @@ function appendLoopLogLine(path, line) {
8202
9669
  import {
8203
9670
  closeSync as closeSync3,
8204
9671
  constants as fsConstants3,
8205
- lstatSync,
9672
+ lstatSync as lstatSync2,
8206
9673
  mkdirSync as mkdirSync3,
8207
9674
  openSync as openSync3,
8208
9675
  linkSync,
@@ -8373,7 +9840,7 @@ function removeQueueHead(path, cut) {
8373
9840
  function queueBucketSize(path) {
8374
9841
  let lstat;
8375
9842
  try {
8376
- lstat = lstatSync(path);
9843
+ lstat = lstatSync2(path);
8377
9844
  } catch (err) {
8378
9845
  if (!isEnoent(err))
8379
9846
  throw err;
@@ -8540,6 +10007,7 @@ async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeou
8540
10007
 
8541
10008
  // src/lib/log-sink.ts
8542
10009
  var OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
10010
+ var LOG_FOLDER_ONLY_ENV = "VINAYA_LOG_FOLDER_ONLY";
8543
10011
  function describeFolderFallback(reason) {
8544
10012
  if (reason.kind === "anchor-unreadable") {
8545
10013
  return `not delivering to the configured log server ${reason.intendedUrl} — the default branch's ` + "vinaya.config.json could not be read to confirm it (the trust-anchor read via `gh` was offline, " + "unauthenticated, or slower than its deadline); events are written to the local folder and can be " + "delivered later with `vinaya log send`";
@@ -8579,6 +10047,9 @@ function logsCredentialMissing(headers, env) {
8579
10047
  return false;
8580
10048
  }
8581
10049
  function resolveLogDestinationFrom(input) {
10050
+ if (input.localConfig?.logs === false || input.unattended && input.trustAnchorConfig?.logs === false) {
10051
+ return { kind: "none", reason: "logs: false disables Log recording" };
10052
+ }
8582
10053
  const spoolDir = input.env.VINAYA_LOG_SPOOL_DIR;
8583
10054
  if (spoolDir !== undefined && spoolDir.trim() !== "") {
8584
10055
  return { kind: "folder", folder: spoolDir };
@@ -8598,6 +10069,10 @@ function resolveLogDestinationFrom(input) {
8598
10069
  } else {
8599
10070
  effective = local;
8600
10071
  }
10072
+ if (input.folderOnly || input.env[LOG_FOLDER_ONLY_ENV] === "1") {
10073
+ const folder = effective && "folder" in effective && !isInsideRepo(effective.folder, input.repoRoot) ? effective.folder : input.defaultFolder;
10074
+ return { kind: "folder", folder };
10075
+ }
8601
10076
  if (hostFromEnv(input.env) === "ci") {
8602
10077
  if (effective && "url" in effective) {
8603
10078
  if (logsCredentialMissing(effective.headers, input.env)) {
@@ -8622,21 +10097,51 @@ function resolveLogDestinationFrom(input) {
8622
10097
  const folder = effective && "folder" in effective ? effective.folder : input.defaultFolder;
8623
10098
  return fallbackReason ? { kind: "folder", folder, fallbackReason } : { kind: "folder", folder };
8624
10099
  }
8625
- var processTrustAnchorByRepo = new Map;
10100
+ var LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS = 30000;
10101
+ var LOG_DESTINATION_ANCHOR_MAX_RETRIES = 5;
10102
+ function createTrustAnchorCache(read, now = Date.now, bounds = {
10103
+ retryIntervalMs: LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS,
10104
+ maxRetries: LOG_DESTINATION_ANCHOR_MAX_RETRIES
10105
+ }) {
10106
+ const slots = new Map;
10107
+ const start = (repoRoot, retries) => {
10108
+ const slot = {
10109
+ reading: Promise.resolve().then(read).catch(() => null),
10110
+ retries,
10111
+ missedAt: null
10112
+ };
10113
+ slots.set(repoRoot, slot);
10114
+ slot.reading.then((config) => {
10115
+ if (config === null)
10116
+ slot.missedAt = now();
10117
+ });
10118
+ return slot.reading;
10119
+ };
10120
+ return {
10121
+ get: (repoRoot) => {
10122
+ const slot = slots.get(repoRoot);
10123
+ if (slot === undefined)
10124
+ return start(repoRoot, 0);
10125
+ if (slot.missedAt === null)
10126
+ return slot.reading;
10127
+ if (slot.retries >= bounds.maxRetries || now() - slot.missedAt < bounds.retryIntervalMs)
10128
+ return slot.reading;
10129
+ return start(repoRoot, slot.retries + 1);
10130
+ },
10131
+ clear: () => slots.clear()
10132
+ };
10133
+ }
10134
+ var processTrustAnchorByRepo = createTrustAnchorCache(safeLoadTrustAnchorConfig);
8626
10135
  function processTrustAnchor(repoRoot) {
8627
- const cached = processTrustAnchorByRepo.get(repoRoot);
8628
- if (cached !== undefined)
8629
- return cached;
8630
- const reading = safeLoadTrustAnchorConfig();
8631
- processTrustAnchorByRepo.set(repoRoot, reading);
8632
- return reading;
10136
+ return processTrustAnchorByRepo.get(repoRoot);
8633
10137
  }
8634
- async function defaultResolveLogDestination(repo, env) {
10138
+ async function defaultResolveLogDestination(repo, env, folderOnly = false) {
8635
10139
  const localConfig = loadConfig();
8636
10140
  const unattended = isUnattendedProcess(process.env);
8637
10141
  const repoRoot = repoRootSync();
8638
10142
  return resolveLogDestinationFrom({
8639
10143
  localConfig,
10144
+ folderOnly,
8640
10145
  trustAnchorConfig: unattended ? await processTrustAnchor(repoRoot) : null,
8641
10146
  unattended,
8642
10147
  env,
@@ -8645,14 +10150,16 @@ async function defaultResolveLogDestination(repo, env) {
8645
10150
  });
8646
10151
  }
8647
10152
  function unresolvedLogDestination(env) {
10153
+ const loaded = loadConfig();
10154
+ if (loaded?.logs === false)
10155
+ return { kind: "none", reason: "logs: false disables Log recording" };
8648
10156
  if (hostFromEnv(env) === "ci") {
8649
10157
  return {
8650
10158
  kind: "none",
8651
10159
  reason: "the process ended before its log destination was resolved, and a CI job never records to a folder"
8652
10160
  };
8653
10161
  }
8654
- const loaded = loadConfig();
8655
- const localConfig = loaded?.logs?.url !== undefined ? { ...loaded, logs: undefined } : loaded;
10162
+ const localConfig = loaded?.logs && loaded.logs.url !== undefined ? { ...loaded, logs: undefined } : loaded;
8656
10163
  const unattended = isUnattendedProcess(process.env);
8657
10164
  const repoRoot = repoRootSync();
8658
10165
  const runtimeDir = process.env[RUNTIME_DIR_ENV_KEY] || resolveRuntimeDir({ repo: null, localConfig, trustAnchorConfig: null, unattended, repoRoot });
@@ -8874,6 +10381,7 @@ async function resolveHeadSha(cwd) {
8874
10381
  }
8875
10382
  function defaultDeps() {
8876
10383
  return {
10384
+ readConfig: loadConfig,
8877
10385
  outboxRoot: () => join6(GLOBAL_VINAYA_HOME, "outbox"),
8878
10386
  home: () => homedir3(),
8879
10387
  hostname: () => osHostname(),
@@ -9057,23 +10565,59 @@ function createLogSink(overrides = {}) {
9057
10565
  };
9058
10566
  let contextCache;
9059
10567
  let settledContext;
10568
+ let contextEnv = {};
10569
+ const resolveDestination = async (repo, env) => deps.readConfig()?.logs === false ? { kind: "none", reason: "logs: false disables Log recording" } : await deps.resolveLogDestination(repo, env, deps.folderOnly);
9060
10570
  const context = () => {
9061
10571
  if (contextCache === undefined) {
9062
10572
  const env = deps.env();
10573
+ contextEnv = env;
9063
10574
  contextCache = Promise.all([
9064
10575
  withDeadline(resolveRepoOnce(), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null),
9065
10576
  doctrine()
9066
10577
  ]).then(async ([resolved, doctrineValue]) => {
9067
10578
  const repo = resolved && isSafeRepoSegment3(resolved.owner) && isSafeRepoSegment3(resolved.repo) ? resolved : null;
9068
- settledContext = { repo, doctrine: doctrineValue, destination: await deps.resolveLogDestination(repo, env) };
10579
+ settledContext = { repo, doctrine: doctrineValue, destination: await resolveDestination(repo, env) };
10580
+ destinationRetryDueAt = deps.now().getTime() + LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS;
9069
10581
  return settledContext;
9070
10582
  });
9071
10583
  }
9072
10584
  return contextCache;
9073
10585
  };
10586
+ let destinationRetries = 0;
10587
+ let destinationRetryDueAt = 0;
10588
+ let destinationRetryInFlight = false;
10589
+ const retryDestinationIfDue = (ctx) => {
10590
+ if (ctx.destination.kind !== "folder" || ctx.destination.fallbackReason?.kind !== "anchor-unreadable")
10591
+ return;
10592
+ if (destinationRetryInFlight || destinationRetries >= LOG_DESTINATION_ANCHOR_MAX_RETRIES)
10593
+ return;
10594
+ if (deps.now().getTime() < destinationRetryDueAt)
10595
+ return;
10596
+ destinationRetryInFlight = true;
10597
+ destinationRetries++;
10598
+ const generation = contextCache;
10599
+ Promise.resolve().then(() => resolveDestination(ctx.repo, contextEnv)).then((destination) => {
10600
+ if (contextCache !== generation)
10601
+ return;
10602
+ if (destination.kind === "server") {
10603
+ settledContext = { ...ctx, destination };
10604
+ contextCache = Promise.resolve(settledContext);
10605
+ return;
10606
+ }
10607
+ if (destination.kind !== "folder" || destination.fallbackReason?.kind !== "anchor-unreadable") {
10608
+ destinationRetries = LOG_DESTINATION_ANCHOR_MAX_RETRIES;
10609
+ }
10610
+ }, () => {
10611
+ return;
10612
+ }).finally(() => {
10613
+ destinationRetryInFlight = false;
10614
+ destinationRetryDueAt = deps.now().getTime() + LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS;
10615
+ });
10616
+ };
9074
10617
  const resetContext = () => {
9075
10618
  contextCache = undefined;
9076
10619
  settledContext = undefined;
10620
+ destinationRetries = 0;
9077
10621
  };
9078
10622
  let drainChain = Promise.resolve();
9079
10623
  const pendingWrites = new Set;
@@ -9086,24 +10630,30 @@ function createLogSink(overrides = {}) {
9086
10630
  `);
9087
10631
  });
9088
10632
  };
9089
- const snapshot = () => {
10633
+ const snapshot = (attribution) => {
9090
10634
  const env = deps.env();
9091
10635
  return {
10636
+ attributed: attribution !== undefined,
9092
10637
  host: hostFromEnv(env),
9093
10638
  now: deps.now(),
9094
10639
  seq: seq++,
9095
10640
  envFields: {
9096
- role: env.VINAYA_ROLE,
10641
+ role: attribution?.role ?? env.VINAYA_ROLE,
9097
10642
  task: env.VINAYA_TASK,
9098
- round: env.VINAYA_ROUND,
10643
+ round: attribution ? String(attribution.round) : env.VINAYA_ROUND,
9099
10644
  pr: env.VINAYA_PR,
9100
10645
  run: env.VINAYA_RUN || runId,
9101
- attempt: env.VINAYA_ATTEMPT,
10646
+ attempt: attribution ? String(attribution.attempt) : env.VINAYA_ATTEMPT,
9102
10647
  parent: env.VINAYA_PARENT_EVENT,
9103
10648
  workRef: env.VINAYA_WORK_REF,
9104
10649
  flow: env.VINAYA_FLOW,
9105
10650
  flowVersion: env.VINAYA_FLOW_VERSION,
9106
10651
  runtime: env.VINAYA_RUNTIME,
10652
+ processId: env.VINAYA_PROCESS_ID,
10653
+ processVersion: env.VINAYA_PROCESS_VERSION,
10654
+ processDigest: env.VINAYA_PROCESS_DIGEST,
10655
+ runnerId: env.VINAYA_RUNNER_ID,
10656
+ runnerVersion: env.VINAYA_RUNNER_VERSION,
9107
10657
  source: env.VINAYA_SOURCE
9108
10658
  }
9109
10659
  };
@@ -9132,6 +10682,8 @@ function createLogSink(overrides = {}) {
9132
10682
  branchIssue,
9133
10683
  eventId: randomUUID2(),
9134
10684
  processId,
10685
+ revision: headSha,
10686
+ provenance: call.attributed ? "parent_attributed" : deps.provenance,
9135
10687
  inputVersions: deps.inputVersions()
9136
10688
  });
9137
10689
  const header = headSha === null ? built : { ...built, subject: { ...built.subject, sha: headSha } };
@@ -9156,11 +10708,14 @@ function createLogSink(overrides = {}) {
9156
10708
  appendLine(outboxPathFor({ outboxRoot: () => destination.folder }, repo, header.subject.issue), line, warnOnce);
9157
10709
  }
9158
10710
  };
9159
- function log(e) {
10711
+ function log(e, attribution) {
9160
10712
  try {
9161
- const call = snapshot();
10713
+ const call = snapshot(attribution);
9162
10714
  const write = async () => {
9163
10715
  const ctx = await context();
10716
+ try {
10717
+ retryDestinationIfDue(ctx);
10718
+ } catch {}
9164
10719
  if (ctx.destination.kind === "none") {
9165
10720
  writeEvent(e, call, ctx, null, null, true);
9166
10721
  return;
@@ -9184,9 +10739,13 @@ function createLogSink(overrides = {}) {
9184
10739
  function logSync(e, opts = {}) {
9185
10740
  try {
9186
10741
  const call = snapshot();
9187
- let ctx = settledContext;
10742
+ let ctx = deps.readConfig()?.logs === false ? {
10743
+ repo: null,
10744
+ doctrine: "unknown",
10745
+ destination: { kind: "none", reason: "logs: false disables Log recording" }
10746
+ } : settledContext;
9188
10747
  if (ctx === undefined) {
9189
- const destination = deps.unresolvedLogDestination(deps.env());
10748
+ const destination = deps.readConfig()?.logs === false ? { kind: "none", reason: "logs: false disables Log recording" } : deps.unresolvedLogDestination(deps.env());
9190
10749
  if (destination.kind === "folder" && !opts.quiet) {
9191
10750
  warnOnce(`vinaya: the process ended before its log destination was resolved — the event is written to ${destination.folder}; \`vinaya log send\` delivers it to a configured server later
9192
10751
  `);
@@ -9222,13 +10781,6 @@ function createLogSink(overrides = {}) {
9222
10781
  }
9223
10782
  var defaultSink = createLogSink();
9224
10783
 
9225
- // src/checks/contract.ts
9226
- var CHECK_SCHEMA_VERSION = 1;
9227
- function emitCheckError(error) {
9228
- process.stderr.write(`${JSON.stringify(error)}
9229
- `);
9230
- }
9231
-
9232
10784
  // src/checks/runner.ts
9233
10785
  var activeChecks = new Map;
9234
10786
 
@@ -9309,6 +10861,117 @@ function summaryLineIndex(maskedRegion) {
9309
10861
 
9310
10862
  // src/lib/forge-read.ts
9311
10863
  import { execFileSync as execFileSync4 } from "node:child_process";
10864
+
10865
+ // src/lib/forge-snapshot.ts
10866
+ import { existsSync as existsSync6, readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "node:fs";
10867
+ import { join as join7 } from "node:path";
10868
+ var FORGE_SNAPSHOT_DIR_ENV = "VINAYA_FORGE_SNAPSHOT_DIR";
10869
+ var PULL_FILE = "pull.json";
10870
+ var PULL_COMMENTS_FILE = "pull-comments.json";
10871
+ var ISSUE_FILE = "issue.json";
10872
+ var ISSUE_COMMENTS_FILE = "issue-comments.json";
10873
+ function forgeSnapshotDir(env = process.env) {
10874
+ if (env.GITHUB_ACTIONS !== "true")
10875
+ return null;
10876
+ const dir = env[FORGE_SNAPSHOT_DIR_ENV];
10877
+ return dir ? dir : null;
10878
+ }
10879
+
10880
+ class ForgeSnapshotIncompleteError extends Error {
10881
+ constructor(dir, file) {
10882
+ 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.`);
10883
+ this.name = "ForgeSnapshotIncompleteError";
10884
+ }
10885
+ }
10886
+
10887
+ class ForgeSnapshotIssueNotFoundError extends Error {
10888
+ constructor(issue) {
10889
+ super(`Issue #${issue} did not resolve (HTTP 404) when this run's forge snapshot was read.`);
10890
+ this.name = "ForgeSnapshotIssueNotFoundError";
10891
+ }
10892
+ }
10893
+ function readSnapshotFile(dir, file) {
10894
+ let text;
10895
+ try {
10896
+ text = readFileSync6(join7(dir, file), "utf8");
10897
+ } catch {
10898
+ throw new ForgeSnapshotIncompleteError(dir, file);
10899
+ }
10900
+ return JSON.parse(text);
10901
+ }
10902
+ function readComments(dir, file, number) {
10903
+ const parsed = readSnapshotFile(dir, file);
10904
+ if (parsed.number !== number)
10905
+ throw new ForgeSnapshotIncompleteError(dir, `${file} for #${number}`);
10906
+ return parsed.comments;
10907
+ }
10908
+ function snapshotPullRequest(number, env = process.env) {
10909
+ const dir = forgeSnapshotDir(env);
10910
+ if (dir === null)
10911
+ return null;
10912
+ const pull = readSnapshotFile(dir, PULL_FILE);
10913
+ return pull.number === number ? pull : null;
10914
+ }
10915
+ function snapshotIssue(number, env = process.env) {
10916
+ const dir = forgeSnapshotDir(env);
10917
+ if (dir === null)
10918
+ return null;
10919
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
10920
+ if (issue.number !== number)
10921
+ return null;
10922
+ if ("notFound" in issue)
10923
+ throw new ForgeSnapshotIssueNotFoundError(number);
10924
+ return issue;
10925
+ }
10926
+ function snapshotComments(number, env = process.env) {
10927
+ const dir = forgeSnapshotDir(env);
10928
+ if (dir === null)
10929
+ return null;
10930
+ if (snapshotPullRequest(number, env) !== null)
10931
+ return readComments(dir, PULL_COMMENTS_FILE, number);
10932
+ if (snapshotIssue(number, env) !== null)
10933
+ return readComments(dir, ISSUE_COMMENTS_FILE, number);
10934
+ return null;
10935
+ }
10936
+ function snapshotBody(number, env = process.env) {
10937
+ const pull = snapshotPullRequest(number, env);
10938
+ if (pull !== null)
10939
+ return pull.body;
10940
+ return snapshotIssue(number, env)?.body ?? null;
10941
+ }
10942
+ function incompleteForgeSnapshot(env = process.env) {
10943
+ const dir = forgeSnapshotDir(env);
10944
+ if (dir === null)
10945
+ return null;
10946
+ for (const file of [PULL_FILE, PULL_COMMENTS_FILE, ISSUE_FILE]) {
10947
+ if (!existsSync6(join7(dir, file)))
10948
+ return new ForgeSnapshotIncompleteError(dir, file).message;
10949
+ }
10950
+ try {
10951
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
10952
+ if (typeof issue.number === "number" && !("notFound" in issue) && !existsSync6(join7(dir, ISSUE_COMMENTS_FILE))) {
10953
+ return new ForgeSnapshotIncompleteError(dir, ISSUE_COMMENTS_FILE).message;
10954
+ }
10955
+ } catch (err) {
10956
+ return `the forge snapshot ${dir} has an unreadable ${ISSUE_FILE}: ${err.message}`;
10957
+ }
10958
+ return null;
10959
+ }
10960
+ function exitOnIncompleteForgeSnapshot(checkName, env = process.env) {
10961
+ const reason = incompleteForgeSnapshot(env);
10962
+ if (reason === null)
10963
+ return;
10964
+ emitCheckError({
10965
+ schema: CHECK_SCHEMA_VERSION,
10966
+ check: checkName,
10967
+ severity: "error",
10968
+ message: `${checkName}: ${reason}`,
10969
+ 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.`
10970
+ });
10971
+ process.exit(1);
10972
+ }
10973
+
10974
+ // src/lib/forge-read.ts
9312
10975
  var FORGE_READ_CEILING_BYTES = 64 * 1024 * 1024;
9313
10976
  var PAGE_SIZE = 100;
9314
10977
  var ghRunner = (args, maxBuffer) => execFileSync4("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer });
@@ -9331,7 +10994,7 @@ function isForgeReadOversize(err) {
9331
10994
  function isBufferOverflow(err) {
9332
10995
  return err?.code === "ENOBUFS";
9333
10996
  }
9334
- function run2(runner, args, subject, usedBytes) {
10997
+ function runBounded(runner, args, subject, usedBytes) {
9335
10998
  const remaining = FORGE_READ_CEILING_BYTES - usedBytes;
9336
10999
  let out;
9337
11000
  try {
@@ -9346,31 +11009,40 @@ function run2(runner, args, subject, usedBytes) {
9346
11009
  throw new ForgeReadOversizeError(subject, usedBytes + size);
9347
11010
  return out;
9348
11011
  }
9349
- function readIssueComments(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
9350
- const number = resolveNumber(issue, subjectLabel, runner);
9351
- const comments = [];
11012
+ function readRestCommentRows(number, subjectLabel = `Issue ${number}`, runner = ghRunner) {
11013
+ const rows = [];
9352
11014
  let used = 0;
9353
11015
  for (let page = 1;; page++) {
9354
- const out = run2(runner, ["api", `repos/{owner}/{repo}/issues/${number}/comments?per_page=${PAGE_SIZE}&page=${page}`], subjectLabel, used);
11016
+ const out = runBounded(runner, ["api", `repos/{owner}/{repo}/issues/${number}/comments?per_page=${PAGE_SIZE}&page=${page}`], subjectLabel, used);
9355
11017
  used += Buffer.byteLength(out, "utf8");
9356
- const rows = JSON.parse(out);
9357
- for (const r of rows) {
9358
- comments.push({
9359
- body: r.body ?? "",
9360
- url: r.html_url ?? "",
9361
- author: r.user?.login ? { login: r.user.login } : null
9362
- });
9363
- }
9364
- if (rows.length < PAGE_SIZE)
9365
- return comments;
11018
+ const pageRows = JSON.parse(out);
11019
+ rows.push(...pageRows);
11020
+ if (pageRows.length < PAGE_SIZE)
11021
+ return rows;
9366
11022
  }
9367
11023
  }
11024
+ function readIssueComments(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
11025
+ const number = resolveNumber(issue, subjectLabel, runner);
11026
+ const fromSnapshot = snapshotComments(number);
11027
+ if (fromSnapshot !== null)
11028
+ return fromSnapshot;
11029
+ return readRestCommentRows(number, subjectLabel, runner).map((r) => ({
11030
+ body: r.body ?? "",
11031
+ url: r.html_url ?? "",
11032
+ author: r.user?.login ? { login: r.user.login } : null
11033
+ }));
11034
+ }
9368
11035
  function readIssueBody(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
9369
- const out = run2(runner, ["issue", "view", String(issue), "--json", "body"], subjectLabel, 0);
11036
+ if (forgeSnapshotDir() !== null) {
11037
+ const fromSnapshot = snapshotBody(resolveNumber(issue, subjectLabel, runner));
11038
+ if (fromSnapshot !== null)
11039
+ return fromSnapshot;
11040
+ }
11041
+ const out = runBounded(runner, ["issue", "view", String(issue), "--json", "body"], subjectLabel, 0);
9370
11042
  return JSON.parse(out).body ?? "";
9371
11043
  }
9372
11044
  function readIssueFields(issue, fields, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
9373
- return JSON.parse(run2(runner, ["issue", "view", String(issue), "--json", fields], subjectLabel, 0));
11045
+ return JSON.parse(runBounded(runner, ["issue", "view", String(issue), "--json", fields], subjectLabel, 0));
9374
11046
  }
9375
11047
  function resolveNumber(issue, subjectLabel, runner) {
9376
11048
  if (typeof issue === "number")
@@ -9382,8 +11054,8 @@ function resolveNumber(issue, subjectLabel, runner) {
9382
11054
 
9383
11055
  // src/lib/brief-assembly.ts
9384
11056
  import { execFileSync as execFileSync7 } from "node:child_process";
9385
- import { existsSync as existsSync7, readFileSync as readFileSync7, readdirSync as readdirSync2 } from "node:fs";
9386
- import { join as join8 } from "node:path";
11057
+ import { existsSync as existsSync8, readFileSync as readFileSync8, readdirSync as readdirSync2 } from "node:fs";
11058
+ import { join as join9 } from "node:path";
9387
11059
 
9388
11060
  // ../../packages/sources/src/commands.ts
9389
11061
  var COMMANDS = [
@@ -9499,6 +11171,16 @@ var COMMANDS = [
9499
11171
  ],
9500
11172
  status: "shipped"
9501
11173
  },
11174
+ {
11175
+ name: "new adr",
11176
+ needs: [],
11177
+ description: "Write the next numbered decision record into the folder decisionRecords.path names",
11178
+ details: [
11179
+ "`vinaya new adr <title>` writes `<decisionRecords.path>/NNNN-<kebab-title>.md` from the shipped decision-record template (`vinaya doctrine --template decision-record`), with status Proposed and today's date, and adds a row for it to the folder's `README.md` index page, creating that page on the first record. Numbers start at `0001` and are one past the highest number any file in the folder or any row of the index carries, so a number is never reused, even after its file is removed.",
11180
+ "Refuses, naming the key, while `decisionRecords.path` is unset: decision records are opt-in. The same key switches on the `decision-record-citation` writing rule — see `decisionRecords.path` in the configuration reference."
11181
+ ],
11182
+ status: "shipped"
11183
+ },
9502
11184
  {
9503
11185
  name: "brief render",
9504
11186
  needs: ["forge", "default-branch"],
@@ -9517,9 +11199,7 @@ var COMMANDS = [
9517
11199
  name: "task dispatch",
9518
11200
  needs: ["forge", "operator-seat"],
9519
11201
  description: "Deprecated — render, pin, and post the brief on the Issue as the frozen original; start the developer",
9520
- flags: [
9521
- { flag: "--agent <claude|codex|gemini>", description: "Start the developer through dispatchRole once posted" }
9522
- ],
11202
+ flags: [{ flag: "--agent <claude|codex>", description: "Start the developer through dispatchRole once posted" }],
9523
11203
  details: [
9524
11204
  "Renders the brief from the Issue and the tree (the same assembly `brief render` uses) and posts it once as an Issue comment whose first line is `<!-- aeg:brief:v1 -->` and whose second line is `Brief hash: <sha256>` — the hash covers only the body below those two lines, so any reader recomputes it. Refuses outright, naming the existing comment's URL, when a `v1` comment already exists on the Issue — the brief is frozen by design, never overwritten or silently reissued.",
9525
11205
  "With `--agent`, starts the Developer through `dispatchRole` when `apps/cli/src/lib/dispatch.ts` exports it; otherwise prints the rendered brief and the manual dispatch instruction and exits `0` — a soft dependency, never a hard block.",
@@ -9544,7 +11224,11 @@ var COMMANDS = [
9544
11224
  description: "One command from a planned Issue to a reviewed pull request — exactly one developer started",
9545
11225
  flags: [
9546
11226
  {
9547
- flag: "--agent <claude|codex|gemini>",
11227
+ flag: "--runner <standalone|atta-engine>",
11228
+ description: "Override runner config for this invocation; absent uses config, whose default is standalone"
11229
+ },
11230
+ {
11231
+ flag: "--agent <claude|codex>",
9548
11232
  description: "Vendor for the developer and both reviewers this run dispatches"
9549
11233
  },
9550
11234
  {
@@ -9554,17 +11238,39 @@ var COMMANDS = [
9554
11238
  {
9555
11239
  flag: "--widen-surface <glob,...> --reason <text>",
9556
11240
  description: "Continue a pre-pull-request escalation whose Developer asked for `widen_surface`: supersede the frozen brief with the globs added to `## Surface`, record that as the escalation's resolution, grade the widened Issue through the write gate, then start the run"
11241
+ },
11242
+ {
11243
+ flag: "--rollback",
11244
+ description: "Run the terminate-and-restart procedure for this task: cancel its in-flight Engine run, reconcile every prepared and uncertain effect by its identity, then start a fresh standalone run from the same frozen brief. Refuses a task whose recorded runner is not `atta-engine`"
9557
11245
  }
9558
11246
  ],
9559
11247
  details: [
11248
+ "The atta-engine runner starts the workspace Engine script with Bun, streams its output and returns its exit code. A published install without the script prints one notice and falls back to standalone. Engine Log events use the local folder only; logs: false disables all Log destinations for both runners.",
11249
+ "A run's runner is recorded when it starts and never changes: switching `runner` in config changes only the runner of new runs, and a run recorded on `atta-engine` keeps routing to the Engine for `task status`, `task_resume` and `task_cancel`. A start on a pause another runner holds is refused with a typed reason naming the recorded runner and the requested one, and so is a start on another runner's Engine run that is still in flight with no pause held — halted or stopped short of completed or cancelled.",
11250
+ "`--rollback` ends the Engine run first: a held pause through the shared cancel `task_cancel` uses, which needs a Principal ruling newer than the pause as any cancel does; a run halted with no pause held has its started effects fenced; a run that already completed or was cancelled is refused, as is a driver still running with no pause held, which is never signalled; and the standalone run never starts while the Engine driver lives, a cancelled run's driver given a bounded wait to release its lock. Every started and uncertain effect is then reconciled by its identity: one the forge carries is recorded verified, one it does not carry is left for the restarted run to complete, and one the forge read cannot settle refuses the restart. Each rehearsal appends a record — task, recorded runner, action, reconciled effect identities, the restarted run's runner and terminal state — to `backend-rollback-rehearsals.jsonl` in the task's runtime directory, whether it completed, was refused or failed at a later step, and nothing removes it.",
9560
11251
  "`--widen-surface` is the Planner's one command for a widen-surface escalation, and refuses before any write when the held pause is not one (no pause, a pause with a pull request — whose continuation is the ruling on that pull request — or a round whose Developer asked for no `widen_surface`), when a driver is still alive for the task, when the escalation's resolution is already consumed (a replay — the Surface is never widened twice), or when the widened body fails the write gate, whose findings name the field to edit first. The escalation packet's permitted next actions name this command with the globs the Developer asked for, and `task_resume` refuses such an escalation naming it.",
9561
- "Composes `task brief`'s own preparation (`prepareTask`) with the watching driver (`runDriverLoop`, `dev-review-loop.ts`) — nothing else. Preparation starts no agent; the loop's own round 1 reads the frozen brief off the Issue and is the only place a developer is ever dispatched from a fresh task, so exactly one developer is started by construction.",
11252
+ "Prepares the frozen brief and resolves the task, branch and model once. The standalone runner then starts the watching driver (`runDriverLoop`, `dev-review-loop.ts`). Preparation starts no agent; the loop's own round 1 reads the frozen brief off the Issue and is the only place a developer is ever dispatched from a fresh task, so exactly one developer is started by construction.",
9562
11253
  "A brief already frozen on the Issue is reused, never re-posted — the second `task dispatch`/`task brief` call this composes around does not fail the whole run, it just skips straight to running the loop. A task whose Issue refuses preparation (a missing brief section, an unmet dispatch gate) is refused before any agent starts, with nothing posted.",
9563
11254
  "Refuses when the frozen brief's developer branch already has an open pull request AND a driver is still live for it — a driver that crashed or was killed leaves its PR behind, and this command is the one that revives it, in any state, pause held or not.",
9564
11255
  "issue-711 O4: a pause never ends this process — it keeps running and watches the pull request, continuing on its own once a newer Principal ruling appears (or, for an `'infrastructure'`/`'stale_driver'` pause, after a bounded backoff), with no `--resume` command needed for the ordinary case. Exit and printed summary distinguish a published pull request OR a watched pause's own genuine end — merged, closed, or an operator's own `--cancel` (exit `0` either way, the PR URL) — from the one pause this process can never watch (no pull request exists yet — exit `1`, with the working `vinaya task run` command for this task's own branch to continue by hand — `<tranche> <n>` for a tranche task, `--issue <n>` for a backlog one — never a `dev-review-loop --resume` line naming a pull-request number this pause does not have), a usage/argv error (exit `2`), and any other failure (exit `3`)."
9565
11256
  ],
9566
11257
  status: "shipped"
9567
11258
  },
11259
+ {
11260
+ name: "task switch",
11261
+ needs: ["forge"],
11262
+ description: "Change a task's agent or model by setting its Engine checkpoint aside, so the next `task run` is accepted",
11263
+ flags: [
11264
+ { flag: "--issue <n>", description: "Address the task by its Issue number instead of `<tranche> <n>`" },
11265
+ { flag: "--agent <claude|codex>", description: "Vendor the next `task run` of the task continues on" },
11266
+ { flag: "--model <model>", description: "Model the next `task run` is meant to use; absent, the vendor default" }
11267
+ ],
11268
+ details: [
11269
+ "Refuses, changing nothing, while a driver for the task is alive, naming its pid. Otherwise moves the task's Engine checkpoint (`checkpoints.sqlite` with its `-wal` and `-shm` files) into a timestamped `switched-*` folder of the task's run directory and never deletes it; the branch, its commits and its pull request are untouched, so the next `task run` with the new agent continues the same branch on a fresh checkpoint.",
11270
+ "Writes one driver-log line naming the from and to agent, the from and to model and the folder the checkpoint went to. On the standalone runner it changes nothing on disk and says that runner already continues a task on a new `--agent` by itself. `task run` and `run-engine --resume` still refuse an agent other than the checkpoint's, and their refusal names this command."
11271
+ ],
11272
+ status: "shipped"
11273
+ },
9568
11274
  {
9569
11275
  name: "task status",
9570
11276
  needs: ["forge"],
@@ -9719,6 +11425,22 @@ var COMMANDS = [
9719
11425
  ],
9720
11426
  status: "shipped"
9721
11427
  },
11428
+ {
11429
+ name: "pr snapshot",
11430
+ needs: ["forge"],
11431
+ description: "CI plumbing: write a run's forge snapshot of the pull request and its task Issue, read over REST",
11432
+ flags: [
11433
+ {
11434
+ flag: "--dir",
11435
+ description: "The snapshot directory; its `raw/` holds the REST pull request and comment pages the read step wrote"
11436
+ }
11437
+ ],
11438
+ details: [
11439
+ "Run by the generated workflows' read step, never by hand. Maps the REST pull request and its comments to the shape `gh pr view --json` prints, resolves the task Issue from the body's `Closes #N`, and reads that Issue and its comments over REST — never GraphQL.",
11440
+ "A check reads the snapshot only when `GITHUB_ACTIONS` is `true` and the step running it sets `VINAYA_FORGE_SNAPSHOT_DIR`; anywhere else every read goes to the forge as before. Exits 1, naming what it could not read and both token budgets, on a failed read; 2 on a usage error."
11441
+ ],
11442
+ status: "shipped"
11443
+ },
9722
11444
  {
9723
11445
  name: "issue create",
9724
11446
  needs: ["forge"],
@@ -9839,14 +11561,14 @@ var COMMANDS = [
9839
11561
  {
9840
11562
  name: "milestone close",
9841
11563
  needs: ["forge"],
9842
- description: "Close a tranche's Milestone after verifying every labeled Issue is actually attached",
11564
+ description: "Close a tranche's Milestone after verifying every labeled Issue is attached and every tranche it declares is complete",
9843
11565
  flags: [
9844
11566
  { flag: "--slug", description: "The tranche whose Milestone is being closed" },
9845
11567
  { flag: "--validate-only", description: "Run every gate and report PASS without closing the Milestone" },
9846
11568
  { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
9847
11569
  ],
9848
11570
  details: [
9849
- "Resolves the target Milestone the same legacy-or-intent-declared way Issue create auto-attach does, then refuses to close on any mismatch between the label's Issues and the Milestone's natively attached Issues — naming each unattached or foreign Issue and its repair path (`gh issue edit <n> --milestone <title>`, or `vinaya milestone adopt`) — before the PATCH ever reaches the forge."
11571
+ "Resolves the target Milestone the same legacy-or-intent-declared way Issue create auto-attach does, then refuses to close on any mismatch between the label's Issues and the Milestone's natively attached Issues — naming each unattached or foreign Issue and its repair path (`gh issue edit <n> --milestone <title>`, or `vinaya milestone adopt`) — before the PATCH ever reaches the forge. It also holds the Milestone open while a tranche its `### Tranche intents` section declares is not complete — naming each unfinished tranche and its lifecycle — or while that section carries no readable tranche line; a Milestone with no such section closes on attachment alone. `--validate-only` refuses with the same reasons."
9850
11572
  ],
9851
11573
  status: "shipped"
9852
11574
  },
@@ -10135,7 +11857,7 @@ var COMMANDS = [
10135
11857
  }
10136
11858
  ],
10137
11859
  details: [
10138
- "Refuses unless HEAD is the default branch, the working tree is clean, HEAD equals `origin/<default>` (after `git fetch origin`), HEAD's commit subject starts with `Chore(release): Version packages` (unless `--allow-any-commit`), and `npm whoami` exits `0` — each its own refusal naming the fix.",
11860
+ "Refuses unless HEAD is the default branch, the working tree is clean, HEAD equals `origin/<default>` (after `git fetch origin`), HEAD's commit subject starts with `Chore(release): Version packages` (unless `--allow-any-commit`), and `npm whoami` exits `0`. Before any plan step, including under `--dry-run`, every package in `.changeset/config.json` fixed groups must have an unpublished working-tree version. Exact-version registry queries refuse with every already-published package and version; workspace read failures and registry errors other than E404 also refuse with their reason. E404 for a missing package or version counts as unpublished.",
10139
11861
  "Then streams `bun install --frozen-lockfile`, `bun run build`, `bun run changeset:publish`, and `git push origin --tags` — a real push, so the repo's own generated pre-push hook sees it exactly as any other push would. After it, prints `npm view <pkg> version` for every tag now on HEAD, noting registry lag on `@attalabs/vinaya` (observed ~20 minutes) when it still shows the previous version.",
10140
11862
  'This is the one procedure named in `apps/cli/specs/self-hosting.md`, "How the published version is produced" — publishing itself stays manual and human-triggered; this command only removes the hand-typed four-step recipe.'
10141
11863
  ],
@@ -10144,11 +11866,11 @@ var COMMANDS = [
10144
11866
  {
10145
11867
  name: "dispatch",
10146
11868
  needs: ["operator-seat"],
10147
- description: "Start a role's headless agent session (claude/codex/gemini) with attribution set on its environment, recording the outcome through the Vinaya Log",
11869
+ description: "Start a role's headless agent session (claude/codex) with attribution set on its environment, recording the outcome through the Vinaya Log",
10148
11870
  flags: [
10149
11871
  {
10150
11872
  flag: "--agent",
10151
- description: "Vendor to start: `claude`, `codex`, or `gemini` (falls back to `dispatch.agent` in config)"
11873
+ description: "Vendor to start: `claude` or `codex` (falls back to `dispatch.agent` in config)"
10152
11874
  },
10153
11875
  { flag: "--prompt-file", description: "Path to the prompt text sent to the agent (never on argv)" },
10154
11876
  { flag: "--task", description: "This dispatch's task Issue number — mutually exclusive with `--pr`" },
@@ -10165,9 +11887,9 @@ var COMMANDS = [
10165
11887
  ],
10166
11888
  details: [
10167
11889
  "Sets `VINAYA_RUN_ID`/`VINAYA_ROLE`/`VINAYA_TASK`/`VINAYA_ROUND` on the child only — never on this process's own environment — and refuses by name, before any spawn attempt, when the named vendor binary is absent from `PATH` or present but not executable.",
10168
- "Records `dispatched` (with the prompt's sha256), `outcome_received` (duration, the vendor's own usage when its stdout prints a recognizable shape), or `dispatch_failed` (`timeout`, `crash`, or `refused`) through the Vinaya Log's one `dispatch` family writer, `dispatchRole`. A wall-time ceiling (`dispatch.timeoutMs` in config, default one hour) sends `SIGTERM` then, after a grace window, `SIGKILL`.",
11890
+ "Records `dispatched` (with the prompt's sha256), `outcome_received` (duration, the vendor's own usage when its stdout prints a recognizable shape), or `dispatch_failed` (`timeout`, `crash`, `refused`, or `usage_limit`) through the Vinaya Log's one `dispatch` family writer, `dispatchRole`. A wall-time ceiling (`dispatch.timeoutMs` in config, default one hour) sends `SIGTERM` then, after a grace window, `SIGKILL`.",
10169
11891
  "Runs no flush of its own after the dispatch returns: every log line `dispatchRole` emits reaches its configured `logs` destination live, as it is emitted, so there is nothing left to ship in a trailing step. `--task`/`--pr` are attribution only, and remain mutually exclusive.",
10170
- "A successful dispatch's `DispatchHandle` carries `resumeId` — the vendor's own session/thread identifier (claude/gemini: `session_id`; codex: `thread_id`), parsed from its stdout, `null` on any failure. Passing that value as `--resume <id>` on a later call swaps in that vendor's own resume invocation (`claude -p -r <id> ...`; `codex exec resume <id> ...`; `gemini ... --resume <id> ...`) in place of its first-dispatch args."
11892
+ "A successful dispatch's `DispatchHandle` carries `resumeId` — the vendor's own session/thread identifier (claude: `session_id`; codex: `thread_id`), parsed from its stdout, `null` on any failure. Passing that value as `--resume <id>` on a later call swaps in that vendor's own resume invocation (`claude -p -r <id> ...`; `codex exec resume <id> ...`) in place of its first-dispatch args."
10171
11893
  ],
10172
11894
  status: "shipped"
10173
11895
  },
@@ -10178,7 +11900,7 @@ var COMMANDS = [
10178
11900
  flags: [
10179
11901
  { flag: "--task <n>", description: "This task's Issue number — its frozen `aeg:brief:v1` comment is the brief" },
10180
11902
  {
10181
- flag: "--agent <claude|codex|gemini>",
11903
+ flag: "--agent <claude|codex>",
10182
11904
  description: "Vendor for every dispatch this loop makes (falls back to `dispatch.agent` in config)"
10183
11905
  },
10184
11906
  { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
@@ -10257,22 +11979,78 @@ function createForgeSource(config) {
10257
11979
  };
10258
11980
  }
10259
11981
  // ../../packages/sources/src/select-source.ts
10260
- import { z as z6 } from "zod";
10261
- var StateSourceConfigSchema = z6.discriminatedUnion("kind", [
10262
- z6.object({ kind: z6.literal("forge"), owner: z6.string(), repo: z6.string() }),
10263
- z6.object({ kind: z6.literal("file"), root: z6.string().optional() })
11982
+ import { z as z7 } from "zod";
11983
+ var StateSourceConfigSchema = z7.discriminatedUnion("kind", [
11984
+ z7.object({ kind: z7.literal("forge"), owner: z7.string(), repo: z7.string() }),
11985
+ z7.object({ kind: z7.literal("file"), root: z7.string().optional() })
10264
11986
  ]);
10265
11987
  // src/checks/edge-resolve.ts
11988
+ import { execFile as execFile6 } from "node:child_process";
11989
+ import { promisify as promisify6 } from "node:util";
11990
+
11991
+ // src/lib/github-rate-limit.ts
10266
11992
  import { execFileSync as execFileSync5 } from "node:child_process";
11993
+ var GITHUB_RATE_LIMIT_WORDING = /api rate limit (?:already )?exceeded|secondary rate limit|rate limit exceeded/i;
11994
+ var SECONDARY_RATE_LIMIT_WORDING = /secondary rate limit/i;
11995
+ function isGithubRateLimitError(text) {
11996
+ return GITHUB_RATE_LIMIT_WORDING.test(text);
11997
+ }
11998
+ function rateLimitBudget(errorText) {
11999
+ return errorText.trimStart().startsWith("GraphQL:") ? "GraphQL" : "REST";
12000
+ }
12001
+ var defaultReader = () => execFileSync5("gh", ["api", "rate_limit"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
12002
+ function readRateLimitReset(budget, read = defaultReader) {
12003
+ let parsed;
12004
+ try {
12005
+ parsed = JSON.parse(read());
12006
+ } catch {
12007
+ return null;
12008
+ }
12009
+ const resources = parsed.resources;
12010
+ const entry = resources?.[budget === "GraphQL" ? "graphql" : "core"];
12011
+ if (!entry || typeof entry.reset !== "number" || !Number.isFinite(entry.reset) || entry.reset <= 0)
12012
+ return null;
12013
+ if (typeof entry.remaining === "number" && entry.remaining > 0)
12014
+ return null;
12015
+ return entry.reset;
12016
+ }
12017
+ function formatResetUtc(epochSeconds) {
12018
+ const d = new Date(epochSeconds * 1000);
12019
+ const hh = String(d.getUTCHours()).padStart(2, "0");
12020
+ const mm = String(d.getUTCMinutes()).padStart(2, "0");
12021
+ return `${hh}:${mm} UTC`;
12022
+ }
12023
+ function rateLimitMessage(errorText, read = defaultReader) {
12024
+ const budget = rateLimitBudget(errorText);
12025
+ const reset = SECONDARY_RATE_LIMIT_WORDING.test(errorText) ? null : readRateLimitReset(budget, read);
12026
+ const when = reset === null ? "resets in a few minutes" : `resets at ${formatResetUtc(reset)}`;
12027
+ return `GitHub rate limit (${budget}), ${when}`;
12028
+ }
12029
+ function execErrorText(err) {
12030
+ const e = err;
12031
+ const stderr = e?.stderr === undefined || e.stderr === null ? "" : String(e.stderr);
12032
+ const message = typeof e?.message === "string" ? e.message : "";
12033
+ return stderr.trim() !== "" ? `${stderr}
12034
+ ${message}` : message;
12035
+ }
12036
+
12037
+ // src/checks/edge-resolve.ts
10267
12038
  var DIRECT_ISSUE_REF = /#(\d+)/;
10268
12039
  var issueCache = new Map;
12040
+ var execFileAsync6 = promisify6(execFile6);
12041
+ var ISSUE_NOT_FOUND = /could not resolve to an issue/i;
10269
12042
  function fetchIssueState(num, repo) {
10270
12043
  const key = `${repo.owner}/${repo.repo}#${num}`;
10271
- if (issueCache.has(key))
10272
- return issueCache.get(key) ?? null;
10273
- let out = null;
12044
+ const cached = issueCache.get(key);
12045
+ if (cached)
12046
+ return cached;
12047
+ const out = readIssueOnce(num, repo).then((first) => first.readFailed ? readIssueOnce(num, repo) : first);
12048
+ issueCache.set(key, out);
12049
+ return out;
12050
+ }
12051
+ async function readIssueOnce(num, repo) {
10274
12052
  try {
10275
- const raw = execFileSync5("gh", [
12053
+ const { stdout } = await execFileAsync6("gh", [
10276
12054
  "issue",
10277
12055
  "view",
10278
12056
  String(num),
@@ -10280,13 +12058,11 @@ function fetchIssueState(num, repo) {
10280
12058
  `${repo.owner}/${repo.repo}`,
10281
12059
  "--json",
10282
12060
  "state,stateReason,closedByPullRequestsReferences"
10283
- ], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
10284
- out = JSON.parse(raw);
10285
- } catch {
10286
- out = null;
12061
+ ], { encoding: "utf8" });
12062
+ return { json: JSON.parse(stdout), readFailed: false };
12063
+ } catch (err) {
12064
+ return { json: null, readFailed: !ISSUE_NOT_FOUND.test(execErrorText(err)) };
10287
12065
  }
10288
- issueCache.set(key, out);
10289
- return out;
10290
12066
  }
10291
12067
  var defaultResolveSiblingTranche = async (slug, repo) => {
10292
12068
  let tranche;
@@ -10303,7 +12079,7 @@ var defaultResolveSiblingTranche = async (slug, repo) => {
10303
12079
  };
10304
12080
  };
10305
12081
  var siblingTrancheCache = new Map;
10306
- function edgeFromIssueJson(num, json) {
12082
+ function edgeFromIssueJson(num, json, readFailed = false) {
10307
12083
  if (json === null) {
10308
12084
  return {
10309
12085
  issue: num,
@@ -10312,7 +12088,8 @@ function edgeFromIssueJson(num, json) {
10312
12088
  issueState: null,
10313
12089
  stateReason: null,
10314
12090
  closedByActor: null,
10315
- resolved: true
12091
+ resolved: true,
12092
+ ...readFailed ? { readFailed: true } : {}
10316
12093
  };
10317
12094
  }
10318
12095
  const state = json.state === "CLOSED" ? "closed" : json.state === "OPEN" ? "open" : null;
@@ -10345,7 +12122,8 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
10345
12122
  const direct = id.match(DIRECT_ISSUE_REF);
10346
12123
  if (direct) {
10347
12124
  const num = Number(direct[1]);
10348
- return edgeFromIssueJson(num, fetchIssueState(num, repo));
12125
+ const read = await fetchIssueState(num, repo);
12126
+ return edgeFromIssueJson(num, read.json, read.readFailed);
10349
12127
  }
10350
12128
  const qualified = splitSlugQualifiedEdge(id);
10351
12129
  if (qualified) {
@@ -10379,17 +12157,36 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
10379
12157
  resolved: false
10380
12158
  };
10381
12159
  }
12160
+ function dependsOnFactFromEdge(id, r) {
12161
+ return {
12162
+ id,
12163
+ issue: r.issue,
12164
+ merged: r.merged,
12165
+ resolved: r.resolved,
12166
+ issueState: r.issueState,
12167
+ stateReason: r.stateReason,
12168
+ closedByActor: r.closedByActor,
12169
+ ...r.readFailed ? { readFailed: true } : {}
12170
+ };
12171
+ }
10382
12172
 
10383
12173
  // src/commands/doctrine.ts
10384
12174
  import { execFileSync as execFileSync6 } from "node:child_process";
10385
- import { existsSync as existsSync6, readdirSync, readFileSync as readFileSync6 } from "node:fs";
10386
- import { dirname as dirname7, join as join7, sep as sep2 } from "node:path";
12175
+ import { existsSync as existsSync7, readdirSync, readFileSync as readFileSync7 } from "node:fs";
12176
+ import { dirname as dirname7, join as join8, sep as sep2 } from "node:path";
10387
12177
  import matter4 from "gray-matter";
10388
12178
 
10389
12179
  // ../../packages/aeg-core/src/docs/parse-doc.ts
10390
12180
  import matter2 from "gray-matter";
10391
12181
  // ../../packages/aeg-core/src/docs/surfaced-manifest.ts
10392
12182
  var NO_MODEL_BACKED_PATHS = new Set;
12183
+ // ../../packages/aeg-core/src/docs/published-prose.ts
12184
+ var ALLOWED_MECHANICS = rulesForGroup("published-prose")[0]?.exemptions ?? [];
12185
+ var PROSE_RULES = rulesForGroup("published-prose").map((rule) => ({
12186
+ id: rule.id,
12187
+ what: rule.message,
12188
+ pattern: rule.patterns.published
12189
+ }));
10393
12190
  // src/roles/contract.ts
10394
12191
  import matter3 from "gray-matter";
10395
12192
 
@@ -10411,22 +12208,22 @@ function gitToplevel(cwd) {
10411
12208
  function resolveDoctrineRootInfo(pkg = packageRoot(import.meta.url), cwd = process.cwd()) {
10412
12209
  const toplevel = gitToplevel(cwd);
10413
12210
  if (toplevel !== null) {
10414
- const treeRoot = join7(toplevel, "aeg-root");
10415
- if (existsSync6(join7(treeRoot, "roles")))
12211
+ const treeRoot = join8(toplevel, "aeg-root");
12212
+ if (existsSync7(join8(treeRoot, "roles")))
10416
12213
  return { root: treeRoot, source: "tree" };
10417
12214
  }
10418
12215
  const fromSource = !pkg.split(sep2).includes("node_modules");
10419
- const bundleRoot = fromSource ? join7(dirname7(dirname7(pkg)), "aeg-root") : join7(pkg, "aeg-root");
12216
+ const bundleRoot = fromSource ? join8(dirname7(dirname7(pkg)), "aeg-root") : join8(pkg, "aeg-root");
10420
12217
  return hasDoctrineEntry(bundleRoot) ? { root: bundleRoot, source: "bundle" } : null;
10421
12218
  }
10422
12219
  function hasDoctrineEntry(root) {
10423
- return existsSync6(join7(root, ...ENTRY_SEGMENTS));
12220
+ return existsSync7(join8(root, ...ENTRY_SEGMENTS));
10424
12221
  }
10425
12222
 
10426
12223
  // src/lib/brief-assembly.ts
10427
12224
  var PACKAGE_ROOT = packageRoot(import.meta.url);
10428
- var PACKAGED_TEMPLATE_PATH = join8(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
10429
- var TEMPLATE_PATH = existsSync7(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join8(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
12225
+ var PACKAGED_TEMPLATE_PATH = join9(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
12226
+ var TEMPLATE_PATH = existsSync8(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join9(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
10430
12227
  function git(args) {
10431
12228
  try {
10432
12229
  return execFileSync7("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
@@ -10449,13 +12246,23 @@ var INFORMATIONAL_DISPATCH_BLOCKER_CLASSES = new Set([
10449
12246
  "conflicts-with"
10450
12247
  ]);
10451
12248
 
12249
+ // src/lib/pre-push-failed-tests.ts
12250
+ var VERIFICATION_LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "yarn.lock", "pnpm-lock.yaml"];
12251
+ var VERIFICATION_INPUT_FILES = ["vinaya.config.json", "package.json", "bunfig.toml", ...VERIFICATION_LOCKFILES];
12252
+
12253
+ // src/lib/pre-push-ready-policy.ts
12254
+ var DEFERRAL_MARKER_TTL_MS = 30 * 60 * 1000;
12255
+ if (false)
12256
+ ;
12257
+
10452
12258
  // src/lib/pr-report-engine.ts
10453
- var execFileAsync6 = promisify6(execFile6);
12259
+ var execFileAsync7 = promisify7(execFile7);
10454
12260
  var BODY_READING_CHECK_NAMES = new Set(coreCheckRegistry().filter((spec) => {
10455
12261
  const decl = spec.env?.PR_BODY;
10456
12262
  return decl === true || typeof decl === "object" && decl !== null && "optional" in decl;
10457
12263
  }).map((spec) => spec.name));
10458
12264
  var FAILING_STATUSES = new Set(["fail", "error", "timeout"]);
12265
+ var GIT_MAX_BUFFER = 16 * 1024 * 1024;
10459
12266
  var NUL = String.fromCharCode(0);
10460
12267
  function extractAgentCommandLines(prBody) {
10461
12268
  const located = locateTestPlanSection(prBody);
@@ -10477,29 +12284,46 @@ function agentCommandText(line) {
10477
12284
  var AGENT_COMMAND_MAX_BUFFER_BYTES = 32 * 1024 * 1024;
10478
12285
  // src/lib/patch-id.ts
10479
12286
  import { execFileSync as execFileSync8 } from "node:child_process";
10480
- function patchIdAt(base, sha) {
10481
- try {
10482
- execFileSync8("git", ["fetch", "--quiet", "origin", sha], { stdio: ["ignore", "ignore", "ignore"] });
10483
- } catch {}
12287
+ var git2 = (args, options, input) => execFileSync8("git", [...args], {
12288
+ encoding: "utf8",
12289
+ maxBuffer: 64 * 1024 * 1024,
12290
+ ...options.cwd === undefined ? {} : { cwd: options.cwd },
12291
+ ...input === undefined ? { stdio: ["ignore", "pipe", "pipe"] } : { input, stdio: ["pipe", "pipe", "pipe"] }
12292
+ });
12293
+ function ownPatchAt(base, sha, options = {}) {
12294
+ for (const rev of [base, sha]) {
12295
+ try {
12296
+ options.fetch?.(rev);
12297
+ } catch {}
12298
+ }
10484
12299
  try {
10485
- const diff = execFileSync8("git", ["diff", `origin/${base}...${sha}`], {
10486
- encoding: "utf8",
10487
- maxBuffer: 64 * 1024 * 1024,
10488
- stdio: ["ignore", "pipe", "pipe"]
10489
- });
10490
- if (diff === "")
12300
+ const bases = git2(["merge-base", "--all", base, sha], options).split(`
12301
+ `).map((line) => line.trim()).filter(Boolean);
12302
+ if (bases.length !== 1)
10491
12303
  return null;
10492
- const out = execFileSync8("git", ["patch-id", "--stable"], {
10493
- input: diff,
10494
- encoding: "utf8",
10495
- stdio: ["pipe", "pipe", "pipe"]
10496
- }).trim();
10497
- const id = out.split(/\s+/)[0] ?? "";
12304
+ const diff = git2(["diff", "-U0", "--no-color", "--no-ext-diff", "--no-textconv", bases[0], sha], options);
12305
+ return diff === "" ? null : diff;
12306
+ } catch {
12307
+ return null;
12308
+ }
12309
+ }
12310
+ function ownPatchIdAt(base, sha, options = {}) {
12311
+ const diff = ownPatchAt(base, sha, options);
12312
+ if (diff === null)
12313
+ return null;
12314
+ try {
12315
+ const id = git2(["patch-id", "--stable"], options, diff).trim().split(/\s+/)[0] ?? "";
10498
12316
  return id === "" ? null : id;
10499
12317
  } catch {
10500
12318
  return null;
10501
12319
  }
10502
12320
  }
12321
+ function fetchFromOrigin(rev) {
12322
+ execFileSync8("git", ["fetch", "--quiet", "origin", rev], { stdio: ["ignore", "ignore", "ignore"] });
12323
+ }
12324
+ function patchIdAt(base, sha) {
12325
+ return ownPatchIdAt(`origin/${base}`, sha, { fetch: (rev) => rev === sha ? fetchFromOrigin(sha) : undefined });
12326
+ }
10503
12327
 
10504
12328
  // src/checks/evidence-fresh-logic.ts
10505
12329
  var HEAD_LINE = /^Head:\s*([0-9a-f]{7,40})\s*$/m;
@@ -10597,23 +12421,56 @@ function compareEvidenceBlock(resolved, resolvedHead, actualNumstat, expectedGro
10597
12421
  return errors.length > 0 ? { status: "fail", errors } : { status: "pass" };
10598
12422
  }
10599
12423
 
12424
+ // src/checks/principals-refusal.ts
12425
+ function principalsUnresolvedCheckError(check, err, severity) {
12426
+ const recovery = err.kind === "not-configured" ? `This repository names no Principal, so nobody's verdict, waiver or Issue close can be trusted. Ask a Principal to ${PRINCIPALS_FIX} (a list of GitHub logins), then re-run \`vinaya check ${check}\`.` : severity === "error" ? `The Principal list could not be read from the forge, so this trust decision cannot be made. Confirm \`gh auth status\` passes (in CI, that the job's token is not empty) and the forge is reachable, then re-run \`vinaya check ${check}\`.` : `The Principal list could not be read from the forge, so the part of this check that needs it was not evaluated — the rest still ran. Confirm \`gh auth status\` passes and the forge is reachable, then re-run \`vinaya check ${check}\`.`;
12427
+ return {
12428
+ schema: CHECK_SCHEMA_VERSION,
12429
+ check,
12430
+ severity,
12431
+ message: `${check}: ${err.message}`,
12432
+ agent_recovery_prompt: recovery
12433
+ };
12434
+ }
12435
+ function refuseUnresolvedPrincipals(check, err) {
12436
+ if (!(err instanceof PrincipalsUnresolvedError))
12437
+ throw err;
12438
+ emitCheckError(principalsUnresolvedCheckError(check, err, "error"));
12439
+ process.exit(1);
12440
+ }
12441
+ function warnOnUnreadPrincipals(check, err) {
12442
+ if (err instanceof PrincipalsUnresolvedError && err.kind === "read-failed") {
12443
+ emitCheckError(principalsUnresolvedCheckError(check, err, "warning"));
12444
+ return;
12445
+ }
12446
+ refuseUnresolvedPrincipals(check, err);
12447
+ }
12448
+
10600
12449
  // src/checks/bin/check-evidence-fresh.ts
10601
- var DEVELOPER_ROUND_MARKER = /<!--\s*aeg:developer:round-\d+\s*-->/i;
12450
+ var DEVELOPER_ROUND_MARKER2 = /<!--\s*aeg:developer:round-\d+\s*-->/i;
10602
12451
  function fetchHasPriorDeveloperRound(prNumber) {
12452
+ let allowlist;
10603
12453
  try {
10604
- const out = execFileSync9("gh", ["pr", "view", String(prNumber), "--json", "comments"], {
10605
- encoding: "utf8",
10606
- stdio: ["ignore", "pipe", "pipe"]
10607
- });
10608
- const parsed = JSON.parse(out);
10609
- const allowlist = resolvePrincipalAllowlist(loadTrustAnchorConfig());
10610
- return (parsed.comments ?? []).some((c) => DEVELOPER_ROUND_MARKER.test(c.body ?? "") && isPrincipal(c.author?.login ?? null, allowlist));
12454
+ allowlist = resolveTrustedPrincipals();
12455
+ } catch (err) {
12456
+ refuseUnresolvedPrincipals(CHECK_NAME, err);
12457
+ }
12458
+ try {
12459
+ const comments = snapshotComments(prNumber) ?? fetchPrComments(prNumber);
12460
+ return comments.some((c) => DEVELOPER_ROUND_MARKER2.test(c.body ?? "") && isPrincipal(c.author?.login ?? null, allowlist));
10611
12461
  } catch {
10612
12462
  return true;
10613
12463
  }
10614
12464
  }
12465
+ function fetchPrComments(prNumber) {
12466
+ const out = execFileSync9("gh", ["pr", "view", String(prNumber), "--json", "comments"], {
12467
+ encoding: "utf8",
12468
+ stdio: ["ignore", "pipe", "pipe"]
12469
+ });
12470
+ return JSON.parse(out).comments ?? [];
12471
+ }
10615
12472
  var CHECK_NAME = "evidence-fresh";
10616
- function git2(args) {
12473
+ function git3(args) {
10617
12474
  try {
10618
12475
  return execFileSync9("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
10619
12476
  } catch {
@@ -10644,13 +12501,17 @@ function resolveMergeBase(head) {
10644
12501
  const primary = process.env.BASE_SHA || "origin/main";
10645
12502
  const tried = primary === "main" ? [primary] : [primary, "main"];
10646
12503
  for (const ref of tried) {
10647
- const base = git2(["merge-base", ref, head]);
12504
+ const base = git3(["merge-base", ref, head]);
10648
12505
  if (base)
10649
12506
  return base;
10650
12507
  }
10651
12508
  throw new UnresolvableMergeBaseError2(tried);
10652
12509
  }
10653
12510
  function fetchPrRefs(prNumber) {
12511
+ const fromSnapshot = snapshotPullRequest(prNumber);
12512
+ if (fromSnapshot !== null) {
12513
+ return fromSnapshot.headRefOid && fromSnapshot.baseRefName ? { head: fromSnapshot.headRefOid, base: fromSnapshot.baseRefName } : null;
12514
+ }
10654
12515
  try {
10655
12516
  const out = execFileSync9("gh", ["pr", "view", String(prNumber), "--json", "headRefOid,baseRefName"], {
10656
12517
  encoding: "utf8",
@@ -10665,6 +12526,7 @@ function fetchPrRefs(prNumber) {
10665
12526
  }
10666
12527
  }
10667
12528
  function main() {
12529
+ exitOnIncompleteForgeSnapshot(CHECK_NAME);
10668
12530
  const body = process.env.PR_BODY ?? "";
10669
12531
  if (!body) {
10670
12532
  process.exit(0);