@attalabs/vinaya 0.39.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/README.md +9 -9
  2. package/aeg-root/contracts/developer-reviewer.md +2 -2
  3. package/aeg-root/contracts/planner-developer.md +5 -5
  4. package/aeg-root/enforcement.md +22 -22
  5. package/aeg-root/process.md +4 -4
  6. package/aeg-root/roles/archivist.md +1 -1
  7. package/aeg-root/roles/developer/reference.md +7 -1
  8. package/aeg-root/roles/developer.md +1 -1
  9. package/aeg-root/roles/planner/reference.md +18 -5
  10. package/aeg-root/roles/principal.md +1 -1
  11. package/aeg-root/roles/reviewer.md +3 -3
  12. package/aeg-root/roles/security.md +4 -4
  13. package/aeg-root/roles/tranche-archivist.md +2 -2
  14. package/aeg-root/skills/aeg/SKILL.md +1 -1
  15. package/aeg-root/state-machine.md +10 -15
  16. package/aeg-root/templates/brief-template.md +5 -2
  17. package/aeg-root/templates/decision-record-template.md +38 -0
  18. package/aeg-root/templates/issue-rationale-template.md +1 -1
  19. package/aeg-root/tranche-model.md +1 -1
  20. package/dist/checks/bin/check-body-bare-digits.js +1974 -354
  21. package/dist/checks/bin/check-branch-topology.js +1296 -243
  22. package/dist/checks/bin/check-brief-shape.js +2038 -460
  23. package/dist/checks/bin/check-changeset-coverage.js +2411 -564
  24. package/dist/checks/bin/check-ci-shard-coverage.js +12391 -15
  25. package/dist/checks/bin/check-closes-n.js +1296 -243
  26. package/dist/checks/bin/check-coherence.js +1914 -1155
  27. package/dist/checks/bin/check-dead-branch-push.js +1242 -230
  28. package/dist/checks/bin/check-dispatch-readiness.js +2222 -460
  29. package/dist/checks/bin/check-doc-claims.js +2233 -260
  30. package/dist/checks/bin/check-doc-coverage-push.js +2436 -550
  31. package/dist/checks/bin/check-doc-coverage.js +2434 -552
  32. package/dist/checks/bin/check-doctrine-no-procedures.js +1776 -353
  33. package/dist/checks/bin/check-doctrine-portability.js +2408 -561
  34. package/dist/checks/bin/check-evidence-fresh.js +2370 -508
  35. package/dist/checks/bin/check-exec-bits.js +2407 -560
  36. package/dist/checks/bin/check-first-push-dispatch.js +1984 -380
  37. package/dist/checks/bin/check-issue-assignment.js +712 -170
  38. package/dist/checks/bin/check-issue-milestone-attach.js +1233 -230
  39. package/dist/checks/bin/check-issue-objectives-numbering.js +1769 -346
  40. package/dist/checks/bin/check-issue-parts-coverage.js +1233 -230
  41. package/dist/checks/bin/check-issue-surface-globs.js +1926 -378
  42. package/dist/checks/bin/check-issue-title-grammar.js +1233 -230
  43. package/dist/checks/bin/check-issue-tranche-label.js +702 -170
  44. package/dist/checks/bin/check-main-branch-refusal.js +1245 -232
  45. package/dist/checks/bin/check-no-disk-state.js +1233 -230
  46. package/dist/checks/bin/check-pr-premise-reassert.js +1769 -346
  47. package/dist/checks/bin/check-pr-report-density.js +1233 -230
  48. package/dist/checks/bin/check-principal-test-plan-wait.js +2489 -259
  49. package/dist/checks/bin/check-quoted-command.js +2391 -544
  50. package/dist/checks/bin/check-reader-resolvable-prose.js +2437 -564
  51. package/dist/checks/bin/check-registry-gates.js +1380 -296
  52. package/dist/checks/bin/check-retired-vocabulary.js +2416 -550
  53. package/dist/checks/bin/check-review-gate.js +2073 -371
  54. package/dist/checks/bin/check-single-plan-pr.js +1297 -235
  55. package/dist/checks/bin/check-surface-scope.js +1531 -252
  56. package/dist/checks/bin/check-test-plan.js +2487 -258
  57. package/dist/checks/bin/check-token-collection-wired.js +1233 -230
  58. package/dist/checks/bin/check-workspace-escape.js +2408 -561
  59. package/dist/checks/bin/verify-coherence.js +597 -97
  60. package/dist/checks/bin/verify-dispatch.js +632 -152
  61. package/dist/checks/bin/verify-docs.js +642 -132
  62. package/dist/index.js +25948 -16630
  63. package/dist/lib/pre-push-cache-test-run.js +1813 -297
  64. package/dist/lib/pre-push-changed-files.js +65 -19
  65. package/dist/lib/pre-push-mode.js +466 -0
  66. package/dist/lib/pre-push-progress-dir.js +4205 -0
  67. package/dist/lib/pre-push-record-tests.js +446 -0
  68. package/dist/lib/pre-push-select-tests.js +2353 -632
  69. package/dist/lib/push-progress-observer.js +4213 -0
  70. package/package.json +22 -5
  71. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/anchored-region.ts +17 -3
  72. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-render.ts +73 -30
  73. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-validation.ts +3 -3
  74. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/coherence-checks.ts +2 -2
  75. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/local.ts +88 -5
  76. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/records.ts +34 -2
  77. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/assess-round.ts +26 -4
  78. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/fakes.ts +7 -2
  79. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/index.ts +7 -1
  80. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/types.ts +29 -3
  81. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dispatch-gate.ts +35 -18
  82. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/index.ts +1 -1
  83. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/published-prose.ts +70 -45
  84. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doctrine-portability.ts +6 -1
  85. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/entry-point.ts +27 -0
  86. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/gate-audience.ts +3 -5
  87. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/index.ts +96 -9
  88. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-assignment.ts +24 -54
  89. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-validation.ts +809 -106
  90. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/live-record.ts +179 -0
  91. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/envelope.ts +8 -2
  92. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/index.ts +1 -0
  93. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/narration.ts +2 -0
  94. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema-digest.ts +225 -0
  95. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema.ts +7 -1
  96. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/main-branch-refusal.ts +23 -1
  97. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/pr-report-density.ts +6 -4
  98. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/principals-config.ts +44 -0
  99. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/prose-rules.ts +532 -0
  100. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/protected-paths.ts +31 -0
  101. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/reader-resolvable-prose.ts +157 -80
  102. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/registry-checks.ts +8 -12
  103. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/retired-vocabulary.ts +53 -93
  104. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-gate.ts +46 -17
  105. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-input-manifest.ts +85 -1
  106. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-policy.ts +32 -13
  107. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/ruling-ordinal.ts +46 -0
  108. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/task-branch-identity.ts +2 -4
  109. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/test-plan-gate.ts +63 -8
  110. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/verdict-extraction.ts +24 -0
  111. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/waiver-label.ts +0 -1
  112. package/studio-standalone/apps/vinaya-studio/web/.next/BUILD_ID +1 -1
  113. package/studio-standalone/apps/vinaya-studio/web/.next/build-manifest.json +3 -3
  114. package/studio-standalone/apps/vinaya-studio/web/.next/prerender-manifest.json +3 -3
  115. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.html +1 -1
  116. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.rsc +1 -1
  117. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  118. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  119. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  120. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  121. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  122. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page/server-reference-manifest.json +2 -2
  123. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page.js.nft.json +1 -1
  124. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  125. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page/server-reference-manifest.json +2 -2
  126. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page.js.nft.json +1 -1
  127. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page_client-reference-manifest.js +1 -1
  128. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page/server-reference-manifest.json +2 -2
  129. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js +1 -1
  130. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js.nft.json +1 -1
  131. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page_client-reference-manifest.js +1 -1
  132. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page/server-reference-manifest.json +2 -2
  133. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js +1 -1
  134. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js.nft.json +1 -1
  135. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page_client-reference-manifest.js +1 -1
  136. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page/server-reference-manifest.json +2 -2
  137. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js +1 -1
  138. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js.nft.json +1 -1
  139. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page_client-reference-manifest.js +1 -1
  140. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page/server-reference-manifest.json +3 -3
  141. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js +1 -1
  142. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js.nft.json +1 -1
  143. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page_client-reference-manifest.js +1 -1
  144. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page/server-reference-manifest.json +2 -2
  145. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js +2 -2
  146. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js.nft.json +1 -1
  147. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page_client-reference-manifest.js +1 -1
  148. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page/server-reference-manifest.json +2 -2
  149. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js +1 -1
  150. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js.nft.json +1 -1
  151. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page_client-reference-manifest.js +1 -1
  152. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page/server-reference-manifest.json +2 -2
  153. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js +1 -1
  154. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js.nft.json +1 -1
  155. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page_client-reference-manifest.js +1 -1
  156. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/1q96_modules_@clerk_nextjs_dist_esm_app-router_client_keyless-creator-reader_0lom2js.js +1 -1
  157. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__08e39jo._.js +1 -1
  158. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0ls23oh._.js +1 -1
  159. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0sxadt2._.js +13 -0
  160. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1a3j3n1._.js +57 -0
  161. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__1ug9syi._.js → [root-of-the-server]__1d4eth3._.js} +1 -1
  162. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1gjqmhq._.js +1 -1
  163. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1snpgaw._.js +3 -3
  164. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1wc4-ip._.js +1 -1
  165. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_08onyya._.js +2 -2
  166. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_096f46i._.js +1 -1
  167. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0af2one._.js +1 -1
  168. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0e5tkdd._.js +1 -1
  169. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0kf2g72._.js +1 -1
  170. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0zf4d27._.js +3 -3
  171. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1-wo68i._.js +1 -1
  172. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1achbh9._.js +1 -1
  173. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/node_modules_@clerk_nextjs_dist_esm_app-router_server-actions_1x7vfhn.js +2 -2
  174. package/studio-standalone/apps/vinaya-studio/web/.next/server/middleware-build-manifest.js +3 -3
  175. package/studio-standalone/apps/vinaya-studio/web/.next/server/pages/500.html +1 -1
  176. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.js +1 -1
  177. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.json +4 -4
  178. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{33rszkngkuoko.js → 0x7u6si-ai179.js} +1 -1
  179. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{06_55xbp7rcbi.js → 2fu7mfsj4oima.js} +1 -1
  180. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{2brkwv169ygep.js → 34b4ruddunn3q.js} +1 -1
  181. package/studio-standalone/apps/vinaya-studio/web/package.json +2 -2
  182. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__04adkz-._.js +0 -57
  183. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__19jyp3m._.js +0 -13
  184. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → 2ZARxTwpuRew8-SvYsRdU}/_buildManifest.js +0 -0
  185. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → 2ZARxTwpuRew8-SvYsRdU}/_clientMiddlewareManifest.js +0 -0
  186. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{D3LiJNIq5FWZxen7CpOSJ → 2ZARxTwpuRew8-SvYsRdU}/_ssgManifest.js +0 -0
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/checks/bin/check-reader-resolvable-prose.ts
4
- import { existsSync as existsSync8, readdirSync as readdirSync3, readFileSync as readFileSync8, realpathSync as realpathSync4, statSync as statSync3 } from "node:fs";
5
- import { extname as extname2, isAbsolute as isAbsolute2, join as join10, relative as relative3, resolve as resolve3, sep as sep3 } from "node:path";
4
+ import { existsSync as existsSync9, readdirSync as readdirSync3, readFileSync as readFileSync9, realpathSync as realpathSync4, statSync as statSync3 } from "node:fs";
5
+ import { extname as extname2, isAbsolute as isAbsolute2, join as join11, relative as relative3, resolve as resolve3, sep as sep3 } from "node:path";
6
6
 
7
7
  // ../../packages/aeg-core/src/entry-point.ts
8
8
  import { realpathSync } from "node:fs";
@@ -43,7 +43,6 @@ var GATE_AUDIENCE = {
43
43
  };
44
44
  var NON_GATE_BINS = [
45
45
  "archive-task",
46
- "assign-task-issue",
47
46
  "dead-branch-audit",
48
47
  "eval-agent-compliance",
49
48
  "open-issue",
@@ -306,6 +305,25 @@ async function runAsync(args) {
306
305
  function ghApiGet(path) {
307
306
  return JSON.parse(run(["api", path]));
308
307
  }
308
+ var MAX_PER_PAGE = 100;
309
+ var MAX_PAGES = 100;
310
+ async function ghApiGetAllPagesAsync(pathWithoutPage, opts) {
311
+ const [base = pathWithoutPage, query = ""] = pathWithoutPage.split("?");
312
+ const params = new URLSearchParams(query);
313
+ params.set("per_page", String(MAX_PER_PAGE));
314
+ const all = [];
315
+ for (let page = 1;page <= MAX_PAGES; page++) {
316
+ params.set("page", String(page));
317
+ const args = ["api", `${base}?${params.toString()}`];
318
+ if (opts?.jq)
319
+ args.push("-q", opts.jq);
320
+ const batch = JSON.parse(await runAsync(args));
321
+ all.push(...batch);
322
+ if (batch.length < MAX_PER_PAGE)
323
+ return all;
324
+ }
325
+ throw new Error(`ghApiGetAllPagesAsync: "${pathWithoutPage}" did not terminate within ${MAX_PAGES} pages (${MAX_PAGES * MAX_PER_PAGE} items) — refusing to keep walking.`);
326
+ }
309
327
  function issueListByLabelArgs(owner, repo, label) {
310
328
  return [
311
329
  "issue",
@@ -717,6 +735,10 @@ function intentGoalForSlug(description, slug) {
717
735
  function matchesLegacyMilestone(milestones, slug) {
718
736
  return milestones.find((m) => m.title === slug) ?? null;
719
737
  }
738
+ var TRANCHE_SLUG_SHAPE = /^[a-z0-9]+(?:-[a-z0-9]+)*-v\d+$/;
739
+ function slugShapedTitles(milestones) {
740
+ return milestones.map((m) => m.title).filter((t) => TRANCHE_SLUG_SHAPE.test(t));
741
+ }
720
742
  function factsFromLegacyMilestone(milestone) {
721
743
  return {
722
744
  goal: milestone.description ?? "",
@@ -750,6 +772,105 @@ function findMilestoneForSlug(owner, repo, slug) {
750
772
  return resolveLegacyFacts(legacy, issues);
751
773
  return { goal: goalFromMilestones(milestones, slug), lifecycle: lifecycleFromIssues(issues) };
752
774
  }
775
+ function trancheSlugsFromLabels(labels) {
776
+ const slugs = [];
777
+ for (const l of labels) {
778
+ const slug = trancheSlugOf(l.name);
779
+ if (slug !== null)
780
+ slugs.push(slug);
781
+ }
782
+ return slugs;
783
+ }
784
+ async function indexTrancheMilestonesAsync(owner, repo, options = {}) {
785
+ const read = (fetch2) => options.retryFailedReads ? retryOnce(fetch2) : fetch2();
786
+ const [milestones, labels] = await Promise.all([
787
+ read(() => ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`)),
788
+ read(() => ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`))
789
+ ]);
790
+ const active = [];
791
+ const archived = [];
792
+ const facts = new Map;
793
+ const legacySlugs = new Set(slugShapedTitles(milestones));
794
+ const legacyMilestoneBySlug = new Map(milestones.filter((m) => legacySlugs.has(m.title)).map((m) => [m.title, m]));
795
+ const newPathSlugs = trancheSlugsFromLabels(labels).filter((slug) => !legacySlugs.has(slug));
796
+ const uniqueNewPathSlugs = [...new Set(newPathSlugs)];
797
+ const uniqueLegacySlugs = [...legacySlugs];
798
+ const [legacyIssuesBySlug, newPathIssuesBySlug] = await Promise.all([
799
+ Promise.all(uniqueLegacySlugs.map((slug) => read(() => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))))),
800
+ Promise.all(uniqueNewPathSlugs.map((slug) => read(() => ghIssueListByLabelAsync(owner, repo, trancheLabel(slug)))))
801
+ ]);
802
+ const issuesBySlug = new Map;
803
+ uniqueLegacySlugs.forEach((slug, i) => {
804
+ issuesBySlug.set(slug, legacyIssuesBySlug[i] ?? []);
805
+ });
806
+ uniqueNewPathSlugs.forEach((slug, i) => {
807
+ issuesBySlug.set(slug, newPathIssuesBySlug[i] ?? []);
808
+ });
809
+ uniqueLegacySlugs.forEach((slug, i) => {
810
+ const m = legacyMilestoneBySlug.get(slug);
811
+ if (!m)
812
+ return;
813
+ const ref = { slug, goal: m.description ?? "" };
814
+ const f = resolveLegacyFacts(m, legacyIssuesBySlug[i] ?? []);
815
+ if (f.lifecycle === "complete")
816
+ archived.push(ref);
817
+ else if (f.lifecycle === "active")
818
+ active.push(ref);
819
+ facts.set(slug, f);
820
+ });
821
+ uniqueNewPathSlugs.forEach((slug, i) => {
822
+ const issues = newPathIssuesBySlug[i] ?? [];
823
+ const lifecycle = lifecycleFromIssues(issues);
824
+ const goal = goalFromMilestones(milestones, slug);
825
+ const f = { goal, lifecycle };
826
+ facts.set(slug, f);
827
+ if (lifecycle === "active")
828
+ active.push({ slug, goal });
829
+ else if (lifecycle === "complete")
830
+ archived.push({ slug, goal });
831
+ });
832
+ return { active, archived, facts, legacySlugs, issuesBySlug };
833
+ }
834
+ async function retryOnce(fetch2) {
835
+ try {
836
+ return await fetch2();
837
+ } catch {
838
+ return fetch2();
839
+ }
840
+ }
841
+ async function indexTrancheMilestonesForSlugAsync(owner, repo, slug) {
842
+ const [milestones, labels, issues] = await Promise.all([
843
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/milestones?state=all&per_page=100`),
844
+ ghApiGetAllPagesAsync(`repos/${owner}/${repo}/labels?per_page=100`),
845
+ ghIssueListByLabelAsync(owner, repo, trancheLabel(slug))
846
+ ]);
847
+ const active = [];
848
+ const archived = [];
849
+ const facts = new Map;
850
+ const legacySlugs = new Set;
851
+ const legacyMilestone = slugShapedTitles(milestones).includes(slug) ? matchesLegacyMilestone(milestones, slug) : null;
852
+ if (legacyMilestone) {
853
+ legacySlugs.add(slug);
854
+ const ref = { slug, goal: legacyMilestone.description ?? "" };
855
+ const f = resolveLegacyFacts(legacyMilestone, issues);
856
+ if (f.lifecycle === "complete")
857
+ archived.push(ref);
858
+ else if (f.lifecycle === "active")
859
+ active.push(ref);
860
+ facts.set(slug, f);
861
+ } else if (trancheSlugsFromLabels(labels).includes(slug)) {
862
+ const lifecycle = lifecycleFromIssues(issues);
863
+ const goal = goalFromMilestones(milestones, slug);
864
+ facts.set(slug, { goal, lifecycle });
865
+ if (lifecycle === "active")
866
+ active.push({ slug, goal });
867
+ else if (lifecycle === "complete")
868
+ archived.push({ slug, goal });
869
+ }
870
+ const openLegacyTitles = new Set(slugShapedTitles(milestones.filter((m) => m.state === "open")));
871
+ const otherOpenLegacySlugs = [...openLegacyTitles].filter((t) => t !== slug);
872
+ return { active, archived, facts, legacySlugs, otherOpenLegacySlugs };
873
+ }
753
874
 
754
875
  // ../../packages/aeg-forge-state/src/derive-from-forge.ts
755
876
  function trancheFromIssues(slug, issues, known) {
@@ -1410,6 +1531,125 @@ var graphql2 = withDefaults3(request, {
1410
1531
  method: "POST",
1411
1532
  url: "/graphql"
1412
1533
  });
1534
+
1535
+ // ../../packages/aeg-forge-state/src/fetch-provenance.ts
1536
+ var PROVENANCE_PATTERN = /^###\s+AEG provenance\b/im;
1537
+ function provenanceMatchesIssue(text, issueNum) {
1538
+ if (!PROVENANCE_PATTERN.test(text))
1539
+ return false;
1540
+ const m = text.match(/^-\s*Issue:\s*#(\d+)/im);
1541
+ return m !== null && Number(m[1]) === issueNum;
1542
+ }
1543
+ function isPrCloser(closer) {
1544
+ return closer !== null && typeof closer.number === "number";
1545
+ }
1546
+ async function fetchProvenanceViaCrossReferences(issueNums, owner, repo, token) {
1547
+ const result = new Map;
1548
+ if (issueNums.length === 0)
1549
+ return result;
1550
+ const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
1551
+ const perIssue = issueNums.map((n) => `
1552
+ i_${n}: issue(number: ${n}) {
1553
+ timelineItems(first: 50, itemTypes: [CROSS_REFERENCED_EVENT]) {
1554
+ nodes {
1555
+ ... on CrossReferencedEvent {
1556
+ source {
1557
+ ... on PullRequest {
1558
+ number
1559
+ body
1560
+ comments(first: 50) { nodes { body } }
1561
+ }
1562
+ }
1563
+ }
1564
+ }
1565
+ }
1566
+ }`).join("");
1567
+ const query = `query ProvenanceCrossRef($owner: String!, $repo: String!) {
1568
+ repository(owner: $owner, name: $repo) {${perIssue}
1569
+ }
1570
+ }`;
1571
+ let response;
1572
+ try {
1573
+ response = await client(query, { owner, repo });
1574
+ } catch {
1575
+ return result;
1576
+ }
1577
+ if (!response.repository)
1578
+ return result;
1579
+ for (const n of issueNums) {
1580
+ const raw = response.repository[`i_${n}`];
1581
+ const nodes = raw?.timelineItems?.nodes ?? [];
1582
+ const found = nodes.some(({ source }) => {
1583
+ if (!source || typeof source.number !== "number")
1584
+ return false;
1585
+ const pr = source;
1586
+ if (provenanceMatchesIssue(pr.body ?? "", n))
1587
+ return true;
1588
+ return pr.comments.nodes.some((c) => provenanceMatchesIssue(c.body, n));
1589
+ });
1590
+ result.set(n, found);
1591
+ }
1592
+ return result;
1593
+ }
1594
+ async function fetchProvenance(issueNums, owner, repo, token) {
1595
+ const result = new Map;
1596
+ if (issueNums.length === 0)
1597
+ return result;
1598
+ const client = graphql2.defaults({ headers: { authorization: `bearer ${token}` } });
1599
+ const perIssue = issueNums.map((n) => `
1600
+ i_${n}: issue(number: ${n}) {
1601
+ timelineItems(last: 1, itemTypes: [CLOSED_EVENT]) {
1602
+ nodes {
1603
+ ... on ClosedEvent {
1604
+ closer {
1605
+ ... on PullRequest {
1606
+ number
1607
+ body
1608
+ comments(first: 50) {
1609
+ nodes { body }
1610
+ }
1611
+ }
1612
+ }
1613
+ }
1614
+ }
1615
+ }
1616
+ }`).join("");
1617
+ const query = `query Provenance($owner: String!, $repo: String!) {
1618
+ repository(owner: $owner, name: $repo) {${perIssue}
1619
+ }
1620
+ }`;
1621
+ let response;
1622
+ try {
1623
+ response = await client(query, { owner, repo });
1624
+ } catch {
1625
+ return result;
1626
+ }
1627
+ if (!response.repository)
1628
+ return result;
1629
+ const needsFallback = [];
1630
+ for (const n of issueNums) {
1631
+ const raw = response.repository[`i_${n}`];
1632
+ if (!raw) {
1633
+ result.set(n, false);
1634
+ continue;
1635
+ }
1636
+ const closer = raw.timelineItems?.nodes?.[0]?.closer;
1637
+ const c = closer ?? null;
1638
+ if (!isPrCloser(c)) {
1639
+ needsFallback.push(n);
1640
+ continue;
1641
+ }
1642
+ const bodyHas = PROVENANCE_PATTERN.test(c.body ?? "");
1643
+ const commentHas = c.comments.nodes.some((x) => PROVENANCE_PATTERN.test(x.body));
1644
+ result.set(n, bodyHas || commentHas);
1645
+ }
1646
+ if (needsFallback.length > 0) {
1647
+ const fallback = await fetchProvenanceViaCrossReferences(needsFallback, owner, repo, token);
1648
+ for (const [n, found] of fallback)
1649
+ result.set(n, found);
1650
+ }
1651
+ return result;
1652
+ }
1413
1653
  // ../../packages/aeg-forge-state/src/github-token.ts
1414
1654
  import { execFile as execFile2 } from "node:child_process";
1415
1655
  import { promisify as promisify2 } from "node:util";
@@ -1639,6 +1879,52 @@ function describeError(err) {
1639
1879
  return err;
1640
1880
  return "unknown error";
1641
1881
  }
1882
+ // ../../packages/aeg-forge-state/src/prior-tranche-archival.ts
1883
+ function defaultPriorTrancheArchivalDeps() {
1884
+ return {
1885
+ activeTranches: async (excludeSlug, repo) => {
1886
+ const index = await indexTrancheMilestonesAsync(repo.owner, repo.repo, { retryFailedReads: true });
1887
+ return index.active.filter((m) => m.slug !== excludeSlug).map((m) => {
1888
+ const issues = index.issuesBySlug?.get(m.slug);
1889
+ if (!issues)
1890
+ throw new Error(`the Milestone index holds no Issue list for tranche \`${m.slug}\``);
1891
+ return { slug: m.slug, issues };
1892
+ });
1893
+ }
1894
+ };
1895
+ }
1896
+ function reason(err) {
1897
+ return err instanceof Error ? err.message.split(`
1898
+ `)[0] ?? "failed" : String(err);
1899
+ }
1900
+ async function resolvePriorTrancheArchival(projects, excludeSlug, repo, deps = defaultPriorTrancheArchivalDeps()) {
1901
+ if (projects.length === 0)
1902
+ return { facts: [], infraFailure: null };
1903
+ let candidates;
1904
+ try {
1905
+ candidates = await deps.activeTranches(excludeSlug, repo);
1906
+ } catch (err) {
1907
+ return {
1908
+ facts: [],
1909
+ infraFailure: `severity:infra — could not read the active tranches (${reason(err)}); whether a prior tranche is archived is unknown.`
1910
+ };
1911
+ }
1912
+ const tasksBySlug = new Map(candidates.map((c) => [c.slug, tasksFromIssues(c.issues)]));
1913
+ const facts = [];
1914
+ for (const project of projects) {
1915
+ let found = null;
1916
+ for (const { slug, issues } of candidates) {
1917
+ if (!(tasksBySlug.get(slug) ?? []).some((t) => t.projects.includes(project)))
1918
+ continue;
1919
+ if (!issues.some((issue) => issue.state === "OPEN")) {
1920
+ found = { project, priorTrancheSlug: slug, archived: false };
1921
+ break;
1922
+ }
1923
+ }
1924
+ facts.push(found ?? { project, priorTrancheSlug: null, archived: false });
1925
+ }
1926
+ return { facts, infraFailure: null };
1927
+ }
1642
1928
  // ../../packages/aeg-forge-state/src/fetch-open-issues.ts
1643
1929
  async function fetchOpenIssuesByLabel(slugs, owner, repo, token) {
1644
1930
  const result = new Map;
@@ -1713,6 +1999,10 @@ function buildQuery(issueNumbers) {
1713
1999
  }
1714
2000
  }`;
1715
2001
  }
2002
+ // ../../packages/aeg-forge-state/src/list-issue-milestones.ts
2003
+ function issueMilestonesFromIssues(issues) {
2004
+ return issues.filter((i) => i.state === "OPEN").map((i) => ({ issue: i.number, milestoneTitle: i.milestone?.title ?? null }));
2005
+ }
1716
2006
  // ../../packages/aeg-forge-state/src/resolve-repo.ts
1717
2007
  import { execFile as execFile3 } from "node:child_process";
1718
2008
  import { promisify as promisify3 } from "node:util";
@@ -1775,7 +2065,8 @@ var ANCHOR_FIELDS = [
1775
2065
  "PREMISE",
1776
2066
  "TEST-PLAN",
1777
2067
  "EVIDENCE",
1778
- "BEYOND-SURFACE"
2068
+ "BEYOND-SURFACE",
2069
+ "LIVE"
1779
2070
  ];
1780
2071
  function anchoredRegionBounds(body, field) {
1781
2072
  const masked = maskCode(body);
@@ -1976,7 +2267,6 @@ var DERIVABLE_STATUSES = DERIVED_STATUSES.filter((s) => s !== "backlog");
1976
2267
  // ../../packages/aeg-core/src/waiver-label.ts
1977
2268
  var WAIVER_LABEL = label("waiver-docs");
1978
2269
  var WAIVER_LABEL_REVIEW = label("waiver-review");
1979
- var PRINCIPAL_ALLOWLIST = ["daniboomerang"];
1980
2270
  function isPrincipal(login, principalAllowlist) {
1981
2271
  if (login === null)
1982
2272
  return false;
@@ -1995,6 +2285,14 @@ var RULING_ORDINAL_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Ruling ordinal:\s*(\d+)(
1995
2285
  var BRIEF_HASH_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Brief hash:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
1996
2286
  var POLICY_DIGEST_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Policy digest:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
1997
2287
  var BASE_SHA_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Judged base:\s*([0-9a-f]{7,40})(?![A-Za-z0-9])/im;
2288
+ var MANIFEST_VERSION_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Manifest version:\s*(\d+)\s*$/im;
2289
+ var PAUSE_BOUND_RULING_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Pause-bound ruling:\s*(?:(\S+)\|(\S+)\|([0-9a-f]{64})|\(none\))\s*$/im;
2290
+ function extractPauseBoundRuling(comment) {
2291
+ const m = comment.match(PAUSE_BOUND_RULING_PATTERN);
2292
+ if (!m)
2293
+ return;
2294
+ return m[1] ? { rulingId: m[1], pauseId: m[2], contentDigest: m[3] } : null;
2295
+ }
1998
2296
  function firstFiveLines(comment) {
1999
2297
  return comment.split(`
2000
2298
  `).slice(0, 5).join(`
@@ -2088,6 +2386,8 @@ function extractVerdict(comments, valuePattern, missingLabel) {
2088
2386
  danglingNote: `the most recent ${missingLabel} verdict comment carries a VERDICT-shaped line outside the first-five-line read window`
2089
2387
  };
2090
2388
  }
2389
+ const versionMatch = latest.match(MANIFEST_VERSION_PATTERN);
2390
+ const pauseBoundRuling = extractPauseBoundRuling(latest);
2091
2391
  return {
2092
2392
  value: m[1].toUpperCase().replace(/[_-]/g, " "),
2093
2393
  headSha: extractHeadSha(latest),
@@ -2096,6 +2396,8 @@ function extractVerdict(comments, valuePattern, missingLabel) {
2096
2396
  briefHash: extractBriefHash(latest),
2097
2397
  policyDigest: extractPolicyDigest(latest),
2098
2398
  baseSha: extractBaseSha(latest),
2399
+ ...versionMatch ? { manifestVersion: Number.parseInt(versionMatch[1], 10) } : {},
2400
+ ...pauseBoundRuling === undefined ? {} : { pauseBoundRuling },
2099
2401
  findingSeverities: extractFindingSeverities(latest),
2100
2402
  danglingNote: null
2101
2403
  };
@@ -2106,6 +2408,16 @@ function extractCodeReviewVerdict(comments) {
2106
2408
  function extractSecurityReviewVerdict(comments) {
2107
2409
  return extractVerdict(comments, /^[ \t]*(?:\*{1,3}|_{1,3})?VERDICT:\s*(PASS|FAIL)(?![A-Za-z0-9])/im, "security-review");
2108
2410
  }
2411
+
2412
+ // ../../packages/aeg-core/src/review-status.ts
2413
+ var DEVELOPER_ROUND_MARKER = /<!--\s*aeg:developer:round-(\d+)\s*-->/i;
2414
+ function parseDeveloperRoundMarker(body) {
2415
+ const m = body.match(DEVELOPER_ROUND_MARKER);
2416
+ if (!m)
2417
+ return null;
2418
+ const n = Number(m[1]);
2419
+ return Number.isFinite(n) ? n : null;
2420
+ }
2109
2421
  // ../../packages/aeg-core/src/report-tokens.ts
2110
2422
  var DASH_LOOKALIKES = {
2111
2423
  "-": "‑",
@@ -2437,11 +2749,13 @@ var CODE_REVIEW_SEVERITY_ORDER = ["BLOCKER", "MAJOR", "MINOR"];
2437
2749
  var SECURITY_SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW"];
2438
2750
  var DEFAULT_MAX_ROUNDS = 3;
2439
2751
  var DEFAULT_MAX_TASK_MINUTES = 180;
2752
+ var DEFAULT_READY_PUSH_TIMEOUT_MINUTES = 20;
2440
2753
  var DEFAULT_REVIEW_POLICY = {
2441
2754
  codeReviewThreshold: "BLOCKER",
2442
2755
  securityThreshold: "HIGH",
2443
2756
  maxRounds: DEFAULT_MAX_ROUNDS,
2444
- maxTaskMinutes: DEFAULT_MAX_TASK_MINUTES
2757
+ maxTaskMinutes: DEFAULT_MAX_TASK_MINUTES,
2758
+ readyPushTimeoutMinutes: DEFAULT_READY_PUSH_TIMEOUT_MINUTES
2445
2759
  };
2446
2760
  var FILE_SHAPED_LOCATION = /\.[a-zA-Z0-9]{1,10}(:\d+)?\s*$/;
2447
2761
  var PROSE_LOCATION_PATTERNS = [/\bpr\s*body\b/i, /\bcomment\b/i];
@@ -2801,14 +3115,14 @@ function checkTestPlan(prBody) {
2801
3115
  const region = located.found ? located.section : prBody;
2802
3116
  if (TEST_PLAN_UNIT_TESTS_ONLY_RE.test(region))
2803
3117
  return { status: "pass", errors: [] };
2804
- if (/\*\*\[(?:agent|principal)\]\*\*/.test(region))
3118
+ if (/\*\*\[(?:agent|principal|live)\]\*\*/.test(region))
2805
3119
  return { status: "pass", errors: [] };
2806
3120
  if (located.found && extractFencedBlocks(region).length > 0)
2807
3121
  return { status: "pass", errors: [] };
2808
3122
  return {
2809
3123
  status: "fail",
2810
3124
  errors: [
2811
- "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."
3125
+ "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."
2812
3126
  ]
2813
3127
  };
2814
3128
  }
@@ -3430,6 +3744,375 @@ function checkPrReportDensity(prBody) {
3430
3744
  const results = [checkDecisionsDensity(prBody), checkScopeDensity(prBody)];
3431
3745
  return { errors: results.flatMap((r) => r.errors) };
3432
3746
  }
3747
+ // ../../packages/aeg-core/src/prose-rules.ts
3748
+ var RETIRED_GLOBAL_EXEMPTIONS = [
3749
+ "docs/decisions-legacy.md",
3750
+ "apps/herald-ai/docs/",
3751
+ "apps/vada-ai/docs/",
3752
+ "aeg-root/tranches/completed/",
3753
+ "packages/aeg-core/src/docs/published-prose",
3754
+ "packages/aeg-core/src/retired-vocabulary.test.ts",
3755
+ "packages/aeg-core/src/retired-vocabulary.ts",
3756
+ "/fixtures/",
3757
+ "/node_modules/",
3758
+ "/.next/",
3759
+ "/.turbo/"
3760
+ ];
3761
+ var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
3762
+ var TRANCHE_MODEL_FILE = "/tranche-model.md";
3763
+ var RETIRED_PATTERN_EXEMPTIONS = {
3764
+ [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
3765
+ [String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`]: [
3766
+ "docs-index.md",
3767
+ "apps/vada-ai/specs/legacy/README.md",
3768
+ "apps/vada-ai/specs/vada-product-spec.md",
3769
+ "apps/vada-ai/web/CLAUDE.md",
3770
+ "apps/vada-ai/CLAUDE.md"
3771
+ ],
3772
+ "decisions-legacy": [
3773
+ "packages/aeg-core/src/file-classify.ts",
3774
+ "packages/aeg-core/src/file-classify.test.ts",
3775
+ "packages/aeg-core/src/pr-tier.test.ts",
3776
+ "docs-index.md",
3777
+ ".claude/skills/database/SKILL.md",
3778
+ ".claude/skills/vada-architecture/SKILL.md",
3779
+ "apps/vada-ai/specs/vada-byok-principles.md",
3780
+ "apps/vada-ai/web/CLAUDE.md",
3781
+ "apps/vada-ai/CLAUDE.md"
3782
+ ],
3783
+ CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
3784
+ ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
3785
+ };
3786
+ var retiredPatterns = [
3787
+ String.raw`\bD-[0-9]{3}\b`,
3788
+ "D-(###|NNN|nnn|xxx)",
3789
+ "decision (entry|logged)",
3790
+ "decision-log entry",
3791
+ "decision log entry",
3792
+ "decision log(s|ged|ging)?([^a-z]|$)",
3793
+ "decision-log",
3794
+ "decision entr",
3795
+ "decisions? (are |is )?logged",
3796
+ "log entries",
3797
+ String.raw`(^|[^-_a-zA-Z0-9])decisions\.md`,
3798
+ "decisions-legacy",
3799
+ "CONTRADICTION",
3800
+ "assumes Tier 3",
3801
+ "Lock: ?YES",
3802
+ "Lock: ?NO",
3803
+ "lock approvals?",
3804
+ "approves locks",
3805
+ "Conforms to lock",
3806
+ "Challenges lock",
3807
+ "checkDecisionNumbersFresh",
3808
+ String.raw`roles/team-leader\.md`,
3809
+ String.raw`\(,`,
3810
+ String.raw`,\)`,
3811
+ String.raw`\(\.\)`,
3812
+ ...PLAN_ON_DISK_PATTERNS
3813
+ ];
3814
+ var published = [
3815
+ ["decision-id", "a decision id", /\bD-\d{3,}\b/],
3816
+ ["section-ref", "a section reference", /§/],
3817
+ ["forge-number", "a forge number", /#\d+/],
3818
+ ["retired-name", "the retired public name", /\bAEG\b/],
3819
+ ["tranche-slug", "a tranche slug", /\b[a-z][a-z0-9]*(?:-[a-z0-9]+)+-v\d+\b/],
3820
+ [
3821
+ "label-vocabulary",
3822
+ "forge label vocabulary",
3823
+ /(?:vinaya\/)?\b(?:tranche|iteration|tier|needs|waiver|project|aeg):(?![/\s]|$)/
3824
+ ],
3825
+ ["internal-path", "a repo-internal path", /\b(?:packages|apps|aeg-root|tools|scripts)\//],
3826
+ ["internal-path", "a repo-internal path", /\.(?:claude|husky|github)\//],
3827
+ [
3828
+ "internal-path",
3829
+ "a repo-internal file",
3830
+ /(?:^|[\s(`"'[])[\w.-]+(?:\/[\w.-]+)*\.(?:ts|tsx|js|jsx|mjs|cjs|sh|ya?ml|json|md)\b/
3831
+ ]
3832
+ ];
3833
+ var DEFAULT_PROSE_RULES = [
3834
+ {
3835
+ id: "forge-number",
3836
+ group: "reader-resolvable",
3837
+ scopes: ["ships", "reader-facing", "spec"],
3838
+ patterns: { prose: /#[0-9]{2,4}/g },
3839
+ flags: ["global"],
3840
+ message: "a forge number",
3841
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
3842
+ exemptions: []
3843
+ },
3844
+ {
3845
+ id: "tranche-slug",
3846
+ group: "reader-resolvable",
3847
+ scopes: ["ships", "reader-facing", "product", "spec"],
3848
+ patterns: { prose: /[a-z][a-z-]+-v[0-9]/g },
3849
+ flags: ["global"],
3850
+ message: "an internal tranche slug",
3851
+ severity: { ships: "warning", "reader-facing": "warning", product: "error", spec: "error" },
3852
+ exemptions: []
3853
+ },
3854
+ {
3855
+ id: "task-number",
3856
+ group: "reader-resolvable",
3857
+ scopes: ["spec"],
3858
+ patterns: { prose: /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi },
3859
+ flags: ["global", "ignore-case"],
3860
+ message: "a task number",
3861
+ severity: { spec: "error" },
3862
+ exemptions: []
3863
+ },
3864
+ {
3865
+ id: "source-comment-tranche-slug",
3866
+ group: "reader-resolvable",
3867
+ scopes: ["source-comment"],
3868
+ patterns: { comment: /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g },
3869
+ flags: ["global"],
3870
+ message: "a tranche-slug citation",
3871
+ severity: { "source-comment": "warning" },
3872
+ exemptions: []
3873
+ },
3874
+ {
3875
+ id: "source-comment-forge-number",
3876
+ group: "reader-resolvable",
3877
+ scopes: ["source-comment"],
3878
+ patterns: { comment: /#[0-9]{2,}/g },
3879
+ flags: ["global"],
3880
+ message: "a forge-number citation",
3881
+ severity: { "source-comment": "warning" },
3882
+ exemptions: []
3883
+ },
3884
+ {
3885
+ id: "legacy-batch-name",
3886
+ group: "reader-resolvable",
3887
+ scopes: ["ships", "reader-facing", "spec"],
3888
+ patterns: {},
3889
+ flags: ["built-in"],
3890
+ message: "an internal tranche slug",
3891
+ severity: { ships: "warning", "reader-facing": "warning", spec: "error" },
3892
+ exemptions: [],
3893
+ builtIn: true
3894
+ },
3895
+ {
3896
+ id: "coined-term",
3897
+ group: "reader-resolvable",
3898
+ scopes: ["ships", "reader-facing"],
3899
+ patterns: {},
3900
+ flags: ["built-in"],
3901
+ message: "uses coined term without defining it inline or linking the glossary",
3902
+ severity: { ships: "warning", "reader-facing": "warning" },
3903
+ exemptions: [],
3904
+ builtIn: true
3905
+ },
3906
+ ...retiredPatterns.map((pattern, index) => ({
3907
+ id: `retired-vocabulary-${index + 1}`,
3908
+ group: "retired-vocabulary",
3909
+ scopes: ["repository"],
3910
+ patterns: { repository: pattern },
3911
+ flags: [],
3912
+ message: "retired vocabulary",
3913
+ severity: { repository: "error" },
3914
+ exemptions: RETIRED_GLOBAL_EXEMPTIONS,
3915
+ patternExemptions: RETIRED_PATTERN_EXEMPTIONS
3916
+ })),
3917
+ ...published.map(([id, message, pattern]) => ({
3918
+ id,
3919
+ group: "published-prose",
3920
+ scopes: ["published"],
3921
+ patterns: { published: pattern },
3922
+ flags: [],
3923
+ message,
3924
+ severity: { published: "error" },
3925
+ exemptions: [".worktrees/task/<tranche>/<n>", "task/<tranche>/<n>", ".worktrees/"]
3926
+ }))
3927
+ ];
3928
+ var rulesForGroup = (group) => DEFAULT_PROSE_RULES.filter((rule) => rule.group === group);
3929
+ var RESOLVABLE_SCOPES = ["ships", "reader-facing", "product", "spec", "source-comment"];
3930
+ var RETIRED_SCOPES = ["repository"];
3931
+ var CONFIGURABLE_PROSE_SCOPES = [...RESOLVABLE_SCOPES, ...RETIRED_SCOPES];
3932
+ function groupOfScope(scope) {
3933
+ if (RESOLVABLE_SCOPES.includes(scope))
3934
+ return "reader-resolvable";
3935
+ if (RETIRED_SCOPES.includes(scope))
3936
+ return "retired-vocabulary";
3937
+ return;
3938
+ }
3939
+ var CONFIGURED_PROSE_FLAGS = ["i", "u"];
3940
+ var CONFIGURED_PATTERN_MAX_LENGTH = 200;
3941
+ var CONFIGURABLE_DEFAULT_RULES = DEFAULT_PROSE_RULES.filter((rule) => rule.group !== "published-prose");
3942
+ function allowedScopesFor(rule) {
3943
+ if (rule.builtIn)
3944
+ return rule.scopes;
3945
+ return rule.group === "retired-vocabulary" ? RETIRED_SCOPES : RESOLVABLE_SCOPES;
3946
+ }
3947
+ function normalizeRepoPath(entry) {
3948
+ let out = entry.replace(/\\/g, "/");
3949
+ while (out.startsWith("./"))
3950
+ out = out.slice(2);
3951
+ out = out.replace(/\/{2,}/g, "/");
3952
+ while (out.endsWith("/"))
3953
+ out = out.slice(0, -1);
3954
+ return out;
3955
+ }
3956
+ function isConfiguredExempt(path, exempt, repoRoot) {
3957
+ if (exempt.length === 0)
3958
+ return false;
3959
+ const root = repoRoot === undefined ? undefined : normalizeRepoPath(repoRoot);
3960
+ let rel = normalizeRepoPath(path);
3961
+ if (root && rel.startsWith(`${root}/`))
3962
+ rel = rel.slice(root.length + 1);
3963
+ return exempt.some((entry) => {
3964
+ const e = normalizeRepoPath(entry);
3965
+ return rel === e || rel.startsWith(`${e}/`);
3966
+ });
3967
+ }
3968
+ function ruleReads(set, rule, path) {
3969
+ return !isConfiguredExempt(path, set.exempt, set.repoRoot) && !isConfiguredExempt(path, rule.exempt, set.repoRoot);
3970
+ }
3971
+ var RESOLVABLE_RUN_ORDER = [
3972
+ "forge-number",
3973
+ "tranche-slug",
3974
+ "legacy-batch-name",
3975
+ "task-number",
3976
+ "source-comment-tranche-slug",
3977
+ "source-comment-forge-number",
3978
+ "coined-term"
3979
+ ];
3980
+ var REPORT_GROUPS = { "task-number": 2, "legacy-batch-name": 2 };
3981
+ function scopeDefaultSeverity(scope, sourceCommentSeverity) {
3982
+ if (scope === "source-comment")
3983
+ return sourceCommentSeverity ?? "warning";
3984
+ if (scope === "repository")
3985
+ return "error";
3986
+ return "warning";
3987
+ }
3988
+ function applySeverity(scopes, base, setting) {
3989
+ const out = {};
3990
+ for (const scope of scopes) {
3991
+ const configured = typeof setting === "string" ? setting : setting?.[scope];
3992
+ const value = configured ?? base[scope];
3993
+ if (value !== undefined)
3994
+ out[scope] = value;
3995
+ }
3996
+ return out;
3997
+ }
3998
+ function defaultPatternFor(rule) {
3999
+ const cache = new Map;
4000
+ return (scope) => {
4001
+ if (cache.has(scope))
4002
+ return cache.get(scope) ?? null;
4003
+ const own = rule.patterns[scope] ?? (scope === "source-comment" ? rule.patterns.comment : rule.patterns.prose) ?? Object.values(rule.patterns)[0];
4004
+ const compiled = own === undefined ? null : own instanceof RegExp ? own : new RegExp(own);
4005
+ cache.set(scope, compiled);
4006
+ return compiled;
4007
+ };
4008
+ }
4009
+ function customPatternFor(rule, global) {
4010
+ const cache = new Map;
4011
+ return (scope) => {
4012
+ if (cache.has(scope))
4013
+ return cache.get(scope) ?? null;
4014
+ const source = rule.patterns?.[scope] ?? rule.pattern;
4015
+ const compiled = source === undefined ? null : new RegExp(source, `${rule.flags ?? ""}${global ? "g" : ""}`);
4016
+ cache.set(scope, compiled);
4017
+ return compiled;
4018
+ };
4019
+ }
4020
+ function resolveProseRules(config = undefined, options = {}) {
4021
+ const rules = [];
4022
+ const defaults = config?.defaults ?? {};
4023
+ for (const rule of CONFIGURABLE_DEFAULT_RULES) {
4024
+ const override = defaults[rule.id];
4025
+ if (override === "off")
4026
+ continue;
4027
+ const group = rule.group;
4028
+ const scopes = override?.scopes ?? rule.scopes;
4029
+ const base = {};
4030
+ for (const scope of scopes) {
4031
+ base[scope] = scope === "source-comment" ? options.sourceCommentSeverity ?? rule.severity[scope] ?? "warning" : rule.severity[scope] ?? scopeDefaultSeverity(scope, options.sourceCommentSeverity);
4032
+ }
4033
+ rules.push({
4034
+ id: rule.id,
4035
+ group,
4036
+ custom: false,
4037
+ builtIn: rule.builtIn === true,
4038
+ scopes,
4039
+ message: rule.message,
4040
+ severity: applySeverity(scopes, base, override?.severity),
4041
+ exempt: override?.exempt ?? [],
4042
+ substringExempt: rule.exemptions,
4043
+ reportGroup: REPORT_GROUPS[rule.id],
4044
+ patternFor: defaultPatternFor(rule)
4045
+ });
4046
+ }
4047
+ for (const rule of config?.custom ?? []) {
4048
+ const group = groupOfScope(rule.scopes[0] ?? "") ?? "reader-resolvable";
4049
+ const base = {};
4050
+ for (const scope of rule.scopes)
4051
+ base[scope] = scopeDefaultSeverity(scope, options.sourceCommentSeverity);
4052
+ rules.push({
4053
+ id: rule.id,
4054
+ group,
4055
+ custom: true,
4056
+ builtIn: false,
4057
+ scopes: rule.scopes,
4058
+ message: rule.means,
4059
+ severity: applySeverity(rule.scopes, base, rule.severity),
4060
+ exempt: rule.exempt ?? [],
4061
+ substringExempt: [],
4062
+ patternFor: customPatternFor(rule, group === "reader-resolvable")
4063
+ });
4064
+ }
4065
+ if (options.decisionRecordsPath !== undefined)
4066
+ rules.push(decisionRecordCitationRule(options.decisionRecordsPath));
4067
+ const order = (rule) => {
4068
+ const at = RESOLVABLE_RUN_ORDER.indexOf(rule.id);
4069
+ return rule.custom || at === -1 ? RESOLVABLE_RUN_ORDER.length : at;
4070
+ };
4071
+ const resolvable = rules.filter((rule) => rule.group === "reader-resolvable");
4072
+ const sorted = resolvable.map((rule, index) => ({ rule, index })).sort((a, b) => order(a.rule) - order(b.rule) || a.index - b.index).map(({ rule }) => rule);
4073
+ return {
4074
+ rules: [...sorted, ...rules.filter((rule) => rule.group === "retired-vocabulary")],
4075
+ exempt: config?.exempt ?? [],
4076
+ repoRoot: options.repoRoot
4077
+ };
4078
+ }
4079
+ function rulesOfGroup(set, group) {
4080
+ return set.rules.filter((rule) => rule.group === group);
4081
+ }
4082
+ function rulesInScope(set, scope) {
4083
+ return set.rules.filter((rule) => rule.scopes.includes(scope));
4084
+ }
4085
+ var DEFAULT_PROSE_RULE_SET = resolveProseRules();
4086
+ var DECISION_RECORD_CITATION_ID = "decision-record-citation";
4087
+ var DECISION_RECORD_CITATION_SCOPES = ["ships", "product", "spec", "source-comment"];
4088
+ var DECISION_RECORD_CITATION_MESSAGE = "a decision-record number";
4089
+ function escapeRegExp(text) {
4090
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4091
+ }
4092
+ function decisionRecordCitationPattern(decisionRecordsPath) {
4093
+ const folder = escapeRegExp(normalizeRepoPath(decisionRecordsPath));
4094
+ return new RegExp(String.raw`\bADR[- ]?[0-9]+\b|(?<![A-Za-z0-9_-])${folder}/[0-9]+[A-Za-z0-9._-]*`, "g");
4095
+ }
4096
+ function decisionRecordCitationRule(decisionRecordsPath) {
4097
+ const folder = normalizeRepoPath(decisionRecordsPath);
4098
+ const pattern = decisionRecordCitationPattern(folder);
4099
+ const severity = {};
4100
+ for (const scope of DECISION_RECORD_CITATION_SCOPES)
4101
+ severity[scope] = "error";
4102
+ return {
4103
+ id: DECISION_RECORD_CITATION_ID,
4104
+ group: "reader-resolvable",
4105
+ custom: false,
4106
+ builtIn: false,
4107
+ scopes: DECISION_RECORD_CITATION_SCOPES,
4108
+ message: DECISION_RECORD_CITATION_MESSAGE,
4109
+ severity,
4110
+ exempt: [folder],
4111
+ substringExempt: [],
4112
+ patternFor: () => pattern
4113
+ };
4114
+ }
4115
+
3433
4116
  // ../../packages/aeg-core/src/reader-resolvable-prose.ts
3434
4117
  var PRODUCT_SLUG_SCOPE = [
3435
4118
  "apps/cli/src",
@@ -3441,8 +4124,8 @@ var PRODUCT_SLUG_SCOPE = [
3441
4124
  function isUnderOrEqual(path, prefix) {
3442
4125
  return path === prefix || path.startsWith(`${prefix}/`);
3443
4126
  }
3444
- function isProductScopeFile(path) {
3445
- return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
4127
+ function isProductScopeFile(path, productPaths) {
4128
+ return productPaths.some((prefix) => isUnderOrEqual(path, normalizeRepoPath(prefix)));
3446
4129
  }
3447
4130
  var SHIPS_PREFIX = "aeg-root/";
3448
4131
  function shipsArchivePrefix(shipsPrefix) {
@@ -3450,13 +4133,7 @@ function shipsArchivePrefix(shipsPrefix) {
3450
4133
  }
3451
4134
  var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
3452
4135
  function normalizeSpecPath(entry) {
3453
- let out = entry.replace(/\\/g, "/");
3454
- while (out.startsWith("./"))
3455
- out = out.slice(2);
3456
- out = out.replace(/\/{2,}/g, "/");
3457
- while (out.endsWith("/"))
3458
- out = out.slice(0, -1);
3459
- return out;
4136
+ return normalizeRepoPath(entry);
3460
4137
  }
3461
4138
  function isSpecFile2(path, specPaths) {
3462
4139
  if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
@@ -3468,7 +4145,7 @@ function isSpecFile2(path, specPaths) {
3468
4145
  function isClaudeMdFile(path) {
3469
4146
  return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
3470
4147
  }
3471
- function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
4148
+ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS, productPaths = PRODUCT_SLUG_SCOPE) {
3472
4149
  if (path.startsWith(shipsPrefix)) {
3473
4150
  return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
3474
4151
  }
@@ -3479,7 +4156,7 @@ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPr
3479
4156
  return "internal";
3480
4157
  if (isSpecFile2(path, specPaths))
3481
4158
  return "spec";
3482
- if (isProductScopeFile(path))
4159
+ if (isProductScopeFile(path, productPaths))
3483
4160
  return "product";
3484
4161
  return null;
3485
4162
  }
@@ -3504,9 +4181,16 @@ function lineAt(content, index) {
3504
4181
  }
3505
4182
  return line;
3506
4183
  }
3507
- var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
3508
- var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
3509
- var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
4184
+ var readerRules = rulesForGroup("reader-resolvable");
4185
+ var readerPattern = (id, scope = "prose") => {
4186
+ const pattern = readerRules.find((rule) => rule.id === id)?.patterns[scope];
4187
+ if (!(pattern instanceof RegExp))
4188
+ throw new Error(`default prose rule ${id} has no ${scope} pattern`);
4189
+ return pattern;
4190
+ };
4191
+ var FORGE_NUMBER_PATTERN = readerPattern("forge-number");
4192
+ var TRANCHE_SLUG_VN_PATTERN = readerPattern("tranche-slug");
4193
+ var TASK_NUMBER_PATTERN = readerPattern("task-number");
3510
4194
  function legacySlugPattern(legacySlugs) {
3511
4195
  if (legacySlugs.length === 0)
3512
4196
  return null;
@@ -3516,48 +4200,61 @@ function legacySlugPattern(legacySlugs) {
3516
4200
  function specGrandfatherPaths(specGrandfather) {
3517
4201
  return Array.isArray(specGrandfather) ? [...specGrandfather] : Object.keys(specGrandfather);
3518
4202
  }
3519
- function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4203
+ var REFERENCE_CLASSES = new Set(["ships", "reader-facing", "product", "spec"]);
4204
+ function referenceRulesFor(set, cls) {
4205
+ return rulesInScope(set, cls).filter((rule) => rule.group === "reader-resolvable" && rule.id !== "coined-term");
4206
+ }
4207
+ function citations(pattern, text, group) {
4208
+ const out = [];
4209
+ const re = pattern.global ? pattern : new RegExp(pattern.source, `${pattern.flags}g`);
4210
+ re.lastIndex = 0;
4211
+ let match = re.exec(text);
4212
+ while (match !== null) {
4213
+ if (match[0] === "") {
4214
+ re.lastIndex++;
4215
+ } else {
4216
+ const cited = group !== undefined ? match[group] ?? match[0] : match[0];
4217
+ out.push({ cited, index: match.index + match[0].indexOf(cited) });
4218
+ }
4219
+ match = re.exec(text);
4220
+ }
4221
+ re.lastIndex = 0;
4222
+ return out;
4223
+ }
4224
+ function customMessage(rule, cited) {
4225
+ return `${rule.id}: ${rule.message} ("${cited}")`;
4226
+ }
4227
+ function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS, options = {}) {
4228
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4229
+ const productPaths = options.productPaths ?? PRODUCT_SLUG_SCOPE;
3520
4230
  const findings = [];
3521
4231
  const legacyPattern = legacySlugPattern(legacySlugs);
3522
4232
  const grandfatheredWhole = new Set(Array.isArray(specGrandfather) ? specGrandfather : []);
3523
4233
  const limits = new Map(Array.isArray(specGrandfather) ? [] : Object.entries(specGrandfather));
3524
- const patterns = [
3525
- { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
3526
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
3527
- ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
3528
- ];
3529
- const productPatterns = [
3530
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
3531
- ];
3532
- const specPatterns = [
3533
- ...patterns,
3534
- { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
3535
- ];
3536
4234
  for (const file of files) {
3537
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
3538
- if (!cls || cls === "internal")
3539
- continue;
3540
- if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
4235
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths, productPaths);
4236
+ if (!cls || !REFERENCE_CLASSES.has(cls))
3541
4237
  continue;
3542
4238
  if (cls === "spec" && grandfatheredWhole.has(file.path))
3543
4239
  continue;
3544
- const blocking = cls === "product" || cls === "spec";
3545
4240
  const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
3546
- const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
3547
4241
  const fileFindings = [];
3548
- for (const { pattern, what, group } of patternsToRun) {
3549
- pattern.lastIndex = 0;
3550
- let match = pattern.exec(scrubbed);
3551
- while (match !== null) {
3552
- const cited = group !== undefined ? match[group] ?? match[0] : match[0];
3553
- const citedIndex = match.index + match[0].indexOf(cited);
4242
+ for (const rule of referenceRulesFor(set, cls)) {
4243
+ if (!ruleReads(set, rule, file.path))
4244
+ continue;
4245
+ const pattern = !rule.custom && rule.id === "legacy-batch-name" ? legacyPattern : rule.patternFor(cls);
4246
+ if (!pattern)
4247
+ continue;
4248
+ const blocking = rule.severity[cls] === "error";
4249
+ const what = cls === "product" ? `${rule.message} in product code` : rule.message;
4250
+ for (const { cited, index } of citations(pattern, scrubbed, rule.custom ? undefined : rule.reportGroup)) {
3554
4251
  fileFindings.push({
3555
4252
  file: file.path,
3556
- line: lineAt(scrubbed, citedIndex),
3557
- message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
3558
- blocking
4253
+ line: lineAt(scrubbed, index),
4254
+ message: rule.custom ? customMessage(rule, cited) : `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4255
+ blocking,
4256
+ rule: rule.id
3559
4257
  });
3560
- match = pattern.exec(scrubbed);
3561
4258
  }
3562
4259
  }
3563
4260
  const limit = cls === "spec" ? limits.get(file.path) : undefined;
@@ -3598,11 +4295,17 @@ function definesOrLinksGlossary(content, term) {
3598
4295
  return true;
3599
4296
  return /docs\/glossary|glossary\.md/i.test(content);
3600
4297
  }
3601
- function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
4298
+ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, options = {}) {
3602
4299
  const findings = [];
4300
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4301
+ const rule = set.rules.find((r) => !r.custom && r.id === "coined-term");
4302
+ if (!rule)
4303
+ return findings;
3603
4304
  for (const file of files) {
3604
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3605
- if (!cls || !SWEPT_CLASSES.has(cls))
4305
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, DEFAULT_SPEC_PATHS, options.productPaths);
4306
+ if (!cls || !SWEPT_CLASSES.has(cls) || !rule.scopes.includes(cls))
4307
+ continue;
4308
+ if (!ruleReads(set, rule, file.path))
3606
4309
  continue;
3607
4310
  const scrubbed = stripNonProse(file.path, file.content);
3608
4311
  for (const term of glossaryTerms) {
@@ -3615,14 +4318,15 @@ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, read
3615
4318
  file: file.path,
3616
4319
  line,
3617
4320
  message: `uses coined term "${term}" without defining it inline or linking the glossary`,
3618
- blocking: false
4321
+ blocking: rule.severity[cls] === "error",
4322
+ rule: rule.id
3619
4323
  });
3620
4324
  }
3621
4325
  }
3622
4326
  return findings;
3623
4327
  }
3624
- var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
3625
- var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
4328
+ var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = readerPattern("source-comment-tranche-slug", "comment");
4329
+ var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = readerPattern("source-comment-forge-number", "comment");
3626
4330
  function extractComments(path, content) {
3627
4331
  if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
3628
4332
  return content.replace(/[^\n]/g, "");
@@ -3719,39 +4423,40 @@ function extractComments(path, content) {
3719
4423
  }
3720
4424
  return out;
3721
4425
  }
3722
- function checkSourceComments(files, allowlist = []) {
4426
+ function checkSourceComments(files, allowlist = [], options = {}) {
3723
4427
  const findings = [];
3724
4428
  const allowed = new Set(allowlist);
3725
- const patterns = [
3726
- { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
3727
- { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
3728
- ];
4429
+ const set = options.rules ?? DEFAULT_PROSE_RULE_SET;
4430
+ const rules = rulesInScope(set, "source-comment").filter((rule) => rule.group === "reader-resolvable");
3729
4431
  for (const file of files) {
3730
4432
  if (!file.path.endsWith(".ts"))
3731
4433
  continue;
3732
4434
  if (allowed.has(file.path))
3733
4435
  continue;
3734
4436
  const comments = extractComments(file.path, file.content);
3735
- for (const { pattern, what } of patterns) {
3736
- pattern.lastIndex = 0;
3737
- let match = pattern.exec(comments);
3738
- while (match !== null) {
3739
- findings.push({
4437
+ for (const rule of rules) {
4438
+ if (!ruleReads(set, rule, file.path))
4439
+ continue;
4440
+ const pattern = rule.patternFor("source-comment");
4441
+ if (!pattern)
4442
+ continue;
4443
+ for (const { cited, index } of citations(pattern, comments)) {
4444
+ findings.push({
3740
4445
  file: file.path,
3741
- line: lineAt(comments, match.index),
3742
- message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
3743
- blocking: false
4446
+ line: lineAt(comments, index),
4447
+ message: rule.custom ? customMessage(rule, cited) : `comment cites ${rule.message} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4448
+ blocking: rule.severity["source-comment"] === "error",
4449
+ rule: rule.id
3744
4450
  });
3745
- match = pattern.exec(comments);
3746
4451
  }
3747
4452
  }
3748
4453
  }
3749
4454
  return findings;
3750
4455
  }
3751
- function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4456
+ function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS, options = {}) {
3752
4457
  return [
3753
- ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
3754
- ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
4458
+ ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths, options),
4459
+ ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix, options)
3755
4460
  ];
3756
4461
  }
3757
4462
  function parseGlossaryTerms(glossaryContent) {
@@ -3954,6 +4659,17 @@ function checkDocClaims(files, fileReader) {
3954
4659
  };
3955
4660
  }
3956
4661
 
4662
+ // ../../packages/aeg-core/src/protected-paths.ts
4663
+ import { posix as posixPath } from "node:path";
4664
+ var PROTECTED_ADMIN_PATHS = ["vinaya.config.json", ".vinaya/doc-owners", ".github/", "aeg-root/"];
4665
+ function normalizeTouchedPath(path) {
4666
+ return posixPath.resolve("/", path.replace(/\\/g, "/")).replace(/^\/+/, "");
4667
+ }
4668
+ function isProtectedAdminPath(path) {
4669
+ const normalized = normalizeTouchedPath(path);
4670
+ return PROTECTED_ADMIN_PATHS.some((prefix) => normalized === prefix || normalized.startsWith(prefix));
4671
+ }
4672
+
3957
4673
  // ../../packages/aeg-core/src/issue-validation.ts
3958
4674
  function hasRationaleField(body, labelPattern) {
3959
4675
  const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
@@ -4073,13 +4789,20 @@ function globCoversPath(glob, path) {
4073
4789
  return !p.includes("/");
4074
4790
  return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
4075
4791
  }
4792
+ function surfaceEntryResolves(entry, resolvesToFile, pinnedFiles) {
4793
+ if (resolvesToFile(entry))
4794
+ return true;
4795
+ const directory = entry.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
4796
+ return pinnedFiles.some((path) => path.startsWith(`${directory}/`));
4797
+ }
4076
4798
  function checkSurfaceGlobsResolve(body, resolvesToFile) {
4077
4799
  const surface = parseIssueSurface(body);
4078
4800
  if (!surface.ok)
4079
4801
  return { status: "pass", errors: [] };
4802
+ const pinnedFiles = boundaryPinnedFiles(body);
4080
4803
  const errors = [];
4081
4804
  for (const glob of surface.value.in) {
4082
- if (!resolvesToFile(glob)) {
4805
+ if (!surfaceEntryResolves(glob, resolvesToFile, pinnedFiles)) {
4083
4806
  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.`);
4084
4807
  }
4085
4808
  }
@@ -4109,6 +4832,14 @@ function recordedBeyondSurfacePaths(body) {
4109
4832
  return paths;
4110
4833
  }
4111
4834
  function checkSurfaceScope(changedFiles, surface, recorded) {
4835
+ for (const path of changedFiles) {
4836
+ if (!isProtectedAdminPath(path))
4837
+ continue;
4838
+ const normalized = normalizeTouchedPath(path);
4839
+ if (!surface.in.some((glob) => globCoversPath(glob, normalized))) {
4840
+ return { ok: false, violation: { path, reason: "protected" } };
4841
+ }
4842
+ }
4112
4843
  const listed = new Set(recorded);
4113
4844
  const violation = beyondSurfacePaths(changedFiles, surface).find((entry) => !listed.has(entry.path));
4114
4845
  return violation ? { ok: false, violation } : { ok: true };
@@ -4164,12 +4895,22 @@ function checkPartsCiteDefinedObjectives(body) {
4164
4895
  }
4165
4896
  return { status: errors.length > 0 ? "fail" : "pass", errors };
4166
4897
  }
4898
+ var ISSUE_LIVE_LINE_RE = /^-\s*\*{2}\[live\]\*{2}(.*)$/gim;
4899
+ function liveCommand(text) {
4900
+ const trimmed = text.trim();
4901
+ const span = /^(`+)(.+)\1$/.exec(trimmed);
4902
+ return span ? span[2].trim() : trimmed;
4903
+ }
4904
+ function liveItemsIn(region) {
4905
+ return [...region.matchAll(ISSUE_LIVE_LINE_RE)].map((m) => liveCommand(m[1] ?? "")).filter(Boolean);
4906
+ }
4907
+ function parseLiveTestPlanItems(body) {
4908
+ const located = locateTestPlanSection(body);
4909
+ return located.found ? liveItemsIn(located.section) : [];
4910
+ }
4167
4911
  function isTaskIssueLabelSet(labels) {
4168
4912
  return hasLabel("tranche", labels);
4169
4913
  }
4170
- function checkTrancheLabelPresence(_body, _labels) {
4171
- return { status: "pass", errors: [] };
4172
- }
4173
4914
  function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
4174
4915
  if (!isTaskIssueLabelSet(labels))
4175
4916
  return { status: "pass", errors: [] };
@@ -4185,6 +4926,7 @@ function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTi
4185
4926
  };
4186
4927
  }
4187
4928
  var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
4929
+ var PATH_TEXT = (body) => stripCode(body, { inlineSpans: "keep" });
4188
4930
  function isControlCodePoint(codePoint) {
4189
4931
  return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
4190
4932
  }
@@ -4245,8 +4987,14 @@ function checkProjectsRegistered(body, _labels, registeredNames) {
4245
4987
  }
4246
4988
  return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
4247
4989
  }
4990
+ function rationaleFieldText(text, labelPattern) {
4991
+ const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})[^\\n]*\\n?([\\s\\S]*?)(?=\\n\\s*(?:\\*\\*[A-Z]|#{1,4}\\s)|(?![\\s\\S]))`, "im");
4992
+ const m = re.exec(text);
4993
+ return m ? m[0] : "";
4994
+ }
4248
4995
  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;
4249
4996
  var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
4997
+ var RATIONALE_PATH_RE_GLOBAL = /`([\w.@-]+(?:\/[\w.@-]+)+)`/g;
4250
4998
  function normalizeEdgeId(s) {
4251
4999
  const qualified = splitSlugQualifiedEdge(s);
4252
5000
  return (qualified ? qualified.bareId : s).replace(/^#/, "").trim();
@@ -4254,6 +5002,15 @@ function normalizeEdgeId(s) {
4254
5002
  function edgesNameEachOther(a, b) {
4255
5003
  return a.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(b.ref)) || b.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(a.ref));
4256
5004
  }
5005
+ var BOUNDARY_OUT_RE = /\bOut\s*:\s*([\s\S]*)$/im;
5006
+ function boundaryOutText(body) {
5007
+ const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
5008
+ const m = BOUNDARY_OUT_RE.exec(boundary);
5009
+ return m ? m[1] : "";
5010
+ }
5011
+ function namedPathsIn(text) {
5012
+ return [...new Set([...text.matchAll(RATIONALE_PATH_RE_GLOBAL)].map((m) => m[1]))].filter((p) => !/^https?:\/\//i.test(p));
5013
+ }
4257
5014
  var FILE_EXTENSIONS = new Set([
4258
5015
  "ts",
4259
5016
  "tsx",
@@ -4275,6 +5032,11 @@ var FILE_EXTENSIONS = new Set([
4275
5032
  "html",
4276
5033
  "css"
4277
5034
  ]);
5035
+ function boundaryPinnedFiles(body) {
5036
+ const boundary = rationaleFieldText(PATH_TEXT(body), "Boundary");
5037
+ const excluded = new Set(namedPathsIn(boundaryOutText(body)));
5038
+ return namedPathsIn(boundary).filter((p) => looksLikeFilePath(p) && !excluded.has(p));
5039
+ }
4278
5040
  var CI_SHARD_DIR = "apps/cli/tests/ci-shards";
4279
5041
  var CI_SHARD_PROBE = `${CI_SHARD_DIR}/shard-1.txt`;
4280
5042
 
@@ -4299,7 +5061,7 @@ function isGrandfathered(isoDate) {
4299
5061
  return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
4300
5062
  }
4301
5063
  var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
4302
- function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
5064
+ function checkA1(entries, principalAllowlist) {
4303
5065
  const failures = [];
4304
5066
  for (const e of entries) {
4305
5067
  if (!e.facts)
@@ -4329,6 +5091,37 @@ function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
4329
5091
  note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4330
5092
  };
4331
5093
  }
5094
+ function checkA2(entries, hasProvenanceByKey) {
5095
+ const failures = [];
5096
+ for (const e of entries) {
5097
+ if (!e.facts)
5098
+ continue;
5099
+ if (e.facts.issueState !== "closed" || e.facts.prState !== "merged")
5100
+ continue;
5101
+ const key = `${e.trancheSlug}/${e.task.id}`;
5102
+ const hasProvenance = hasProvenanceByKey.get(key);
5103
+ if (hasProvenance === undefined)
5104
+ continue;
5105
+ if (!hasProvenance) {
5106
+ failures.push({
5107
+ code: "archived-without-provenance",
5108
+ issue: e.task.issue,
5109
+ tranche: e.trancheSlug,
5110
+ task: e.task.id,
5111
+ reason: "Closing PR has no `### AEG provenance` comment (Archivist close-out missing)",
5112
+ grandfathered: isGrandfathered(e.facts.mergedAt)
5113
+ });
5114
+ }
5115
+ }
5116
+ const activeFails = failures.filter((f) => !f.grandfathered);
5117
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
5118
+ return {
5119
+ check: "A2",
5120
+ status,
5121
+ failures,
5122
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
5123
+ };
5124
+ }
4332
5125
  function checkA3(entries) {
4333
5126
  const failures = [];
4334
5127
  for (const e of entries) {
@@ -4544,6 +5337,33 @@ function checkL1(files, entriesBySlug) {
4544
5337
  note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
4545
5338
  };
4546
5339
  }
5340
+ function checkL2(files, entriesBySlug) {
5341
+ const failures = [];
5342
+ for (const f of files) {
5343
+ if (!f.archived)
5344
+ continue;
5345
+ const entries = entriesBySlug.get(f.slug) ?? [];
5346
+ for (const e of entries) {
5347
+ if (!e.facts)
5348
+ continue;
5349
+ if (e.facts.issueState === "open") {
5350
+ failures.push({
5351
+ code: "premature-archive",
5352
+ issue: e.task.issue,
5353
+ tranche: f.slug,
5354
+ task: e.task.id,
5355
+ reason: `Archived tranche has open task-Issue #${e.task.issue ?? "?"} (premature archive)`
5356
+ });
5357
+ }
5358
+ }
5359
+ }
5360
+ return {
5361
+ check: "L2",
5362
+ status: "info",
5363
+ failures,
5364
+ note: failures.length > 0 ? `${failures.length} archived tranche(s) with an open task-Issue — investigate (advisory)` : undefined
5365
+ };
5366
+ }
4547
5367
  function checkL3(files) {
4548
5368
  const active = files.filter((f) => !f.archived);
4549
5369
  return {
@@ -4553,6 +5373,51 @@ function checkL3(files) {
4553
5373
  note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
4554
5374
  };
4555
5375
  }
5376
+ function checkL4(activeTrancheSlugs, issueMilestones) {
5377
+ const activeSet = new Set(activeTrancheSlugs);
5378
+ const failures = [];
5379
+ for (const f of issueMilestones) {
5380
+ if (!activeSet.has(f.tranche))
5381
+ continue;
5382
+ if (f.milestoneTitle === f.tranche)
5383
+ continue;
5384
+ failures.push({
5385
+ code: "milestone-drift",
5386
+ issue: f.issue,
5387
+ tranche: f.tranche,
5388
+ 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`
5389
+ });
5390
+ }
5391
+ return {
5392
+ check: "L4",
5393
+ status: "info",
5394
+ failures,
5395
+ 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
5396
+ };
5397
+ }
5398
+ function checkL5(activeTrancheSlugs, entriesBySlug) {
5399
+ const failures = [];
5400
+ for (const slug of activeTrancheSlugs) {
5401
+ const entries = entriesBySlug.get(slug) ?? [];
5402
+ const withFacts = entries.filter((e) => e.facts !== undefined);
5403
+ if (withFacts.length === 0)
5404
+ continue;
5405
+ const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
5406
+ if (allClosed) {
5407
+ failures.push({
5408
+ code: "tranche-not-archived",
5409
+ tranche: slug,
5410
+ reason: "Every task Issue is closed but the tranche is not recorded as complete — archive it"
5411
+ });
5412
+ }
5413
+ }
5414
+ return {
5415
+ check: "L5",
5416
+ status: failures.length > 0 ? "fail" : "pass",
5417
+ failures,
5418
+ note: failures.length > 0 ? `${failures.length} tranche(s) whose task Issues are all closed but were never archived` : undefined
5419
+ };
5420
+ }
4556
5421
  function extractClosesReferences(prBody) {
4557
5422
  const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
4558
5423
  const stripped = stripCode(prBody);
@@ -4648,6 +5513,58 @@ function extractIssue(body) {
4648
5513
  }
4649
5514
  // ../../packages/aeg-core/src/review-input-manifest.ts
4650
5515
  import { createHash as createHash4 } from "node:crypto";
5516
+
5517
+ // ../../packages/aeg-core/src/ruling-ordinal.ts
5518
+ var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
5519
+ function newestPrincipalRulingOrdinal(comments, allowlist) {
5520
+ let best = 0;
5521
+ for (const c of comments) {
5522
+ if (!isPrincipal(c.author, allowlist))
5523
+ continue;
5524
+ const firstLine = (c.body.split(`
5525
+ `)[0] ?? "").trim();
5526
+ const m = RULING_MARKER_ORDINAL.exec(firstLine);
5527
+ if (!m)
5528
+ continue;
5529
+ const k = Number.parseInt(m[1], 10);
5530
+ if (k > best)
5531
+ best = k;
5532
+ }
5533
+ return best;
5534
+ }
5535
+ function parseRulingIdentity(rulingId) {
5536
+ const m = /^(issue-)?(\d+)-(\d+)$/.exec(rulingId);
5537
+ if (!m)
5538
+ return null;
5539
+ const ref = Number.parseInt(m[2], 10);
5540
+ const ordinal = Number.parseInt(m[3], 10);
5541
+ if (ref <= 0 || ordinal <= 0)
5542
+ return null;
5543
+ return { target: m[1] ? "issue" : "pr", ref, ordinal };
5544
+ }
5545
+ function principalRulingTextById(comments, allowlist, rulingId) {
5546
+ const identity = parseRulingIdentity(rulingId);
5547
+ if (identity === null)
5548
+ return null;
5549
+ const matches = comments.filter((c) => {
5550
+ if (!isPrincipal(c.author, allowlist))
5551
+ return false;
5552
+ const m = RULING_MARKER_ORDINAL.exec((c.body.split(`
5553
+ `)[0] ?? "").trim());
5554
+ return m !== null && Number.parseInt(m[1], 10) === identity.ordinal;
5555
+ });
5556
+ if (matches.length !== 1)
5557
+ return null;
5558
+ const body = matches[0].body;
5559
+ const idx = body.indexOf(`
5560
+ `);
5561
+ return idx === -1 ? "" : body.slice(idx + 1).trim();
5562
+ }
5563
+
5564
+ // ../../packages/aeg-core/src/review-input-manifest.ts
5565
+ function pauseBoundRulingDigest(rulingText) {
5566
+ return createHash4("sha256").update(rulingText).digest("hex");
5567
+ }
4651
5568
  function briefHash(brief) {
4652
5569
  return createHash4("sha256").update(`${brief}
4653
5570
  `).digest("hex");
@@ -4708,14 +5625,19 @@ function compareManifest(echoed, current, patchIdOf) {
4708
5625
  const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4709
5626
  const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4710
5627
  const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
5628
+ const legacyCurrent = current.manifestVersion === undefined;
5629
+ const manifestVersion = legacyCurrent ? echoed.manifestVersion === undefined || echoed.manifestVersion === null : echoed.manifestVersion === current.manifestVersion;
5630
+ const pauseBoundRuling = legacyCurrent ? true : Object.hasOwn(echoed, "pauseBoundRuling") && JSON.stringify(echoed.pauseBoundRuling) === JSON.stringify(current.pauseBoundRuling);
4711
5631
  const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4712
5632
  return {
4713
- bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
5633
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && pauseBoundRuling && manifestVersion && policyDigestBound,
4714
5634
  head,
4715
5635
  base,
4716
5636
  briefHash: briefHashBound,
4717
5637
  objectivesVersion,
4718
5638
  rulingOrdinal,
5639
+ pauseBoundRuling,
5640
+ manifestVersion,
4719
5641
  policyDigest: policyDigestBound
4720
5642
  };
4721
5643
  }
@@ -4731,7 +5653,7 @@ function renderGateDeferred(deferred) {
4731
5653
  return ` ${deferred.length} finding(s) deferred, not blocking this round: ${items}.`;
4732
5654
  }
4733
5655
  function checkReviewGate(input) {
4734
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
5656
+ const { principalAllowlist } = input;
4735
5657
  const waived = isWaiverLabelActorVerified({
4736
5658
  label: WAIVER_LABEL_REVIEW,
4737
5659
  labels: input.labels,
@@ -4770,27 +5692,33 @@ function checkReviewGate(input) {
4770
5692
  const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4771
5693
  const securityClean = securityTextClean && securityPolicyClean;
4772
5694
  const currentManifest = {
5695
+ ...input.manifestVersion === undefined ? {} : { manifestVersion: input.manifestVersion },
4773
5696
  headSha: input.headSha,
4774
5697
  baseSha: input.baseSha ?? null,
4775
5698
  briefHash: input.briefHash ?? null,
4776
5699
  objectivesVersion: input.objectivesVersion,
4777
5700
  rulingOrdinal: input.rulingOrdinal,
5701
+ pauseBoundRuling: input.pauseBoundRuling ?? null,
4778
5702
  policyDigest: policyDigest(policy)
4779
5703
  };
4780
5704
  const codeReviewEchoed = {
5705
+ manifestVersion: codeReview.manifestVersion,
4781
5706
  headSha: codeReview.headSha,
4782
5707
  baseSha: codeReview.baseSha,
4783
5708
  briefHash: codeReview.briefHash,
4784
5709
  objectivesVersion: codeReview.objectivesVersion,
4785
5710
  rulingOrdinal: codeReview.rulingOrdinal,
5711
+ pauseBoundRuling: codeReview.pauseBoundRuling,
4786
5712
  policyDigest: codeReview.policyDigest
4787
5713
  };
4788
5714
  const securityEchoed = {
5715
+ manifestVersion: security.manifestVersion,
4789
5716
  headSha: security.headSha,
4790
5717
  baseSha: security.baseSha,
4791
5718
  briefHash: security.briefHash,
4792
5719
  objectivesVersion: security.objectivesVersion,
4793
5720
  rulingOrdinal: security.rulingOrdinal,
5721
+ pauseBoundRuling: security.pauseBoundRuling,
4794
5722
  policyDigest: security.policyDigest
4795
5723
  };
4796
5724
  const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
@@ -4829,6 +5757,10 @@ function checkReviewGate(input) {
4829
5757
  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"}`);
4830
5758
  } else if (!codeReviewBinding.policyDigest) {
4831
5759
  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}`);
5760
+ } else if (!codeReviewBinding.manifestVersion) {
5761
+ problems.push(`the newest code-review verdict echoes manifest version ${codeReview.manifestVersion ?? "none"}, the frozen review-input manifest is version ${currentManifest.manifestVersion ?? "unversioned"}`);
5762
+ } else if (!codeReviewBinding.pauseBoundRuling) {
5763
+ problems.push(`the newest code-review verdict echoes pauseBoundRuling ${renderBinding(codeReview.pauseBoundRuling)}, the frozen review-input manifest binds ${renderBinding(currentManifest.pauseBoundRuling)}`);
4832
5764
  }
4833
5765
  if (!securityTextClean) {
4834
5766
  problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
@@ -4846,6 +5778,10 @@ function checkReviewGate(input) {
4846
5778
  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"}`);
4847
5779
  } else if (!securityBinding.policyDigest) {
4848
5780
  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}`);
5781
+ } else if (!securityBinding.manifestVersion) {
5782
+ problems.push(`the newest security-review verdict echoes manifest version ${security.manifestVersion ?? "none"}, the frozen review-input manifest is version ${currentManifest.manifestVersion ?? "unversioned"}`);
5783
+ } else if (!securityBinding.pauseBoundRuling) {
5784
+ problems.push(`the newest security-review verdict echoes pauseBoundRuling ${renderBinding(security.pauseBoundRuling)}, the frozen review-input manifest binds ${renderBinding(currentManifest.pauseBoundRuling)}`);
4849
5785
  }
4850
5786
  const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4851
5787
  return {
@@ -4854,29 +5790,16 @@ function checkReviewGate(input) {
4854
5790
  waived: false
4855
5791
  };
4856
5792
  }
5793
+ function renderBinding(binding) {
5794
+ if (binding === undefined)
5795
+ return "(absent)";
5796
+ return binding === null ? "(none)" : `${binding.rulingId}|${binding.pauseId}|${binding.contentDigest}`;
5797
+ }
4857
5798
  var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4858
5799
  var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4859
5800
  function isChangesetsReleasePr(branch, author, expectedAuthor) {
4860
5801
  return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4861
5802
  }
4862
- // ../../packages/aeg-core/src/ruling-ordinal.ts
4863
- var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4864
- function newestPrincipalRulingOrdinal(comments, allowlist) {
4865
- let best = 0;
4866
- for (const c of comments) {
4867
- if (!isPrincipal(c.author, allowlist))
4868
- continue;
4869
- const firstLine = (c.body.split(`
4870
- `)[0] ?? "").trim();
4871
- const m = RULING_MARKER_ORDINAL.exec(firstLine);
4872
- if (!m)
4873
- continue;
4874
- const k = Number.parseInt(m[1], 10);
4875
- if (k > best)
4876
- best = k;
4877
- }
4878
- return best;
4879
- }
4880
5803
  // ../../packages/aeg-core/src/markdown-table.ts
4881
5804
  function splitRow(line) {
4882
5805
  const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
@@ -5028,7 +5951,6 @@ var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
5028
5951
  var NON_GATE_BIN_NAMES = NON_GATE_BINS;
5029
5952
  var TWIN_CANDIDATE_EXCEPTIONS = {
5030
5953
  "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)',
5031
- "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)`,
5032
5954
  "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
5033
5955
  };
5034
5956
  var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
@@ -5252,72 +6174,10 @@ function compareToBaseline(current, baseline) {
5252
6174
  };
5253
6175
  }
5254
6176
  // ../../packages/aeg-core/src/retired-vocabulary.ts
5255
- var PLAN_ON_DISK_PATTERNS = ["[Tt]opology files?", "aeg-root/tranches/", "aeg-project/"];
5256
- var RETIRED_PATTERNS = [
5257
- String.raw`\bD-[0-9]{3}\b`,
5258
- "D-(###|NNN|nnn|xxx)",
5259
- "decision (entry|logged)",
5260
- "decision-log entry",
5261
- "decision log entry",
5262
- "decision log(s|ged|ging)?([^a-z]|$)",
5263
- "decision-log",
5264
- "decision entr",
5265
- "decisions? (are |is )?logged",
5266
- "log entries",
5267
- String.raw`decisions\.md`,
5268
- "decisions-legacy",
5269
- "CONTRADICTION",
5270
- "assumes Tier 3",
5271
- "Lock: ?YES",
5272
- "Lock: ?NO",
5273
- "lock approvals?",
5274
- "approves locks",
5275
- "Conforms to lock",
5276
- "Challenges lock",
5277
- "checkDecisionNumbersFresh",
5278
- String.raw`roles/team-leader\.md`,
5279
- String.raw`\(,`,
5280
- String.raw`,\)`,
5281
- String.raw`\(\.\)`,
5282
- ...PLAN_ON_DISK_PATTERNS
5283
- ];
5284
- var TRANCHE_MODEL_FILE = "/tranche-model.md";
5285
- var RETIRED_EXEMPT_SUBSTRINGS = [
5286
- "docs/decisions-legacy.md",
5287
- "apps/herald-ai/docs/",
5288
- "apps/vada-ai/docs/",
5289
- "aeg-root/tranches/completed/",
5290
- "packages/aeg-core/src/docs/published-prose",
5291
- "packages/aeg-core/src/retired-vocabulary.test.ts",
5292
- "packages/aeg-core/src/retired-vocabulary.ts",
5293
- "/fixtures/",
5294
- "/node_modules/",
5295
- "/.next/",
5296
- "/.turbo/"
5297
- ];
5298
- var PATTERN_EXEMPT = {
5299
- [String.raw`\bD-[0-9]{3}\b`]: ["./CLAUDE.md"],
5300
- [String.raw`decisions\.md`]: [
5301
- "docs-index.md",
5302
- "apps/vada-ai/specs/legacy/README.md",
5303
- "apps/vada-ai/specs/vada-product-spec.md",
5304
- "apps/vada-ai/web/CLAUDE.md",
5305
- "apps/vada-ai/CLAUDE.md"
5306
- ],
5307
- "decisions-legacy": [
5308
- "packages/aeg-core/src/file-classify.ts",
5309
- "packages/aeg-core/src/file-classify.test.ts",
5310
- "packages/aeg-core/src/pr-tier.test.ts",
5311
- "docs-index.md",
5312
- ".claude/skills/database/SKILL.md",
5313
- ".claude/skills/vada-architecture/SKILL.md",
5314
- "apps/vada-ai/specs/vada-byok-principles.md",
5315
- "apps/vada-ai/web/CLAUDE.md",
5316
- "apps/vada-ai/CLAUDE.md"
5317
- ],
5318
- CONTRADICTION: ["apps/vada-ai/specs/vada-reviewers-spec.md"],
5319
- ...Object.fromEntries(PLAN_ON_DISK_PATTERNS.map((pattern) => [pattern, [TRANCHE_MODEL_FILE]]))
5320
- };
6177
+ var retiredRules = rulesForGroup("retired-vocabulary");
6178
+ var RETIRED_PATTERNS = retiredRules.map((rule) => rule.patterns.repository);
6179
+ var PATTERN_EXEMPT = RETIRED_PATTERN_EXEMPTIONS;
6180
+ var DEFAULT_PATTERN_OF = new Map(retiredRules.map((rule) => [rule.id, rule.patterns.repository]));
5321
6181
  function lineNumbers(content, pattern) {
5322
6182
  const out = [];
5323
6183
  const lines = content.split(`
@@ -5328,22 +6188,29 @@ function lineNumbers(content, pattern) {
5328
6188
  }
5329
6189
  return out;
5330
6190
  }
5331
- function scanRetiredVocabulary(files) {
6191
+ function scanRetiredVocabulary(files, rules = DEFAULT_PROSE_RULE_SET) {
5332
6192
  const findings = [];
6193
+ const retired = rulesOfGroup(rules, "retired-vocabulary");
5333
6194
  for (const file of files) {
5334
- if (RETIRED_EXEMPT_SUBSTRINGS.some((e) => file.path.includes(e)))
5335
- continue;
5336
- for (const pattern of RETIRED_PATTERNS) {
5337
- const patternExempt = PATTERN_EXEMPT[pattern] ?? [];
5338
- if (patternExempt.some((e) => file.path.includes(e)))
6195
+ for (const rule of retired) {
6196
+ if (rule.substringExempt.some((e) => file.path.includes(e)))
6197
+ continue;
6198
+ if (!ruleReads(rules, rule, file.path))
6199
+ continue;
6200
+ const re = rule.patternFor("repository");
6201
+ if (!re)
6202
+ continue;
6203
+ const pattern = rule.custom ? re.source : DEFAULT_PATTERN_OF.get(rule.id) ?? re.source;
6204
+ if (!rule.custom && (PATTERN_EXEMPT[pattern] ?? []).some((e) => file.path.includes(e)))
5339
6205
  continue;
5340
- const re = new RegExp(pattern);
5341
6206
  for (const line of lineNumbers(file.content, re)) {
5342
6207
  findings.push({
5343
6208
  file: file.path,
5344
6209
  line,
5345
6210
  pattern,
5346
- message: `claims a retired AEG mechanism is still live (matches /${pattern}/)`
6211
+ message: rule.custom ? `${rule.id}: ${rule.message} (matches /${pattern}/)` : `claims a retired AEG mechanism is still live (matches /${pattern}/)`,
6212
+ rule: rule.id,
6213
+ blocking: rule.severity.repository === "error"
5347
6214
  });
5348
6215
  }
5349
6216
  }
@@ -5367,7 +6234,7 @@ function isSelfDependency(dep, task, issue) {
5367
6234
  function checkDispatchReadiness(input) {
5368
6235
  const { trancheSlug, task } = input;
5369
6236
  const taskLabel = `task ${task.id} (tranche ${trancheSlug})`;
5370
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
6237
+ const { principalAllowlist } = input;
5371
6238
  const blockerDetails = [];
5372
6239
  const push = (blockerClass, message) => {
5373
6240
  blockerDetails.push({ class: blockerClass, message });
@@ -5459,6 +6326,16 @@ function pushesAnyBranchRef(pushRefs) {
5459
6326
  return pushRefs.split(`
5460
6327
  `).map((line) => line.trim()).filter((line) => line.length > 0).some((line) => line.split(/\s+/)[2]?.startsWith("refs/heads/") === true);
5461
6328
  }
6329
+ function resolveDefaultBranch(facts) {
6330
+ const { originHead, hasOriginMain, hasOriginMaster } = facts;
6331
+ if (originHead !== null && originHead !== "")
6332
+ return originHead;
6333
+ if (hasOriginMain)
6334
+ return "main";
6335
+ if (hasOriginMaster)
6336
+ return "master";
6337
+ return null;
6338
+ }
5462
6339
  function checkMainBranchRefusal(facts) {
5463
6340
  const { currentSymbolicBranch, defaultBranch, pushRefs = null } = facts;
5464
6341
  if (currentSymbolicBranch === null)
@@ -5719,54 +6596,61 @@ function checkFirstPushDispatchGate(input) {
5719
6596
  reason: `verify-dispatch reports READY TO DISPATCH for \`${branch}\`.`
5720
6597
  };
5721
6598
  }
5722
- // ../../packages/aeg-core/src/issue-assignment.ts
5723
- function decideIssueAssignment(input) {
5724
- const { branch, remoteRefExists, issue, assignees, login } = input;
5725
- if (parseTaskBranch(branch) === null) {
5726
- return {
5727
- action: "skip",
5728
- reason: `Branch \`${branch}\` is not a task/<tranche>/<n> branch — Issue self-assignment only applies to task branches.`
5729
- };
5730
- }
5731
- if (remoteRefExists) {
5732
- return {
5733
- action: "skip",
5734
- reason: `Branch \`${branch}\` already exists on the remote — not its first push, nothing to assign.`
5735
- };
5736
- }
5737
- if (issue === null) {
5738
- return {
5739
- action: "skip",
5740
- reason: `No Issue resolved for \`${branch}\` from its topology row — skipping self-assignment (the gate owns refusing an unplanned branch).`
5741
- };
5742
- }
5743
- if (assignees === null) {
5744
- return {
5745
- action: "skip",
5746
- reason: `Could not read Issue #${issue}'s current assignees — skipping rather than risking a double-assign (fail-open, never a guess).`
5747
- };
5748
- }
5749
- if (assignees.length > 0) {
5750
- return {
5751
- action: "skip",
5752
- reason: `Issue #${issue} is already assigned (${assignees.join(", ")}) — no-op.`
5753
- };
5754
- }
5755
- if (login === null) {
5756
- return {
5757
- action: "skip",
5758
- reason: "Could not resolve the authenticated `gh` login — never assigning anyone other than the actual pusher, so skipping."
5759
- };
6599
+ // ../../packages/aeg-core/src/live-record.ts
6600
+ var RECORD_LINE_RE = /^-\s*\[([ xX])\]\s*\*\*\[live\]\*\*\s+(`+) ?(.+?) ?\2(?!`)\s+—\s+(passed|failed|unverified)\s+at\s+`([^`]+)`/;
6601
+ function liveMarkers(body) {
6602
+ const masked = maskCode(body);
6603
+ return [...masked.matchAll(/<!--\s*AEG:LIVE:(?:START|END)\s*-->/g)].map((m) => ({
6604
+ start: m.index,
6605
+ end: m.index + m[0].length
6606
+ }));
6607
+ }
6608
+ var AMBIGUOUS_RECORD_LINE = {
6609
+ line: "- [ ] **[live]** the pull request body carries more than one `AEG:LIVE` marker pair, so the driver's record cannot be told apart",
6610
+ ticked: false,
6611
+ command: "",
6612
+ outcome: "failed",
6613
+ head: ""
6614
+ };
6615
+ function readLiveRecord(body) {
6616
+ const markers = liveMarkers(body).length;
6617
+ if (markers === 0)
6618
+ return [];
6619
+ if (markers !== 2)
6620
+ return [AMBIGUOUS_RECORD_LINE];
6621
+ const region = anchoredRegion(body, "LIVE");
6622
+ if (region === null)
6623
+ return [];
6624
+ const lines = [];
6625
+ for (const raw of region.split(`
6626
+ `)) {
6627
+ const line = raw.trim();
6628
+ const m = RECORD_LINE_RE.exec(line);
6629
+ if (!m)
6630
+ continue;
6631
+ lines.push({
6632
+ line,
6633
+ ticked: m[1].toLowerCase() === "x",
6634
+ command: m[3],
6635
+ outcome: m[4],
6636
+ head: m[5]
6637
+ });
5760
6638
  }
5761
- return {
5762
- action: "assign",
5763
- issue,
5764
- login,
5765
- reason: `First push of \`${branch}\` — assigning Issue #${issue} to @${login} (the authenticated pusher).`
5766
- };
6639
+ return lines;
5767
6640
  }
5768
6641
  // ../../packages/aeg-core/src/test-plan-gate.ts
5769
- function evaluateTestPlanGate(body, branch) {
6642
+ function gradedLiveLines(record, live) {
6643
+ if (live === undefined)
6644
+ return record.map((entry) => entry.line);
6645
+ const commands = new Set(live.liveCommands);
6646
+ const others = record.filter((entry) => !commands.has(entry.command)).map((entry) => entry.line);
6647
+ const graded = live.liveCommands.map((command) => {
6648
+ const atHead = record.filter((entry) => entry.command === command && entry.head === live.head);
6649
+ return (atHead.find((entry) => entry.ticked) ?? atHead[0])?.line ?? `- [ ] **[live]** \`${command}\` — no passed run recorded at \`${live.head || "an unknown head"}\``;
6650
+ });
6651
+ return [...others, ...graded];
6652
+ }
6653
+ function evaluateTestPlanGate(body, branch, live) {
5770
6654
  if (!body) {
5771
6655
  return {
5772
6656
  verdict: "pass",
@@ -5777,7 +6661,9 @@ function evaluateTestPlanGate(body, branch) {
5777
6661
  };
5778
6662
  }
5779
6663
  const located = locateTestPlanSection(body);
5780
- if (!located.found) {
6664
+ const liveLines = gradedLiveLines(readLiveRecord(body), live);
6665
+ const liveUnticked = liveLines.some((line) => /^[-*]\s+\[\s\]/.test(line));
6666
+ if (!located.found && !liveUnticked) {
5781
6667
  if (parseTaskBranchIdentity(branch) !== null) {
5782
6668
  return {
5783
6669
  verdict: "fail",
@@ -5797,15 +6683,18 @@ function evaluateTestPlanGate(body, branch) {
5797
6683
  ]
5798
6684
  };
5799
6685
  }
5800
- const section = located.section;
5801
- if (/unit-tests-only/i.test(section)) {
6686
+ const section = located.found ? located.section : "";
6687
+ if (/unit-tests-only/i.test(section) && !liveUnticked) {
5802
6688
  return {
5803
6689
  verdict: "pass",
5804
6690
  messages: ["Test Plan: unit-tests-only — pure-logic brief, CI unit-tests are the proof.", "PASS."]
5805
6691
  };
5806
6692
  }
5807
- const checkboxLines = section.split(`
5808
- `).map((line) => line.trimStart()).filter((line) => /^[-*]\s+\[[ xX]\]\s*\*{0,2}\[principal\]\*{0,2}/i.test(line));
6693
+ const checkboxLines = [
6694
+ ...section.split(`
6695
+ `).map((line) => line.trimStart()).filter((line) => /^[-*]\s+\[[ xX]\]\s*\*{0,2}\[principal\]\*{0,2}/i.test(line)),
6696
+ ...liveLines
6697
+ ];
5809
6698
  if (checkboxLines.length === 0) {
5810
6699
  return {
5811
6700
  verdict: "pass",
@@ -5822,7 +6711,9 @@ function evaluateTestPlanGate(body, branch) {
5822
6711
  messages.push("", "FAIL — the following [principal] Test Plan items are unticked:");
5823
6712
  for (const line of unchecked)
5824
6713
  messages.push(` ${line}`);
5825
- 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.");
6714
+ 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 ? [
6715
+ "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."
6716
+ ] : [], "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.");
5826
6717
  return { verdict: "fail", messages };
5827
6718
  }
5828
6719
  messages.push("All [principal] Test Plan items ticked — runtime verification complete.", "PASS.");
@@ -6011,9 +6902,11 @@ var LineageSchema = z3.object({
6011
6902
  parent: z3.string().nullable()
6012
6903
  }).strict();
6013
6904
  var InputVersionsSchema = z3.object({
6905
+ manifest_version: z3.literal(2).nullable().optional(),
6014
6906
  objectives_version: z3.string().nullable(),
6015
6907
  brief_hash: z3.string().nullable(),
6016
6908
  ruling_ordinal: z3.number().int().nullable(),
6909
+ pause_bound_ruling: z3.object({ rulingId: z3.string().min(1), pauseId: z3.string().min(1), contentDigest: z3.string().min(1) }).strict().nullable().optional(),
6017
6910
  policy_digest: z3.string().nullable()
6018
6911
  }).strict();
6019
6912
  var ProvenanceSchema = z3.enum(["parent_attributed", "env_correlated", "self_reported", "unavailable"]);
@@ -6051,7 +6944,17 @@ var HeaderMetaV3Schema = z3.object({
6051
6944
  runtime: z3.string().nullable(),
6052
6945
  source: z3.string().nullable()
6053
6946
  }).strict();
6054
- var HeaderMetaSchema = z3.discriminatedUnion("schema", [HeaderMetaV1Schema, HeaderMetaV2Schema, HeaderMetaV3Schema]);
6947
+ var HeaderMetaV4Schema = HeaderMetaV3Schema.extend({
6948
+ schema: z3.literal(4),
6949
+ process: z3.object({ id: z3.string(), version: z3.string().nullable(), digest: z3.string().nullable() }).strict(),
6950
+ runner: z3.object({ id: z3.string(), version: z3.string().nullable() }).strict()
6951
+ }).strict();
6952
+ var HeaderMetaSchema = z3.discriminatedUnion("schema", [
6953
+ HeaderMetaV1Schema,
6954
+ HeaderMetaV2Schema,
6955
+ HeaderMetaV3Schema,
6956
+ HeaderMetaV4Schema
6957
+ ]);
6055
6958
  var SubjectSchema = z3.object({
6056
6959
  issue: z3.number().int().nullable(),
6057
6960
  pr: z3.number().int().optional(),
@@ -6273,21 +7176,90 @@ var DevReviewLoopEventSchema = z3.discriminatedUnion("event", [
6273
7176
  }).strict(),
6274
7177
  z3.object({
6275
7178
  ...loopShared,
6276
- event: z3.literal("driver_exited"),
7179
+ event: z3.literal("conflict_reentry"),
6277
7180
  task: z3.number().int(),
6278
- reason: z3.enum(["finished", "paused", "reexec", "error", "signal"]),
6279
- last_decision: z3.string(),
6280
- exit_code: z3.number().int().optional(),
6281
- error_class: CodeTokenSchema.optional()
6282
- }).strict()
6283
- ]);
6284
- var ForgeOpSchema = z3.enum([
6285
- "pr.create",
6286
- "pr.comment",
6287
- "pr.body.replace",
6288
- "pr.refreeze",
6289
- "issue.create",
6290
- "issue.edit",
7181
+ pr: z3.number().int().positive(),
7182
+ attempt: z3.number().int().positive(),
7183
+ bound: z3.number().int().positive()
7184
+ }).strict(),
7185
+ z3.object({
7186
+ ...loopShared,
7187
+ event: z3.literal("storage_push"),
7188
+ round: z3.number().int(),
7189
+ branch: z3.string(),
7190
+ head: z3.string()
7191
+ }).strict(),
7192
+ z3.object({
7193
+ ...loopShared,
7194
+ event: z3.literal("local_checks_run"),
7195
+ round: z3.number().int(),
7196
+ head: z3.string().nullable(),
7197
+ passed: z3.boolean(),
7198
+ wall_ms: z3.number().nonnegative()
7199
+ }).strict(),
7200
+ z3.object({
7201
+ ...loopShared,
7202
+ event: z3.literal("ready_push"),
7203
+ round: z3.number().int(),
7204
+ head: z3.string(),
7205
+ outcome: z3.enum(["passed", "refused"]),
7206
+ selected: z3.number().int().nonnegative(),
7207
+ failed: z3.number().int().nonnegative(),
7208
+ rerun: z3.boolean(),
7209
+ wall_ms: z3.number().nonnegative()
7210
+ }).strict(),
7211
+ z3.object({
7212
+ ...loopShared,
7213
+ event: z3.literal("failed_tests_rerun"),
7214
+ round: z3.number().int(),
7215
+ head: z3.string(),
7216
+ rerun_of: z3.string(),
7217
+ failed_files: z3.number().int().nonnegative(),
7218
+ affected_files: z3.number().int().nonnegative(),
7219
+ full_count: z3.number().int().nonnegative()
7220
+ }).strict(),
7221
+ z3.object({
7222
+ ...loopShared,
7223
+ event: z3.literal("pr_opened"),
7224
+ round: z3.number().int(),
7225
+ pr: z3.number().int().positive(),
7226
+ head: z3.string()
7227
+ }).strict(),
7228
+ z3.object({
7229
+ ...loopShared,
7230
+ event: z3.literal("ci_result_read"),
7231
+ round: z3.number().int(),
7232
+ pr: z3.number().int().positive(),
7233
+ head: z3.string(),
7234
+ conclusion: z3.enum(["green", "red", "pending", "skipped"]),
7235
+ failing_checks: z3.array(z3.string()),
7236
+ wait_ms: z3.number().nonnegative()
7237
+ }).strict(),
7238
+ z3.object({
7239
+ ...loopShared,
7240
+ event: z3.literal("phase_time"),
7241
+ round: z3.number().int(),
7242
+ phase: z3.enum(["developer", "local_checks", "review", "push", "ci", "other"]),
7243
+ step: z3.string(),
7244
+ wall_ms: z3.number().nonnegative()
7245
+ }).strict(),
7246
+ z3.object({
7247
+ ...loopShared,
7248
+ event: z3.literal("driver_exited"),
7249
+ task: z3.number().int(),
7250
+ reason: z3.enum(["finished", "paused", "reexec", "error", "signal"]),
7251
+ last_decision: z3.string(),
7252
+ exit_code: z3.number().int().optional(),
7253
+ error_class: CodeTokenSchema.optional()
7254
+ }).strict()
7255
+ ]);
7256
+ var ForgeOpSchema = z3.enum([
7257
+ "pr.create",
7258
+ "pr.comment",
7259
+ "pr.body.replace",
7260
+ "pr.refreeze",
7261
+ "issue.create",
7262
+ "issue.edit",
6291
7263
  "issue.comment",
6292
7264
  "milestone.create",
6293
7265
  "milestone.edit",
@@ -6458,7 +7430,7 @@ var EffectEventSchema = z3.discriminatedUnion("event", [
6458
7430
  ]);
6459
7431
  var CustomFieldValueSchema = z3.union([z3.string().max(CUSTOM_TEXT_MAX_LENGTH), z3.number().finite(), z3.boolean()]);
6460
7432
  var customShared = {
6461
- meta: HeaderMetaV3Schema,
7433
+ meta: HeaderMetaSchema,
6462
7434
  subject: SubjectSchema,
6463
7435
  kind: z3.literal("custom"),
6464
7436
  ...envelopeTail
@@ -6543,7 +7515,7 @@ function buildHeader(input) {
6543
7515
  const issue = subject.issue;
6544
7516
  return {
6545
7517
  meta: {
6546
- schema: 3,
7518
+ schema: 4,
6547
7519
  ts: input.now.toISOString(),
6548
7520
  run_id: input.runId,
6549
7521
  seq: input.seq,
@@ -6561,23 +7533,34 @@ function buildHeader(input) {
6561
7533
  parent: lineageFieldFromEnv(input.env.parent)
6562
7534
  },
6563
7535
  input_versions: {
7536
+ manifest_version: input.inputVersions?.manifestVersion ?? null,
6564
7537
  objectives_version: input.inputVersions?.objectivesVersion ?? null,
6565
7538
  brief_hash: input.inputVersions?.briefHash ?? null,
6566
7539
  ruling_ordinal: input.inputVersions?.rulingOrdinal ?? null,
7540
+ pause_bound_ruling: input.inputVersions?.pauseBoundRuling ?? null,
6567
7541
  policy_digest: input.inputVersions?.policyDigest ?? null
6568
7542
  },
6569
7543
  provenance: provenanceFor(input),
6570
7544
  work: {
6571
7545
  ref: lineageFieldFromEnv(input.env.workRef) ?? (issue === null ? null : String(issue)),
6572
7546
  repo: input.repo,
6573
- change: null,
6574
- revision: null
7547
+ change: pr === undefined ? null : String(pr),
7548
+ revision: input.revision ?? null
6575
7549
  },
6576
7550
  flow: {
6577
7551
  id: lineageFieldFromEnv(input.env.flow) ?? "vinaya",
6578
7552
  version: lineageFieldFromEnv(input.env.flowVersion)
6579
7553
  },
6580
7554
  runtime: lineageFieldFromEnv(input.env.runtime),
7555
+ process: {
7556
+ id: lineageFieldFromEnv(input.env.processId) ?? "vinaya",
7557
+ version: lineageFieldFromEnv(input.env.processVersion),
7558
+ digest: lineageFieldFromEnv(input.env.processDigest)
7559
+ },
7560
+ runner: {
7561
+ id: lineageFieldFromEnv(input.env.runnerId) ?? "standalone",
7562
+ version: lineageFieldFromEnv(input.env.runnerVersion)
7563
+ },
6581
7564
  source: lineageFieldFromEnv(input.env.source)
6582
7565
  },
6583
7566
  subject
@@ -6621,7 +7604,7 @@ function redact(value, home) {
6621
7604
  return value;
6622
7605
  }
6623
7606
  // ../../packages/aeg-core/src/log/store.ts
6624
- var KNOWN_SCHEMA_VERSIONS = [1, 2, 3];
7607
+ var KNOWN_SCHEMA_VERSIONS = [1, 2, 3, 4];
6625
7608
  function metaOf(obj) {
6626
7609
  if (obj === null || typeof obj !== "object")
6627
7610
  return null;
@@ -6759,6 +7742,12 @@ var ManifestRecordSchema = z4.object({
6759
7742
  briefHash: z4.string().min(1).nullable(),
6760
7743
  objectivesVersion: z4.string().min(1).nullable(),
6761
7744
  rulingOrdinal: epochNumber,
7745
+ manifestVersion: z4.literal(2).optional(),
7746
+ pauseBoundRuling: z4.object({
7747
+ rulingId: z4.string().min(1),
7748
+ pauseId: z4.string().min(1),
7749
+ contentDigest: z4.string().min(1)
7750
+ }).strict().nullable().optional(),
6762
7751
  policyDigest: z4.string().min(1),
6763
7752
  recordedAt: isoTimestamp
6764
7753
  }).strict();
@@ -6780,7 +7769,11 @@ var LoopStateRecordSchema = z4.object({
6780
7769
  deliveredFindings: roundHeadIdentity.nullable(),
6781
7770
  repeatMemory: z4.object({
6782
7771
  blockingFindings: z4.array(z4.string()),
6783
- lastFailure: z4.object({ signature: z4.string(), message: z4.string() }).nullable()
7772
+ lastFailure: z4.object({ signature: z4.string(), message: z4.string(), developerAttemptedSince: z4.boolean().optional() }).nullable()
7773
+ }).strict().optional(),
7774
+ developerHandoff: z4.object({
7775
+ findings: z4.array(z4.object({ id: z4.string().min(1), description: z4.string().min(1) }).strict()),
7776
+ failingChecks: z4.array(z4.string().min(1))
6784
7777
  }).strict().optional(),
6785
7778
  publicationExpectedBase: z4.string().regex(/^[0-9a-f]{40}$/).nullable().optional(),
6786
7779
  taskStartedAt: isoTimestamp.optional(),
@@ -6835,6 +7828,16 @@ var ResolutionRecordSchema = z4.object({
6835
7828
  authenticatedFrom: z4.string().min(1),
6836
7829
  consumedAt: isoTimestamp
6837
7830
  }).strict();
7831
+ var ExecutionRoundMirrorRecordSchema = z4.object({
7832
+ version: z4.literal(1),
7833
+ kind: z4.literal("execution_round"),
7834
+ task: taskId,
7835
+ repository: z4.string().min(1),
7836
+ threadId: z4.string().min(1),
7837
+ checkpointId: z4.string().min(1),
7838
+ round: z4.number().int().positive(),
7839
+ recordedAt: isoTimestamp
7840
+ }).strict();
6838
7841
  // ../../packages/aeg-core/src/control-store/local.ts
6839
7842
  var CONTROL_AREA_DIRNAME = "control";
6840
7843
  // src/commands/doctrine.ts
@@ -6864,6 +7867,13 @@ function packageRoot(moduleUrl) {
6864
7867
  import matter2 from "gray-matter";
6865
7868
  // ../../packages/aeg-core/src/docs/surfaced-manifest.ts
6866
7869
  var NO_MODEL_BACKED_PATHS = new Set;
7870
+ // ../../packages/aeg-core/src/docs/published-prose.ts
7871
+ var ALLOWED_MECHANICS = rulesForGroup("published-prose")[0]?.exemptions ?? [];
7872
+ var PROSE_RULES = rulesForGroup("published-prose").map((rule) => ({
7873
+ id: rule.id,
7874
+ what: rule.message,
7875
+ pattern: rule.patterns.published
7876
+ }));
6867
7877
  // ../../packages/sources/src/commands.ts
6868
7878
  var COMMANDS = [
6869
7879
  {
@@ -6978,6 +7988,16 @@ var COMMANDS = [
6978
7988
  ],
6979
7989
  status: "shipped"
6980
7990
  },
7991
+ {
7992
+ name: "new adr",
7993
+ needs: [],
7994
+ description: "Write the next numbered decision record into the folder decisionRecords.path names",
7995
+ details: [
7996
+ "`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.",
7997
+ "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."
7998
+ ],
7999
+ status: "shipped"
8000
+ },
6981
8001
  {
6982
8002
  name: "brief render",
6983
8003
  needs: ["forge", "default-branch"],
@@ -6996,9 +8016,7 @@ var COMMANDS = [
6996
8016
  name: "task dispatch",
6997
8017
  needs: ["forge", "operator-seat"],
6998
8018
  description: "Deprecated — render, pin, and post the brief on the Issue as the frozen original; start the developer",
6999
- flags: [
7000
- { flag: "--agent <claude|codex|gemini>", description: "Start the developer through dispatchRole once posted" }
7001
- ],
8019
+ flags: [{ flag: "--agent <claude|codex>", description: "Start the developer through dispatchRole once posted" }],
7002
8020
  details: [
7003
8021
  "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.",
7004
8022
  "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.",
@@ -7023,7 +8041,11 @@ var COMMANDS = [
7023
8041
  description: "One command from a planned Issue to a reviewed pull request — exactly one developer started",
7024
8042
  flags: [
7025
8043
  {
7026
- flag: "--agent <claude|codex|gemini>",
8044
+ flag: "--runner <standalone|atta-engine>",
8045
+ description: "Override runner config for this invocation; absent uses config, whose default is standalone"
8046
+ },
8047
+ {
8048
+ flag: "--agent <claude|codex>",
7027
8049
  description: "Vendor for the developer and both reviewers this run dispatches"
7028
8050
  },
7029
8051
  {
@@ -7033,17 +8055,39 @@ var COMMANDS = [
7033
8055
  {
7034
8056
  flag: "--widen-surface <glob,...> --reason <text>",
7035
8057
  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"
8058
+ },
8059
+ {
8060
+ flag: "--rollback",
8061
+ 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`"
7036
8062
  }
7037
8063
  ],
7038
8064
  details: [
8065
+ "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.",
8066
+ "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.",
8067
+ "`--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.",
7039
8068
  "`--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.",
7040
- "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.",
8069
+ "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.",
7041
8070
  "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.",
7042
8071
  "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.",
7043
8072
  "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`)."
7044
8073
  ],
7045
8074
  status: "shipped"
7046
8075
  },
8076
+ {
8077
+ name: "task switch",
8078
+ needs: ["forge"],
8079
+ description: "Change a task's agent or model by setting its Engine checkpoint aside, so the next `task run` is accepted",
8080
+ flags: [
8081
+ { flag: "--issue <n>", description: "Address the task by its Issue number instead of `<tranche> <n>`" },
8082
+ { flag: "--agent <claude|codex>", description: "Vendor the next `task run` of the task continues on" },
8083
+ { flag: "--model <model>", description: "Model the next `task run` is meant to use; absent, the vendor default" }
8084
+ ],
8085
+ details: [
8086
+ "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.",
8087
+ "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."
8088
+ ],
8089
+ status: "shipped"
8090
+ },
7047
8091
  {
7048
8092
  name: "task status",
7049
8093
  needs: ["forge"],
@@ -7198,6 +8242,22 @@ var COMMANDS = [
7198
8242
  ],
7199
8243
  status: "shipped"
7200
8244
  },
8245
+ {
8246
+ name: "pr snapshot",
8247
+ needs: ["forge"],
8248
+ description: "CI plumbing: write a run's forge snapshot of the pull request and its task Issue, read over REST",
8249
+ flags: [
8250
+ {
8251
+ flag: "--dir",
8252
+ description: "The snapshot directory; its `raw/` holds the REST pull request and comment pages the read step wrote"
8253
+ }
8254
+ ],
8255
+ details: [
8256
+ "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.",
8257
+ "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."
8258
+ ],
8259
+ status: "shipped"
8260
+ },
7201
8261
  {
7202
8262
  name: "issue create",
7203
8263
  needs: ["forge"],
@@ -7318,14 +8378,14 @@ var COMMANDS = [
7318
8378
  {
7319
8379
  name: "milestone close",
7320
8380
  needs: ["forge"],
7321
- description: "Close a tranche's Milestone after verifying every labeled Issue is actually attached",
8381
+ description: "Close a tranche's Milestone after verifying every labeled Issue is attached and every tranche it declares is complete",
7322
8382
  flags: [
7323
8383
  { flag: "--slug", description: "The tranche whose Milestone is being closed" },
7324
8384
  { flag: "--validate-only", description: "Run every gate and report PASS without closing the Milestone" },
7325
8385
  { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
7326
8386
  ],
7327
8387
  details: [
7328
- "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."
8388
+ "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."
7329
8389
  ],
7330
8390
  status: "shipped"
7331
8391
  },
@@ -7614,7 +8674,7 @@ var COMMANDS = [
7614
8674
  }
7615
8675
  ],
7616
8676
  details: [
7617
- "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.",
8677
+ "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.",
7618
8678
  "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.",
7619
8679
  '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.'
7620
8680
  ],
@@ -7623,11 +8683,11 @@ var COMMANDS = [
7623
8683
  {
7624
8684
  name: "dispatch",
7625
8685
  needs: ["operator-seat"],
7626
- description: "Start a role's headless agent session (claude/codex/gemini) with attribution set on its environment, recording the outcome through the Vinaya Log",
8686
+ description: "Start a role's headless agent session (claude/codex) with attribution set on its environment, recording the outcome through the Vinaya Log",
7627
8687
  flags: [
7628
8688
  {
7629
8689
  flag: "--agent",
7630
- description: "Vendor to start: `claude`, `codex`, or `gemini` (falls back to `dispatch.agent` in config)"
8690
+ description: "Vendor to start: `claude` or `codex` (falls back to `dispatch.agent` in config)"
7631
8691
  },
7632
8692
  { flag: "--prompt-file", description: "Path to the prompt text sent to the agent (never on argv)" },
7633
8693
  { flag: "--task", description: "This dispatch's task Issue number — mutually exclusive with `--pr`" },
@@ -7644,9 +8704,9 @@ var COMMANDS = [
7644
8704
  ],
7645
8705
  details: [
7646
8706
  "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.",
7647
- "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`.",
8707
+ "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`.",
7648
8708
  "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.",
7649
- "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."
8709
+ "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."
7650
8710
  ],
7651
8711
  status: "shipped"
7652
8712
  },
@@ -7657,7 +8717,7 @@ var COMMANDS = [
7657
8717
  flags: [
7658
8718
  { flag: "--task <n>", description: "This task's Issue number — its frozen `aeg:brief:v1` comment is the brief" },
7659
8719
  {
7660
- flag: "--agent <claude|codex|gemini>",
8720
+ flag: "--agent <claude|codex>",
7661
8721
  description: "Vendor for every dispatch this loop makes (falls back to `dispatch.agent` in config)"
7662
8722
  },
7663
8723
  { flag: "--json", description: "Enveloped JSON output (schema: 1)" }
@@ -7744,32 +8804,323 @@ var StateSourceConfigSchema = z5.discriminatedUnion("kind", [
7744
8804
  // src/lib/config.ts
7745
8805
  import { execFile as execFile4, execFileSync as execFileSync2 } from "node:child_process";
7746
8806
  import { promisify as promisify4 } from "node:util";
7747
- import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync } from "node:fs";
8807
+ import { existsSync as existsSync2, lstatSync, mkdirSync, readFileSync as readFileSync2, realpathSync as realpathSync2, writeFileSync } from "node:fs";
7748
8808
  import { homedir } from "node:os";
7749
- import { dirname as dirname2, isAbsolute, join as join2, resolve } from "node:path";
7750
- import { z as z6 } from "zod";
8809
+ import { basename as basename3, dirname as dirname2, isAbsolute, join as join2, resolve } from "node:path";
8810
+ import { z as z7 } from "zod";
8811
+
8812
+ // src/checks/contract.ts
8813
+ var CHECK_SCHEMA_VERSION = 1;
8814
+ function emitCheckError(error) {
8815
+ process.stderr.write(`${JSON.stringify(error)}
8816
+ `);
8817
+ }
7751
8818
 
7752
8819
  // src/lib/agent-vendors.ts
7753
8820
  var AGENT_VENDORS = ["skills", "claude", "gemini"];
7754
8821
 
8822
+ // src/lib/prose-rules-config.ts
8823
+ import safeRegex from "safe-regex2";
8824
+ import { z as z6 } from "zod";
8825
+ var SEVERITIES = ["error", "warning"];
8826
+ var OVERRIDE_KEYS = ["scopes", "severity", "exempt"];
8827
+ var FIXED_DEFAULT_KEYS = ["pattern", "patterns", "flags", "means", "message", "id"];
8828
+ var CUSTOM_KEYS = ["id", "pattern", "patterns", "flags", "means", "scopes", "severity", "exempt"];
8829
+ var DEFAULT_IDS = new Set([...DEFAULT_PROSE_RULES.map((rule) => rule.id), DECISION_RECORD_CITATION_ID]);
8830
+ function isPlainObject3(value) {
8831
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8832
+ }
8833
+ function outsideRepositoryReason(entry) {
8834
+ if (entry.startsWith("/") || /^[A-Za-z]:/.test(entry))
8835
+ return "must be a repository-relative path, not an absolute one";
8836
+ if (entry.split(/[\\/]/).includes(".."))
8837
+ return "must stay inside the repository — no `..` segment";
8838
+ return null;
8839
+ }
8840
+ var RepoRelativePathSchema = z6.string().min(1).superRefine((entry, ctx) => {
8841
+ const reason = outsideRepositoryReason(entry);
8842
+ if (reason)
8843
+ ctx.addIssue({ code: z6.ZodIssueCode.custom, message: reason });
8844
+ });
8845
+ function pathListIssues(value, path, issues) {
8846
+ if (!Array.isArray(value)) {
8847
+ issues.push({ path, message: "must be a list of repository-relative paths" });
8848
+ return;
8849
+ }
8850
+ value.forEach((entry, index) => {
8851
+ if (typeof entry !== "string" || entry.length === 0) {
8852
+ issues.push({ path: [...path, index], message: "must be a non-empty repository-relative path" });
8853
+ return;
8854
+ }
8855
+ const reason = outsideRepositoryReason(entry);
8856
+ if (reason)
8857
+ issues.push({ path: [...path, index], message: reason });
8858
+ });
8859
+ }
8860
+ function scopeListIssues(value, path, allowed, issues) {
8861
+ if (!Array.isArray(value) || value.length === 0) {
8862
+ issues.push({ path, message: "must name at least one scope" });
8863
+ return null;
8864
+ }
8865
+ const scopes = [];
8866
+ value.forEach((scope, index) => {
8867
+ if (typeof scope !== "string" || !CONFIGURABLE_PROSE_SCOPES.includes(scope)) {
8868
+ issues.push({
8869
+ path: [...path, index],
8870
+ 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(", ")}`
8871
+ });
8872
+ return;
8873
+ }
8874
+ if (!allowed.includes(scope)) {
8875
+ issues.push({
8876
+ path: [...path, index],
8877
+ message: `scope "${scope}" is not one this rule can run in — it can run in: ${allowed.join(", ")}`
8878
+ });
8879
+ return;
8880
+ }
8881
+ scopes.push(scope);
8882
+ });
8883
+ return scopes;
8884
+ }
8885
+ function severityIssues(value, path, scopes, issues) {
8886
+ if (typeof value === "string") {
8887
+ if (!SEVERITIES.includes(value)) {
8888
+ issues.push({ path, message: `unknown severity ${JSON.stringify(value)} — use "error" or "warning"` });
8889
+ }
8890
+ return;
8891
+ }
8892
+ if (!isPlainObject3(value)) {
8893
+ issues.push({ path, message: 'must be "error", "warning", or a map from scope to one of them' });
8894
+ return;
8895
+ }
8896
+ for (const [scope, severity] of Object.entries(value)) {
8897
+ if (!scopes.includes(scope)) {
8898
+ issues.push({ path: [...path, scope], message: `names scope "${scope}", which this rule's scopes do not cover` });
8899
+ }
8900
+ if (typeof severity !== "string" || !SEVERITIES.includes(severity)) {
8901
+ issues.push({
8902
+ path: [...path, scope],
8903
+ message: `unknown severity ${JSON.stringify(severity)} — use "error" or "warning"`
8904
+ });
8905
+ }
8906
+ }
8907
+ }
8908
+ function patternIssues(source, flags, path, issues) {
8909
+ if (typeof source !== "string" || source.length === 0) {
8910
+ issues.push({ path, message: "must be a non-empty regular expression" });
8911
+ return;
8912
+ }
8913
+ if (source.length > CONFIGURED_PATTERN_MAX_LENGTH) {
8914
+ issues.push({
8915
+ path,
8916
+ message: `is ${source.length} characters, over the ${CONFIGURED_PATTERN_MAX_LENGTH}-character limit for a configured pattern`
8917
+ });
8918
+ return;
8919
+ }
8920
+ try {
8921
+ new RegExp(source, flags);
8922
+ } catch (err) {
8923
+ issues.push({ path, message: `does not compile: ${err.message}` });
8924
+ return;
8925
+ }
8926
+ if (!safeRegex(source, { limit: Number.MAX_SAFE_INTEGER })) {
8927
+ issues.push({
8928
+ path,
8929
+ 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."
8930
+ });
8931
+ }
8932
+ }
8933
+ function flagIssues(value, path, issues) {
8934
+ if (value === undefined)
8935
+ return "";
8936
+ if (typeof value !== "string") {
8937
+ issues.push({ path, message: 'must be a string of flags, e.g. "i"' });
8938
+ return "";
8939
+ }
8940
+ const seen = new Set;
8941
+ for (const flag of value) {
8942
+ if (!CONFIGURED_PROSE_FLAGS.includes(flag)) {
8943
+ issues.push({
8944
+ path,
8945
+ message: `unknown flag ${JSON.stringify(flag)} — only ${CONFIGURED_PROSE_FLAGS.map((f) => `"${f}"`).join(" and ")} are allowed`
8946
+ });
8947
+ return "";
8948
+ }
8949
+ if (seen.has(flag)) {
8950
+ issues.push({ path, message: `repeats the flag "${flag}"` });
8951
+ return "";
8952
+ }
8953
+ seen.add(flag);
8954
+ }
8955
+ return value;
8956
+ }
8957
+ function defaultsIssues(value, issues) {
8958
+ const base = ["defaults"];
8959
+ if (!isPlainObject3(value)) {
8960
+ issues.push({ path: base, message: 'must map a default rule id to "off" or an override' });
8961
+ return;
8962
+ }
8963
+ for (const [id, override] of Object.entries(value)) {
8964
+ const path = [...base, id];
8965
+ const rule = CONFIGURABLE_DEFAULT_RULES.find((candidate) => candidate.id === id);
8966
+ if (!rule) {
8967
+ issues.push({
8968
+ path,
8969
+ message: `unknown default rule id "${id}" — \`vinaya check --plan\` lists the rules each prose check runs`
8970
+ });
8971
+ continue;
8972
+ }
8973
+ if (override === "off")
8974
+ continue;
8975
+ if (!isPlainObject3(override)) {
8976
+ issues.push({ path, message: 'must be "off" or an object with any of scopes, severity, exempt' });
8977
+ continue;
8978
+ }
8979
+ for (const key of Object.keys(override)) {
8980
+ if (OVERRIDE_KEYS.includes(key))
8981
+ continue;
8982
+ issues.push({
8983
+ path: [...path, key],
8984
+ 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`
8985
+ });
8986
+ }
8987
+ const scopes = override.scopes === undefined ? [...rule.scopes] : scopeListIssues(override.scopes, [...path, "scopes"], allowedScopesFor(rule), issues);
8988
+ if (override.severity !== undefined && scopes)
8989
+ severityIssues(override.severity, [...path, "severity"], scopes, issues);
8990
+ if (override.exempt !== undefined)
8991
+ pathListIssues(override.exempt, [...path, "exempt"], issues);
8992
+ }
8993
+ }
8994
+ function customIssues(value, issues) {
8995
+ if (!Array.isArray(value)) {
8996
+ issues.push({ path: ["custom"], message: "must be a list of rules" });
8997
+ return;
8998
+ }
8999
+ const ids = new Set;
9000
+ value.forEach((rule, index) => {
9001
+ const path = ["custom", index];
9002
+ if (!isPlainObject3(rule)) {
9003
+ issues.push({ path, message: "must be a rule object" });
9004
+ return;
9005
+ }
9006
+ for (const key of Object.keys(rule)) {
9007
+ if (!CUSTOM_KEYS.includes(key)) {
9008
+ issues.push({ path: [...path, key], message: `unknown key "${key}" — a rule takes ${CUSTOM_KEYS.join(", ")}` });
9009
+ }
9010
+ }
9011
+ if (typeof rule.id !== "string" || rule.id.length === 0) {
9012
+ issues.push({ path: [...path, "id"], message: "a custom rule needs an id" });
9013
+ } else if (DEFAULT_IDS.has(rule.id)) {
9014
+ issues.push({
9015
+ path: [...path, "id"],
9016
+ message: `"${rule.id}" is a default rule id — a custom rule needs its own id; retune the default under proseGates.rules.defaults instead`
9017
+ });
9018
+ } else if (ids.has(rule.id)) {
9019
+ issues.push({ path: [...path, "id"], message: `"${rule.id}" is used by an earlier custom rule` });
9020
+ } else {
9021
+ ids.add(rule.id);
9022
+ }
9023
+ if (typeof rule.means !== "string" || rule.means.trim().length === 0) {
9024
+ issues.push({ path: [...path, "means"], message: "a custom rule needs a message (`means`)" });
9025
+ }
9026
+ let scopes = null;
9027
+ if (rule.scopes === undefined) {
9028
+ issues.push({ path: [...path, "scopes"], message: "a custom rule needs at least one scope (`scopes`)" });
9029
+ } else {
9030
+ scopes = scopeListIssues(rule.scopes, [...path, "scopes"], CONFIGURABLE_PROSE_SCOPES, issues);
9031
+ }
9032
+ if (scopes && new Set(scopes.map(groupOfScope)).size > 1) {
9033
+ issues.push({
9034
+ path: [...path, "scopes"],
9035
+ 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'
9036
+ });
9037
+ }
9038
+ const flags = flagIssues(rule.flags, [...path, "flags"], issues);
9039
+ if (rule.pattern === undefined && rule.patterns === undefined) {
9040
+ issues.push({
9041
+ path: [...path, "pattern"],
9042
+ message: "a custom rule needs a `pattern` or a per-scope `patterns` map"
9043
+ });
9044
+ }
9045
+ if (rule.pattern !== undefined)
9046
+ patternIssues(rule.pattern, flags, [...path, "pattern"], issues);
9047
+ if (rule.patterns !== undefined) {
9048
+ if (!isPlainObject3(rule.patterns)) {
9049
+ issues.push({ path: [...path, "patterns"], message: "must map a scope to a regular expression" });
9050
+ } else {
9051
+ for (const [scope, source] of Object.entries(rule.patterns)) {
9052
+ if (scopes && !scopes.includes(scope)) {
9053
+ issues.push({
9054
+ path: [...path, "patterns", scope],
9055
+ message: `names scope "${scope}", which this rule's scopes do not cover`
9056
+ });
9057
+ continue;
9058
+ }
9059
+ patternIssues(source, flags, [...path, "patterns", scope], issues);
9060
+ }
9061
+ if (rule.pattern === undefined && scopes) {
9062
+ for (const scope of scopes) {
9063
+ if (!(scope in rule.patterns)) {
9064
+ issues.push({
9065
+ path: [...path, "patterns"],
9066
+ message: `has no pattern for scope "${scope}" — add one, or a \`pattern\` every other scope uses`
9067
+ });
9068
+ }
9069
+ }
9070
+ }
9071
+ }
9072
+ }
9073
+ if (rule.severity !== undefined && scopes)
9074
+ severityIssues(rule.severity, [...path, "severity"], scopes, issues);
9075
+ if (rule.exempt !== undefined)
9076
+ pathListIssues(rule.exempt, [...path, "exempt"], issues);
9077
+ });
9078
+ }
9079
+ function proseRulesIssues(value) {
9080
+ const issues = [];
9081
+ if (!isPlainObject3(value))
9082
+ return [{ path: [], message: "must be an object with any of exempt, defaults, custom" }];
9083
+ for (const key of Object.keys(value)) {
9084
+ if (!["exempt", "defaults", "custom"].includes(key)) {
9085
+ issues.push({ path: [key], message: `unknown key "${key}" — proseGates.rules takes exempt, defaults and custom` });
9086
+ }
9087
+ }
9088
+ if (value.exempt !== undefined)
9089
+ pathListIssues(value.exempt, ["exempt"], issues);
9090
+ if (value.defaults !== undefined)
9091
+ defaultsIssues(value.defaults, issues);
9092
+ if (value.custom !== undefined)
9093
+ customIssues(value.custom, issues);
9094
+ return issues;
9095
+ }
9096
+ var ProseRulesSchema = z6.unknown().superRefine((value, ctx) => {
9097
+ for (const issue of proseRulesIssues(value)) {
9098
+ ctx.addIssue({ code: z6.ZodIssueCode.custom, path: issue.path, message: issue.message });
9099
+ }
9100
+ }).transform((value) => value);
9101
+ var PublishedProseSchema = z6.object({
9102
+ allow: z6.array(z6.string().min(1)).optional()
9103
+ }).strict();
9104
+
7755
9105
  // src/lib/config.ts
7756
- var EnvEntrySchema = z6.union([
7757
- z6.literal(true),
7758
- z6.object({ optional: z6.literal(true) }),
7759
- z6.object({ anyOf: z6.array(z6.string()).min(2) }),
7760
- z6.string()
9106
+ var EnvEntrySchema = z7.union([
9107
+ z7.literal(true),
9108
+ z7.object({ optional: z7.literal(true) }),
9109
+ z7.object({ anyOf: z7.array(z7.string()).min(2) }),
9110
+ z7.string()
7761
9111
  ]);
7762
- var CheckEntrySchema = z6.object({
7763
- run: z6.string(),
7764
- scope: z6.enum(["diff", "full"]),
7765
- include: z6.array(z6.string()).optional(),
7766
- args: z6.array(z6.string()).optional(),
7767
- timeoutMs: z6.number().optional(),
7768
- env: z6.record(z6.string(), EnvEntrySchema).optional(),
7769
- requiresOpenPr: z6.boolean().optional(),
7770
- ownWorkflow: z6.boolean().optional(),
7771
- principalOwed: z6.literal(true).optional(),
7772
- validates: z6.enum(["body", "issue"]).optional()
9112
+ var CheckEntrySchema = z7.object({
9113
+ run: z7.string(),
9114
+ scope: z7.enum(["diff", "full"]),
9115
+ include: z7.array(z7.string()).optional(),
9116
+ args: z7.array(z7.string()).optional(),
9117
+ timeoutMs: z7.number().optional(),
9118
+ env: z7.record(z7.string(), EnvEntrySchema).optional(),
9119
+ requiresOpenPr: z7.boolean().optional(),
9120
+ ownWorkflow: z7.boolean().optional(),
9121
+ principalOwed: z7.literal(true).optional(),
9122
+ validates: z7.enum(["body", "issue"]).optional(),
9123
+ advisory: z7.literal(true).optional()
7773
9124
  }).superRefine((entry, ctx) => {
7774
9125
  if (!entry.env)
7775
9126
  return;
@@ -7779,22 +9130,22 @@ var CheckEntrySchema = z6.object({
7779
9130
  const members = value.anyOf;
7780
9131
  if (new Set(members).size !== members.length) {
7781
9132
  ctx.addIssue({
7782
- code: z6.ZodIssueCode.custom,
9133
+ code: z7.ZodIssueCode.custom,
7783
9134
  message: `env.${key}.anyOf has duplicate members`,
7784
9135
  path: ["env", key, "anyOf"]
7785
9136
  });
7786
9137
  }
7787
9138
  if (!members.includes(key)) {
7788
9139
  ctx.addIssue({
7789
- code: z6.ZodIssueCode.custom,
9140
+ code: z7.ZodIssueCode.custom,
7790
9141
  message: `env.${key}.anyOf must include "${key}" itself as a member`,
7791
9142
  path: ["env", key, "anyOf"]
7792
9143
  });
7793
9144
  }
7794
9145
  }
7795
9146
  });
7796
- var RoleEntrySchema = z6.object({
7797
- contract: z6.string().refine((p) => p.includes("/"), {
9147
+ var RoleEntrySchema = z7.object({
9148
+ contract: z7.string().refine((p) => p.includes("/"), {
7798
9149
  message: 'must be a path (contain at least one "/"), not a bare filename'
7799
9150
  })
7800
9151
  });
@@ -7818,17 +9169,17 @@ var BRIEF_BUILTINS = [
7818
9169
  "briefSections",
7819
9170
  "milestoneShape"
7820
9171
  ];
7821
- var BriefSectionSchema = z6.union([
7822
- z6.object({ builtin: z6.enum(BRIEF_BUILTINS) }),
7823
- z6.object({ heading: z6.string().min(1), name: z6.string().optional() }),
7824
- z6.object({ field: z6.string().min(1), name: z6.string().optional() }),
7825
- z6.object({ phrase: z6.string().min(1), name: z6.string().optional() })
9172
+ var BriefSectionSchema = z7.union([
9173
+ z7.object({ builtin: z7.enum(BRIEF_BUILTINS) }),
9174
+ z7.object({ heading: z7.string().min(1), name: z7.string().optional() }),
9175
+ z7.object({ field: z7.string().min(1), name: z7.string().optional() }),
9176
+ z7.object({ phrase: z7.string().min(1), name: z7.string().optional() })
7826
9177
  ]);
7827
- var BriefSchemaSchema = z6.object({
7828
- pr: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
7829
- issue: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
7830
- milestone: z6.object({ sections: z6.array(BriefSectionSchema) }).optional(),
7831
- ack: z6.array(z6.enum(BRIEF_BUILTINS)).optional()
9178
+ var BriefSchemaSchema = z7.object({
9179
+ pr: z7.object({ sections: z7.array(BriefSectionSchema) }).optional(),
9180
+ issue: z7.object({ sections: z7.array(BriefSectionSchema) }).optional(),
9181
+ milestone: z7.object({ sections: z7.array(BriefSectionSchema) }).optional(),
9182
+ ack: z7.array(z7.enum(BRIEF_BUILTINS)).optional()
7832
9183
  });
7833
9184
  function isSafeRepoRelPath(p) {
7834
9185
  if (p.length === 0)
@@ -7837,7 +9188,7 @@ function isSafeRepoRelPath(p) {
7837
9188
  return false;
7838
9189
  return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
7839
9190
  }
7840
- var SafeRepoRelPath = z6.string().refine(isSafeRepoRelPath, {
9191
+ var SafeRepoRelPath = z7.string().refine(isSafeRepoRelPath, {
7841
9192
  message: "must be a repo-root-relative path with no `..` segment or absolute root"
7842
9193
  });
7843
9194
  var CANONICAL_HOOK_BLOCK_PREFIXES = [".git/", ".husky/", ".vinaya/hooks/", ".claude/hooks/"];
@@ -7847,22 +9198,22 @@ function isCanonicalHookBlockPath(p) {
7847
9198
  var ManagedHookBlockPath = SafeRepoRelPath.refine(isCanonicalHookBlockPath, {
7848
9199
  message: `must start with one of ${CANONICAL_HOOK_BLOCK_PREFIXES.join(", ")} (byte-exact, case-sensitive)`
7849
9200
  });
7850
- var ManagedBlockRecordSchema = z6.object({
9201
+ var ManagedBlockRecordSchema = z7.object({
7851
9202
  path: ManagedHookBlockPath,
7852
- marker: z6.string(),
7853
- comment: z6.enum(["hash", "html"])
9203
+ marker: z7.string(),
9204
+ comment: z7.enum(["hash", "html"])
7854
9205
  });
7855
- var ManagedManifestSchema = z6.object({
7856
- version: z6.number().int().positive(),
7857
- files: z6.array(SafeRepoRelPath),
7858
- blocks: z6.array(ManagedBlockRecordSchema),
7859
- labels: z6.array(z6.string()),
7860
- agents: z6.array(z6.enum(AGENT_VENDORS)).optional()
9206
+ var ManagedManifestSchema = z7.object({
9207
+ version: z7.number().int().positive(),
9208
+ files: z7.array(SafeRepoRelPath),
9209
+ blocks: z7.array(ManagedBlockRecordSchema),
9210
+ labels: z7.array(z7.string()),
9211
+ agents: z7.array(z7.enum(AGENT_VENDORS)).optional()
7861
9212
  });
7862
- var ProjectEntrySchema = z6.object({
7863
- name: z6.string().min(1),
7864
- description: z6.string().min(1).optional(),
7865
- path: z6.string().min(1).optional()
9213
+ var ProjectEntrySchema = z7.object({
9214
+ name: z7.string().min(1),
9215
+ description: z7.string().min(1).optional(),
9216
+ path: z7.string().min(1).optional()
7866
9217
  });
7867
9218
  function parseTokensCollectDeclaration(value) {
7868
9219
  const m = value.trim().match(/^(\S+)\s+(\S+)$/);
@@ -7873,90 +9224,101 @@ function parseTokensCollectDeclaration(value) {
7873
9224
  return null;
7874
9225
  return { interpreter, script };
7875
9226
  }
7876
- var VinayaConfigSchema = z6.object({
7877
- rings: z6.object({
7878
- ring1_forgeWriteInterception: z6.boolean(),
7879
- ring2_asyncAudits: z6.boolean()
9227
+ var VinayaConfigObjectSchema = z7.object({
9228
+ rings: z7.object({
9229
+ ring1_forgeWriteInterception: z7.boolean(),
9230
+ ring2_asyncAudits: z7.boolean()
7880
9231
  }).optional(),
7881
- checks: z6.record(z6.string(), CheckEntrySchema).optional(),
7882
- roles: z6.record(z6.string(), RoleEntrySchema).optional(),
9232
+ checks: z7.record(z7.string(), CheckEntrySchema).optional(),
9233
+ roles: z7.record(z7.string(), RoleEntrySchema).optional(),
7883
9234
  briefSchema: BriefSchemaSchema.optional(),
7884
9235
  managed: ManagedManifestSchema.optional(),
7885
- principals: z6.array(z6.string()).min(1).optional(),
7886
- releaseActor: z6.string().min(1).optional(),
7887
- ci: z6.object({ setup: z6.string().min(1) }).optional(),
7888
- tokens: z6.object({
7889
- collect: z6.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
9236
+ principals: z7.array(z7.string()).min(1).optional(),
9237
+ releaseActor: z7.string().min(1).optional(),
9238
+ ci: z7.object({ setup: z7.string().min(1) }).optional(),
9239
+ tokens: z7.object({
9240
+ collect: z7.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
7890
9241
  message: 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
7891
9242
  })
7892
9243
  }).optional(),
7893
- blastRadius: z6.object({ extraDomains: z6.array(z6.string()).optional() }).optional(),
7894
- proseGates: z6.object({
7895
- doctrineRoot: z6.string().min(1).optional(),
7896
- readerFacingPrefix: z6.string().min(1).optional(),
7897
- readerFacingSuffix: z6.string().min(1).optional(),
7898
- legacySlugDir: z6.string().min(1).optional(),
7899
- sourceComments: z6.object({
7900
- globs: z6.array(z6.string().min(1)).optional(),
7901
- allowlist: z6.array(z6.string().min(1)).optional(),
7902
- severity: z6.enum(["warning", "error"]).optional()
9244
+ blastRadius: z7.object({ extraDomains: z7.array(z7.string()).optional() }).optional(),
9245
+ proseGates: z7.object({
9246
+ doctrineRoot: z7.string().min(1).optional(),
9247
+ readerFacingPrefix: z7.string().min(1).optional(),
9248
+ readerFacingSuffix: z7.string().min(1).optional(),
9249
+ legacySlugDir: z7.string().min(1).optional(),
9250
+ sourceComments: z7.object({
9251
+ globs: z7.array(z7.string().min(1)).optional(),
9252
+ allowlist: z7.array(z7.string().min(1)).optional(),
9253
+ severity: z7.enum(["warning", "error"]).optional()
7903
9254
  }).optional(),
7904
- specGrandfather: z6.union([z6.array(z6.string().min(1)), z6.record(z6.string().min(1), z6.number().int().min(0))]).optional(),
7905
- specPaths: z6.array(z6.string().min(1).refine((entry) => !entry.startsWith("/") && !/^[A-Za-z]:/.test(entry), {
7906
- message: "must be a repository-relative path, not an absolute one"
7907
- }).refine((entry) => !entry.split(/[\\/]/).includes(".."), {
7908
- message: "must stay inside the repository — no `..` segment"
7909
- })).optional()
9255
+ specGrandfather: z7.union([z7.array(z7.string().min(1)), z7.record(z7.string().min(1), z7.number().int().min(0))]).optional(),
9256
+ specPaths: z7.array(RepoRelativePathSchema).optional(),
9257
+ productPaths: z7.array(RepoRelativePathSchema).optional(),
9258
+ published: PublishedProseSchema.optional(),
9259
+ rules: ProseRulesSchema.optional()
7910
9260
  }).optional(),
7911
- projects: z6.array(ProjectEntrySchema).optional(),
7912
- dispatch: z6.object({
7913
- timeoutMs: z6.number().int().positive().optional(),
7914
- killGraceMs: z6.number().int().positive().optional(),
7915
- agent: z6.enum(["claude", "codex", "gemini"]).optional()
9261
+ projects: z7.array(ProjectEntrySchema).optional(),
9262
+ dispatch: z7.object({
9263
+ timeoutMs: z7.number().int().positive().optional(),
9264
+ reviewerTimeoutMs: z7.number().int().positive().optional(),
9265
+ killGraceMs: z7.number().int().positive().optional(),
9266
+ agent: z7.enum(["claude", "codex"]).optional()
7916
9267
  }).optional(),
7917
- reviewPolicy: z6.object({
7918
- codeReviewThreshold: z6.string().min(1).optional(),
7919
- securityThreshold: z6.string().min(1).optional(),
7920
- maxRounds: z6.number().optional(),
7921
- maxTaskMinutes: z6.number().optional()
9268
+ reviewPolicy: z7.object({
9269
+ codeReviewThreshold: z7.string().min(1).optional(),
9270
+ securityThreshold: z7.string().min(1).optional(),
9271
+ maxRounds: z7.number().optional(),
9272
+ maxTaskMinutes: z7.number().optional(),
9273
+ readyPushTimeoutMinutes: z7.number().optional()
7922
9274
  }).optional(),
7923
- securityScan: z6.object({
7924
- command: z6.array(z6.string().min(1)).min(1)
9275
+ securityScan: z7.object({
9276
+ command: z7.array(z7.string().min(1)).min(1)
7925
9277
  }).optional(),
7926
- gateCutovers: z6.object({
7927
- objectivesSinceIssue: z6.number().int().nonnegative().optional(),
7928
- briefSectionsSinceIssue: z6.number().int().nonnegative().optional(),
7929
- documentationSinceIssue: z6.number().int().nonnegative().optional(),
7930
- briefRulesSincePr: z6.number().int().nonnegative().optional(),
7931
- agentBoxesRefusedSincePr: z6.number().int().nonnegative().optional()
9278
+ gateCutovers: z7.object({
9279
+ objectivesSinceIssue: z7.number().int().nonnegative().optional(),
9280
+ briefSectionsSinceIssue: z7.number().int().nonnegative().optional(),
9281
+ documentationSinceIssue: z7.number().int().nonnegative().optional(),
9282
+ briefRulesSincePr: z7.number().int().nonnegative().optional(),
9283
+ agentBoxesRefusedSincePr: z7.number().int().nonnegative().optional()
7932
9284
  }).optional(),
7933
- planning: z6.object({
7934
- collisionThreshold: z6.number().int().nonnegative().optional()
9285
+ planning: z7.object({
9286
+ collisionThreshold: z7.number().int().nonnegative().optional()
7935
9287
  }).optional(),
7936
- prePush: z6.object({
7937
- alwaysRun: z6.array(z6.string()).optional()
9288
+ prePush: z7.object({
9289
+ alwaysRun: z7.array(z7.string()).optional(),
9290
+ readyTests: z7.object({
9291
+ mode: z7.literal("ci"),
9292
+ workflow: z7.literal(".github/workflows/ci.yml"),
9293
+ check: z7.literal("Vinaya CI")
9294
+ }).strict().optional(),
9295
+ requiredCi: z7.object({
9296
+ workflow: z7.literal(".github/workflows/ci.yml"),
9297
+ check: z7.literal("Vinaya CI")
9298
+ }).strict().optional()
7938
9299
  }).optional(),
7939
- report: z6.object({
7940
- commandTimeoutMs: z6.number().int().positive().optional()
9300
+ report: z7.object({
9301
+ commandTimeoutMs: z7.number().int().positive().optional()
7941
9302
  }).superRefine((report, ctx) => {
7942
9303
  const commandTimeoutMs = report.commandTimeoutMs;
7943
9304
  if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
7944
9305
  ctx.addIssue({
7945
- code: z6.ZodIssueCode.custom,
9306
+ code: z7.ZodIssueCode.custom,
7946
9307
  path: ["commandTimeoutMs"],
7947
9308
  message: "must be at most 3600000 (1 hour)"
7948
9309
  });
7949
9310
  }
7950
9311
  }).optional(),
7951
- logPublish: z6.unknown().refine((v) => v === undefined, {
9312
+ logPublish: z7.unknown().refine((v) => v === undefined, {
7952
9313
  message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
7953
9314
  }),
7954
- runtimeDir: z6.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
7955
- logs: z6.object({
7956
- folder: z6.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
7957
- url: z6.string().url().optional(),
7958
- headers: z6.record(z6.string()).optional(),
7959
- readHeaders: z6.record(z6.string()).optional(),
9315
+ runtimeDir: z7.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
9316
+ runner: z7.enum(["standalone", "atta-engine"]).optional(),
9317
+ logs: z7.object({
9318
+ folder: z7.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
9319
+ url: z7.string().url().optional(),
9320
+ headers: z7.record(z7.string()).optional(),
9321
+ readHeaders: z7.record(z7.string()).optional(),
7960
9322
  events: CustomEventDeclarationsSchema.optional()
7961
9323
  }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
7962
9324
  message: "logs: set at most one of folder/url"
@@ -7964,8 +9326,33 @@ var VinayaConfigSchema = z6.object({
7964
9326
  message: "logs: headers requires url"
7965
9327
  }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
7966
9328
  message: "logs: readHeaders requires url"
7967
- }).optional()
9329
+ }).or(z7.literal(false)).optional(),
9330
+ decisionRecords: z7.object({
9331
+ path: RepoRelativePathSchema
9332
+ }).strict().optional()
7968
9333
  });
9334
+ function decisionRecordsPathIssue(path, doctrineRoot) {
9335
+ const reason = outsideRepositoryReason(path);
9336
+ if (reason)
9337
+ return reason;
9338
+ const folder = normalizeSpecPath(path);
9339
+ if (folder === "" || folder === ".")
9340
+ return "must name a folder, not the repository root";
9341
+ const root = normalizeSpecPath(doctrineRoot ?? "aeg-root");
9342
+ if (folder === root || folder.startsWith(`${root}/`)) {
9343
+ return `must be outside the doctrine tree "${root}" — decision records belong to this repository, not to the doctrine it ships`;
9344
+ }
9345
+ return null;
9346
+ }
9347
+ var VinayaConfigSchema = VinayaConfigObjectSchema.superRefine((config, ctx) => {
9348
+ const path = config.decisionRecords?.path;
9349
+ if (path === undefined || outsideRepositoryReason(path))
9350
+ return;
9351
+ const issue = decisionRecordsPathIssue(path, config.proseGates?.doctrineRoot);
9352
+ if (issue)
9353
+ ctx.addIssue({ code: z7.ZodIssueCode.custom, path: ["decisionRecords", "path"], message: issue });
9354
+ });
9355
+ var VinayaConfigShape = VinayaConfigObjectSchema.shape;
7969
9356
  var GLOBAL_VINAYA_HOME = join2(homedir(), ".vinaya");
7970
9357
  var GLOBAL_CONFIG_PATH = join2(GLOBAL_VINAYA_HOME, "config.json");
7971
9358
  var LOCAL_CONFIG_FILENAME = "vinaya.config.json";
@@ -8046,9 +9433,6 @@ function stripGlobalOnlyKeys(config, path) {
8046
9433
  }
8047
9434
  return result;
8048
9435
  }
8049
- function resolvePrincipalAllowlist(config) {
8050
- return config?.principals ?? PRINCIPAL_ALLOWLIST;
8051
- }
8052
9436
  function resolveReleaseActor(config) {
8053
9437
  return config?.releaseActor ?? DEFAULT_RELEASE_ACTOR;
8054
9438
  }
@@ -8072,13 +9456,19 @@ function resolveReviewPolicy(config) {
8072
9456
  if (!Number.isInteger(maxTaskMinutes) || maxTaskMinutes < 0) {
8073
9457
  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.`);
8074
9458
  }
9459
+ const readyPushTimeoutMinutes = raw.readyPushTimeoutMinutes ?? DEFAULT_READY_PUSH_TIMEOUT_MINUTES;
9460
+ if (!Number.isInteger(readyPushTimeoutMinutes) || readyPushTimeoutMinutes < 1) {
9461
+ throw new Error(`vinaya.config.json: reviewPolicy.readyPushTimeoutMinutes "${readyPushTimeoutMinutes}" is not a positive integer — fix the config, this never falls back to a default.`);
9462
+ }
8075
9463
  return {
8076
9464
  codeReviewThreshold,
8077
9465
  securityThreshold,
8078
9466
  maxRounds,
8079
- maxTaskMinutes
9467
+ maxTaskMinutes,
9468
+ readyPushTimeoutMinutes
8080
9469
  };
8081
9470
  }
9471
+ var emittedLocalOverrideWarnings = new Set;
8082
9472
  function resolveGateCutovers(config) {
8083
9473
  const raw = config?.gateCutovers;
8084
9474
  if (!raw)
@@ -8184,13 +9574,14 @@ function readTrustAnchorConfigAtRef(ref) {
8184
9574
  });
8185
9575
  return Buffer.from(raw, "utf-8").toString("base64");
8186
9576
  }
9577
+ var NO_TRUST_ANCHOR_REPO_MESSAGE = "could not resolve repo identity for the trust-anchor read";
8187
9578
  function ghFetchTrustAnchorConfig() {
8188
9579
  const probeRef = resolveCiTrustAnchorProbeRef();
8189
9580
  if (probeRef)
8190
9581
  return readTrustAnchorConfigAtRef(probeRef);
8191
9582
  const repo = trustAnchorRepo();
8192
9583
  if (!repo)
8193
- throw new Error("could not resolve repo identity for the trust-anchor read");
9584
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
8194
9585
  return execFileSync2("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], {
8195
9586
  encoding: "utf-8",
8196
9587
  stdio: ["ignore", "pipe", "pipe"]
@@ -8207,7 +9598,7 @@ async function ghFetchTrustAnchorConfigAsync() {
8207
9598
  }
8208
9599
  const repo = await trustAnchorRepoAsync();
8209
9600
  if (!repo)
8210
- throw new Error("could not resolve repo identity for the trust-anchor read");
9601
+ throw new Error(NO_TRUST_ANCHOR_REPO_MESSAGE);
8211
9602
  const { stdout } = await execFileAsync4("gh", ["api", `repos/${repo}/contents/${LOCAL_CONFIG_FILENAME}`, "--jq", ".content"], { encoding: "utf-8", timeout: 1e4, killSignal: "SIGKILL" });
8212
9603
  return stdout;
8213
9604
  }
@@ -8233,6 +9624,47 @@ function loadTrustAnchorConfig(fetcher = ghFetchTrustAnchorConfig) {
8233
9624
  }
8234
9625
  return parseTrustAnchorContent(base64);
8235
9626
  }
9627
+ class PrincipalsUnresolvedError extends Error {
9628
+ kind;
9629
+ constructor(kind, message) {
9630
+ super(message);
9631
+ this.name = "PrincipalsUnresolvedError";
9632
+ this.kind = kind;
9633
+ }
9634
+ }
9635
+ var PRINCIPALS_FIX = 'add "principals": [...] to vinaya.config.json on the default branch';
9636
+ function fetchFailureReason(err) {
9637
+ const stderr = err?.stderr;
9638
+ const text = (typeof stderr === "string" ? stderr : stderr?.toString() ?? "").trim();
9639
+ return text.split(`
9640
+ `)[0]?.trim() || firstLine(err);
9641
+ }
9642
+ function principalsNotConfigured(why) {
9643
+ return new PrincipalsUnresolvedError("not-configured", `no Principal is configured (${why}) — ${PRINCIPALS_FIX}.`);
9644
+ }
9645
+ function resolveTrustedPrincipals(fetcher = ghFetchTrustAnchorConfig) {
9646
+ let content;
9647
+ try {
9648
+ content = fetcher();
9649
+ } catch (err) {
9650
+ if (err?.message === NO_TRUST_ANCHOR_REPO_MESSAGE) {
9651
+ throw principalsNotConfigured("no repository resolves for the read");
9652
+ }
9653
+ if (isMissingFileError(err))
9654
+ throw principalsNotConfigured("the default branch has no vinaya.config.json");
9655
+ throw new PrincipalsUnresolvedError("read-failed", `could not read "principals" from vinaya.config.json on the default branch: ${fetchFailureReason(err)}`);
9656
+ }
9657
+ const unusable = { why: "" };
9658
+ const config = parseTrustAnchorContent(content, (why) => {
9659
+ unusable.why = why;
9660
+ });
9661
+ if (config === null) {
9662
+ throw principalsNotConfigured(`vinaya.config.json on the default branch ${unusable.why ? `is unusable: ${unusable.why}` : "is empty"}`);
9663
+ }
9664
+ if (!config.principals)
9665
+ throw principalsNotConfigured('vinaya.config.json on the default branch sets no "principals"');
9666
+ return config.principals;
9667
+ }
8236
9668
  async function loadTrustAnchorConfigAsync(fetcher = ghFetchTrustAnchorConfigAsync, options = {}) {
8237
9669
  const warn = options.quiet ? () => {} : warnTrustAnchorFallback;
8238
9670
  let base64;
@@ -8272,12 +9704,67 @@ function loadConfig() {
8272
9704
  const path = configPath();
8273
9705
  if (!path)
8274
9706
  return null;
9707
+ let text;
8275
9708
  try {
8276
- const raw = JSON.parse(readFileSync2(path, "utf-8"));
8277
- return stripGlobalOnlyKeys(VinayaConfigSchema.parse(raw), path);
8278
- } catch {
9709
+ text = readFileSync2(path, "utf-8");
9710
+ } catch (err) {
9711
+ reportInvalidConfigOnce(path, `unreadable: ${err.message}`);
8279
9712
  return null;
8280
9713
  }
9714
+ let raw;
9715
+ try {
9716
+ raw = JSON.parse(text);
9717
+ } catch (err) {
9718
+ reportInvalidConfigOnce(path, `invalid JSON: ${err.message}`);
9719
+ return null;
9720
+ }
9721
+ const parsed = VinayaConfigSchema.safeParse(raw);
9722
+ if (!parsed.success) {
9723
+ reportInvalidConfigOnce(path, schemaIssueDetail(parsed.error));
9724
+ return null;
9725
+ }
9726
+ return stripGlobalOnlyKeys(parsed.data, path);
9727
+ }
9728
+ function schemaIssueDetail(error) {
9729
+ return error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
9730
+ }
9731
+ var emittedInvalidConfigReports = new Set;
9732
+ function reportInvalidConfigOnce(path, detail) {
9733
+ const key = `${path}
9734
+ ${detail}`;
9735
+ if (emittedInvalidConfigReports.has(key))
9736
+ return;
9737
+ emittedInvalidConfigReports.add(key);
9738
+ const message = `${path} is not a valid Vinaya configuration (${detail}) — falling back to built-in defaults.`;
9739
+ const checkName = process.env.VINAYA_CHECK_NAME;
9740
+ if (checkName) {
9741
+ emitCheckError({
9742
+ schema: CHECK_SCHEMA_VERSION,
9743
+ check: checkName,
9744
+ severity: "warning",
9745
+ message,
9746
+ agent_recovery_prompt: `Fix the failing keys in ${path} (${detail}) so the file parses and satisfies the configuration schema, then re-run.`,
9747
+ file: path
9748
+ });
9749
+ return;
9750
+ }
9751
+ console.error(`⚠ ${message}`);
9752
+ }
9753
+ function loadConfigChecked() {
9754
+ const path = configPath();
9755
+ if (!path)
9756
+ return { ok: true, config: null };
9757
+ let raw;
9758
+ try {
9759
+ raw = JSON.parse(readFileSync2(path, "utf-8"));
9760
+ } catch (err) {
9761
+ return { ok: false, path, error: `invalid JSON: ${err.message}` };
9762
+ }
9763
+ const parsed = VinayaConfigSchema.safeParse(raw);
9764
+ if (!parsed.success) {
9765
+ return { ok: false, path, error: schemaIssueDetail(parsed.error) };
9766
+ }
9767
+ return { ok: true, config: stripGlobalOnlyKeys(parsed.data, path) };
8281
9768
  }
8282
9769
  var TOKENS_COLLECT_TRUST_PATH = join2(GLOBAL_VINAYA_HOME, "tokens-collect-trust.json");
8283
9770
 
@@ -8314,19 +9801,123 @@ function hasDoctrineEntry(root) {
8314
9801
  return existsSync3(join3(root, ...ENTRY_SEGMENTS));
8315
9802
  }
8316
9803
 
8317
- // src/checks/contract.ts
8318
- var CHECK_SCHEMA_VERSION = 1;
8319
- function emitCheckError(error) {
8320
- process.stderr.write(`${JSON.stringify(error)}
8321
- `);
8322
- }
8323
-
8324
9804
  // src/lib/diff-evidence.ts
8325
9805
  import { execFileSync as execFileSync8 } from "node:child_process";
8326
- import { join as join9, relative as relative2, resolve as resolve2 } from "node:path";
9806
+ import { join as join10, relative as relative2, resolve as resolve2 } from "node:path";
8327
9807
 
8328
9808
  // src/lib/forge-read.ts
8329
9809
  import { execFileSync as execFileSync4 } from "node:child_process";
9810
+
9811
+ // src/lib/forge-snapshot.ts
9812
+ import { existsSync as existsSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "node:fs";
9813
+ import { join as join4 } from "node:path";
9814
+ var FORGE_SNAPSHOT_DIR_ENV = "VINAYA_FORGE_SNAPSHOT_DIR";
9815
+ var PULL_FILE = "pull.json";
9816
+ var PULL_COMMENTS_FILE = "pull-comments.json";
9817
+ var ISSUE_FILE = "issue.json";
9818
+ var ISSUE_COMMENTS_FILE = "issue-comments.json";
9819
+ function forgeSnapshotDir(env = process.env) {
9820
+ if (env.GITHUB_ACTIONS !== "true")
9821
+ return null;
9822
+ const dir = env[FORGE_SNAPSHOT_DIR_ENV];
9823
+ return dir ? dir : null;
9824
+ }
9825
+
9826
+ class ForgeSnapshotIncompleteError extends Error {
9827
+ constructor(dir, file) {
9828
+ 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.`);
9829
+ this.name = "ForgeSnapshotIncompleteError";
9830
+ }
9831
+ }
9832
+
9833
+ class ForgeSnapshotIssueNotFoundError extends Error {
9834
+ constructor(issue) {
9835
+ super(`Issue #${issue} did not resolve (HTTP 404) when this run's forge snapshot was read.`);
9836
+ this.name = "ForgeSnapshotIssueNotFoundError";
9837
+ }
9838
+ }
9839
+ function readSnapshotFile(dir, file) {
9840
+ let text;
9841
+ try {
9842
+ text = readFileSync4(join4(dir, file), "utf8");
9843
+ } catch {
9844
+ throw new ForgeSnapshotIncompleteError(dir, file);
9845
+ }
9846
+ return JSON.parse(text);
9847
+ }
9848
+ function readComments(dir, file, number) {
9849
+ const parsed = readSnapshotFile(dir, file);
9850
+ if (parsed.number !== number)
9851
+ throw new ForgeSnapshotIncompleteError(dir, `${file} for #${number}`);
9852
+ return parsed.comments;
9853
+ }
9854
+ function snapshotPullRequest(number, env = process.env) {
9855
+ const dir = forgeSnapshotDir(env);
9856
+ if (dir === null)
9857
+ return null;
9858
+ const pull = readSnapshotFile(dir, PULL_FILE);
9859
+ return pull.number === number ? pull : null;
9860
+ }
9861
+ function snapshotIssue(number, env = process.env) {
9862
+ const dir = forgeSnapshotDir(env);
9863
+ if (dir === null)
9864
+ return null;
9865
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
9866
+ if (issue.number !== number)
9867
+ return null;
9868
+ if ("notFound" in issue)
9869
+ throw new ForgeSnapshotIssueNotFoundError(number);
9870
+ return issue;
9871
+ }
9872
+ function snapshotComments(number, env = process.env) {
9873
+ const dir = forgeSnapshotDir(env);
9874
+ if (dir === null)
9875
+ return null;
9876
+ if (snapshotPullRequest(number, env) !== null)
9877
+ return readComments(dir, PULL_COMMENTS_FILE, number);
9878
+ if (snapshotIssue(number, env) !== null)
9879
+ return readComments(dir, ISSUE_COMMENTS_FILE, number);
9880
+ return null;
9881
+ }
9882
+ function snapshotBody(number, env = process.env) {
9883
+ const pull = snapshotPullRequest(number, env);
9884
+ if (pull !== null)
9885
+ return pull.body;
9886
+ return snapshotIssue(number, env)?.body ?? null;
9887
+ }
9888
+ function incompleteForgeSnapshot(env = process.env) {
9889
+ const dir = forgeSnapshotDir(env);
9890
+ if (dir === null)
9891
+ return null;
9892
+ for (const file of [PULL_FILE, PULL_COMMENTS_FILE, ISSUE_FILE]) {
9893
+ if (!existsSync4(join4(dir, file)))
9894
+ return new ForgeSnapshotIncompleteError(dir, file).message;
9895
+ }
9896
+ try {
9897
+ const issue = readSnapshotFile(dir, ISSUE_FILE);
9898
+ if (typeof issue.number === "number" && !("notFound" in issue) && !existsSync4(join4(dir, ISSUE_COMMENTS_FILE))) {
9899
+ return new ForgeSnapshotIncompleteError(dir, ISSUE_COMMENTS_FILE).message;
9900
+ }
9901
+ } catch (err) {
9902
+ return `the forge snapshot ${dir} has an unreadable ${ISSUE_FILE}: ${err.message}`;
9903
+ }
9904
+ return null;
9905
+ }
9906
+ function exitOnIncompleteForgeSnapshot(checkName, env = process.env) {
9907
+ const reason = incompleteForgeSnapshot(env);
9908
+ if (reason === null)
9909
+ return;
9910
+ emitCheckError({
9911
+ schema: CHECK_SCHEMA_VERSION,
9912
+ check: checkName,
9913
+ severity: "error",
9914
+ message: `${checkName}: ${reason}`,
9915
+ 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.`
9916
+ });
9917
+ process.exit(1);
9918
+ }
9919
+
9920
+ // src/lib/forge-read.ts
8330
9921
  var FORGE_READ_CEILING_BYTES = 64 * 1024 * 1024;
8331
9922
  var PAGE_SIZE = 100;
8332
9923
  var ghRunner = (args, maxBuffer) => execFileSync4("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer });
@@ -8349,7 +9940,7 @@ function isForgeReadOversize(err) {
8349
9940
  function isBufferOverflow(err) {
8350
9941
  return err?.code === "ENOBUFS";
8351
9942
  }
8352
- function run2(runner, args, subject, usedBytes) {
9943
+ function runBounded(runner, args, subject, usedBytes) {
8353
9944
  const remaining = FORGE_READ_CEILING_BYTES - usedBytes;
8354
9945
  let out;
8355
9946
  try {
@@ -8364,31 +9955,40 @@ function run2(runner, args, subject, usedBytes) {
8364
9955
  throw new ForgeReadOversizeError(subject, usedBytes + size);
8365
9956
  return out;
8366
9957
  }
8367
- function readIssueComments(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
8368
- const number = resolveNumber(issue, subjectLabel, runner);
8369
- const comments = [];
9958
+ function readRestCommentRows(number, subjectLabel = `Issue ${number}`, runner = ghRunner) {
9959
+ const rows = [];
8370
9960
  let used = 0;
8371
9961
  for (let page = 1;; page++) {
8372
- const out = run2(runner, ["api", `repos/{owner}/{repo}/issues/${number}/comments?per_page=${PAGE_SIZE}&page=${page}`], subjectLabel, used);
9962
+ const out = runBounded(runner, ["api", `repos/{owner}/{repo}/issues/${number}/comments?per_page=${PAGE_SIZE}&page=${page}`], subjectLabel, used);
8373
9963
  used += Buffer.byteLength(out, "utf8");
8374
- const rows = JSON.parse(out);
8375
- for (const r of rows) {
8376
- comments.push({
8377
- body: r.body ?? "",
8378
- url: r.html_url ?? "",
8379
- author: r.user?.login ? { login: r.user.login } : null
8380
- });
8381
- }
8382
- if (rows.length < PAGE_SIZE)
8383
- return comments;
9964
+ const pageRows = JSON.parse(out);
9965
+ rows.push(...pageRows);
9966
+ if (pageRows.length < PAGE_SIZE)
9967
+ return rows;
8384
9968
  }
8385
9969
  }
9970
+ function readIssueComments(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
9971
+ const number = resolveNumber(issue, subjectLabel, runner);
9972
+ const fromSnapshot = snapshotComments(number);
9973
+ if (fromSnapshot !== null)
9974
+ return fromSnapshot;
9975
+ return readRestCommentRows(number, subjectLabel, runner).map((r) => ({
9976
+ body: r.body ?? "",
9977
+ url: r.html_url ?? "",
9978
+ author: r.user?.login ? { login: r.user.login } : null
9979
+ }));
9980
+ }
8386
9981
  function readIssueBody(issue, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
8387
- const out = run2(runner, ["issue", "view", String(issue), "--json", "body"], subjectLabel, 0);
9982
+ if (forgeSnapshotDir() !== null) {
9983
+ const fromSnapshot = snapshotBody(resolveNumber(issue, subjectLabel, runner));
9984
+ if (fromSnapshot !== null)
9985
+ return fromSnapshot;
9986
+ }
9987
+ const out = runBounded(runner, ["issue", "view", String(issue), "--json", "body"], subjectLabel, 0);
8388
9988
  return JSON.parse(out).body ?? "";
8389
9989
  }
8390
9990
  function readIssueFields(issue, fields, subjectLabel = `Issue ${issue}`, runner = ghRunner) {
8391
- return JSON.parse(run2(runner, ["issue", "view", String(issue), "--json", fields], subjectLabel, 0));
9991
+ return JSON.parse(runBounded(runner, ["issue", "view", String(issue), "--json", fields], subjectLabel, 0));
8392
9992
  }
8393
9993
  function resolveNumber(issue, subjectLabel, runner) {
8394
9994
  if (typeof issue === "number")
@@ -8400,20 +10000,76 @@ function resolveNumber(issue, subjectLabel, runner) {
8400
10000
 
8401
10001
  // src/lib/brief-assembly.ts
8402
10002
  import { execFileSync as execFileSync6 } from "node:child_process";
8403
- import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync2 } from "node:fs";
8404
- import { join as join4 } from "node:path";
10003
+ import { existsSync as existsSync5, readFileSync as readFileSync5, readdirSync as readdirSync2 } from "node:fs";
10004
+ import { join as join5 } from "node:path";
8405
10005
 
8406
10006
  // src/checks/edge-resolve.ts
10007
+ import { execFile as execFile5 } from "node:child_process";
10008
+ import { promisify as promisify5 } from "node:util";
10009
+
10010
+ // src/lib/github-rate-limit.ts
8407
10011
  import { execFileSync as execFileSync5 } from "node:child_process";
10012
+ var GITHUB_RATE_LIMIT_WORDING = /api rate limit (?:already )?exceeded|secondary rate limit|rate limit exceeded/i;
10013
+ var SECONDARY_RATE_LIMIT_WORDING = /secondary rate limit/i;
10014
+ function isGithubRateLimitError(text) {
10015
+ return GITHUB_RATE_LIMIT_WORDING.test(text);
10016
+ }
10017
+ function rateLimitBudget(errorText) {
10018
+ return errorText.trimStart().startsWith("GraphQL:") ? "GraphQL" : "REST";
10019
+ }
10020
+ var defaultReader = () => execFileSync5("gh", ["api", "rate_limit"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
10021
+ function readRateLimitReset(budget, read = defaultReader) {
10022
+ let parsed;
10023
+ try {
10024
+ parsed = JSON.parse(read());
10025
+ } catch {
10026
+ return null;
10027
+ }
10028
+ const resources = parsed.resources;
10029
+ const entry = resources?.[budget === "GraphQL" ? "graphql" : "core"];
10030
+ if (!entry || typeof entry.reset !== "number" || !Number.isFinite(entry.reset) || entry.reset <= 0)
10031
+ return null;
10032
+ if (typeof entry.remaining === "number" && entry.remaining > 0)
10033
+ return null;
10034
+ return entry.reset;
10035
+ }
10036
+ function formatResetUtc(epochSeconds) {
10037
+ const d = new Date(epochSeconds * 1000);
10038
+ const hh = String(d.getUTCHours()).padStart(2, "0");
10039
+ const mm = String(d.getUTCMinutes()).padStart(2, "0");
10040
+ return `${hh}:${mm} UTC`;
10041
+ }
10042
+ function rateLimitMessage(errorText, read = defaultReader) {
10043
+ const budget = rateLimitBudget(errorText);
10044
+ const reset = SECONDARY_RATE_LIMIT_WORDING.test(errorText) ? null : readRateLimitReset(budget, read);
10045
+ const when = reset === null ? "resets in a few minutes" : `resets at ${formatResetUtc(reset)}`;
10046
+ return `GitHub rate limit (${budget}), ${when}`;
10047
+ }
10048
+ function execErrorText(err) {
10049
+ const e = err;
10050
+ const stderr = e?.stderr === undefined || e.stderr === null ? "" : String(e.stderr);
10051
+ const message = typeof e?.message === "string" ? e.message : "";
10052
+ return stderr.trim() !== "" ? `${stderr}
10053
+ ${message}` : message;
10054
+ }
10055
+
10056
+ // src/checks/edge-resolve.ts
8408
10057
  var DIRECT_ISSUE_REF = /#(\d+)/;
8409
10058
  var issueCache = new Map;
10059
+ var execFileAsync5 = promisify5(execFile5);
10060
+ var ISSUE_NOT_FOUND = /could not resolve to an issue/i;
8410
10061
  function fetchIssueState(num, repo) {
8411
10062
  const key = `${repo.owner}/${repo.repo}#${num}`;
8412
- if (issueCache.has(key))
8413
- return issueCache.get(key) ?? null;
8414
- let out = null;
10063
+ const cached = issueCache.get(key);
10064
+ if (cached)
10065
+ return cached;
10066
+ const out = readIssueOnce(num, repo).then((first) => first.readFailed ? readIssueOnce(num, repo) : first);
10067
+ issueCache.set(key, out);
10068
+ return out;
10069
+ }
10070
+ async function readIssueOnce(num, repo) {
8415
10071
  try {
8416
- const raw = execFileSync5("gh", [
10072
+ const { stdout } = await execFileAsync5("gh", [
8417
10073
  "issue",
8418
10074
  "view",
8419
10075
  String(num),
@@ -8421,13 +10077,11 @@ function fetchIssueState(num, repo) {
8421
10077
  `${repo.owner}/${repo.repo}`,
8422
10078
  "--json",
8423
10079
  "state,stateReason,closedByPullRequestsReferences"
8424
- ], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
8425
- out = JSON.parse(raw);
8426
- } catch {
8427
- out = null;
10080
+ ], { encoding: "utf8" });
10081
+ return { json: JSON.parse(stdout), readFailed: false };
10082
+ } catch (err) {
10083
+ return { json: null, readFailed: !ISSUE_NOT_FOUND.test(execErrorText(err)) };
8428
10084
  }
8429
- issueCache.set(key, out);
8430
- return out;
8431
10085
  }
8432
10086
  var defaultResolveSiblingTranche = async (slug, repo) => {
8433
10087
  let tranche;
@@ -8444,7 +10098,7 @@ var defaultResolveSiblingTranche = async (slug, repo) => {
8444
10098
  };
8445
10099
  };
8446
10100
  var siblingTrancheCache = new Map;
8447
- function edgeFromIssueJson(num, json) {
10101
+ function edgeFromIssueJson(num, json, readFailed = false) {
8448
10102
  if (json === null) {
8449
10103
  return {
8450
10104
  issue: num,
@@ -8453,7 +10107,8 @@ function edgeFromIssueJson(num, json) {
8453
10107
  issueState: null,
8454
10108
  stateReason: null,
8455
10109
  closedByActor: null,
8456
- resolved: true
10110
+ resolved: true,
10111
+ ...readFailed ? { readFailed: true } : {}
8457
10112
  };
8458
10113
  }
8459
10114
  const state = json.state === "CLOSED" ? "closed" : json.state === "OPEN" ? "open" : null;
@@ -8486,7 +10141,8 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
8486
10141
  const direct = id.match(DIRECT_ISSUE_REF);
8487
10142
  if (direct) {
8488
10143
  const num = Number(direct[1]);
8489
- return edgeFromIssueJson(num, fetchIssueState(num, repo));
10144
+ const read = await fetchIssueState(num, repo);
10145
+ return edgeFromIssueJson(num, read.json, read.readFailed);
8490
10146
  }
8491
10147
  const qualified = splitSlugQualifiedEdge(id);
8492
10148
  if (qualified) {
@@ -8520,11 +10176,23 @@ async function resolveEdge(id, taskById, factsByTaskId, repo, resolveSibling = d
8520
10176
  resolved: false
8521
10177
  };
8522
10178
  }
10179
+ function dependsOnFactFromEdge(id, r) {
10180
+ return {
10181
+ id,
10182
+ issue: r.issue,
10183
+ merged: r.merged,
10184
+ resolved: r.resolved,
10185
+ issueState: r.issueState,
10186
+ stateReason: r.stateReason,
10187
+ closedByActor: r.closedByActor,
10188
+ ...r.readFailed ? { readFailed: true } : {}
10189
+ };
10190
+ }
8523
10191
 
8524
10192
  // src/lib/brief-assembly.ts
8525
10193
  var PACKAGE_ROOT = packageRoot(import.meta.url);
8526
- var PACKAGED_TEMPLATE_PATH = join4(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
8527
- var TEMPLATE_PATH = existsSync4(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join4(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
10194
+ var PACKAGED_TEMPLATE_PATH = join5(PACKAGE_ROOT, "aeg-root", "templates", "brief-template.md");
10195
+ var TEMPLATE_PATH = existsSync5(PACKAGED_TEMPLATE_PATH) ? PACKAGED_TEMPLATE_PATH : join5(PACKAGE_ROOT, "..", "..", "aeg-root", "templates", "brief-template.md");
8528
10196
  function git(args) {
8529
10197
  try {
8530
10198
  return execFileSync6("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
@@ -8540,24 +10208,25 @@ function expandGlob(glob) {
8540
10208
  var DRAFT_ISSUE_SENTINEL = Number.MAX_SAFE_INTEGER;
8541
10209
 
8542
10210
  // src/checks/registry.ts
8543
- import { join as join5, relative, sep as sep2 } from "node:path";
10211
+ import { join as join6, relative, sep as sep2 } from "node:path";
8544
10212
  import { fileURLToPath as fileURLToPath3 } from "node:url";
8545
10213
  function resolveCheckBin(packageDir, moduleUrl) {
8546
10214
  const fromPackage = relative(packageDir, fileURLToPath3(moduleUrl));
8547
10215
  const bundled = fromPackage === "dist" || fromPackage.startsWith(`dist${sep2}`);
8548
- return bundled ? { dir: join5(packageDir, "dist", "checks", "bin"), ext: ".js" } : { dir: join5(packageDir, "src", "checks", "bin"), ext: ".ts" };
10216
+ return bundled ? { dir: join6(packageDir, "dist", "checks", "bin"), ext: ".js" } : { dir: join6(packageDir, "src", "checks", "bin"), ext: ".ts" };
8549
10217
  }
8550
10218
  var CHECK_BIN = resolveCheckBin(packageRoot(import.meta.url), import.meta.url);
8551
10219
  var BIN_DIR = CHECK_BIN.dir;
8552
10220
  var BIN_EXT = CHECK_BIN.ext;
8553
10221
  function bin(name) {
8554
- return join5(BIN_DIR, `${name}${BIN_EXT}`);
10222
+ return join6(BIN_DIR, `${name}${BIN_EXT}`);
8555
10223
  }
8556
10224
  var REGISTRY = [
8557
10225
  [
8558
10226
  {
8559
10227
  name: "brief-shape",
8560
10228
  validates: "body",
10229
+ requiresOpenPr: true,
8561
10230
  run: bin("check-brief-shape"),
8562
10231
  scope: "diff",
8563
10232
  timeoutMs: 15000,
@@ -8566,7 +10235,9 @@ var REGISTRY = [
8566
10235
  BRANCH: { optional: true },
8567
10236
  PR_NUMBER: { optional: true },
8568
10237
  GITHUB_TOKEN: { optional: true },
8569
- GH_TOKEN: { optional: true }
10238
+ GH_TOKEN: { optional: true },
10239
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10240
+ GITHUB_ACTIONS: { optional: true }
8570
10241
  }
8571
10242
  },
8572
10243
  0
@@ -8575,6 +10246,7 @@ var REGISTRY = [
8575
10246
  {
8576
10247
  name: "pr-report-density",
8577
10248
  validates: "body",
10249
+ requiresOpenPr: true,
8578
10250
  run: bin("check-pr-report-density"),
8579
10251
  scope: "diff",
8580
10252
  timeoutMs: 15000,
@@ -8600,7 +10272,9 @@ var REGISTRY = [
8600
10272
  PR_NUMBER: { optional: true },
8601
10273
  GITHUB_REPOSITORY: { optional: true },
8602
10274
  GITHUB_TOKEN: { optional: true },
8603
- GH_TOKEN: { optional: true }
10275
+ GH_TOKEN: { optional: true },
10276
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10277
+ GITHUB_ACTIONS: { optional: true }
8604
10278
  }
8605
10279
  },
8606
10280
  0
@@ -8624,6 +10298,7 @@ var REGISTRY = [
8624
10298
  {
8625
10299
  name: "pr-premise-reassert",
8626
10300
  validates: "body",
10301
+ requiresOpenPr: true,
8627
10302
  run: bin("check-pr-premise-reassert"),
8628
10303
  scope: "diff",
8629
10304
  timeoutMs: 15000,
@@ -8644,7 +10319,9 @@ var REGISTRY = [
8644
10319
  BRANCH: { optional: true },
8645
10320
  GITHUB_TOKEN: { optional: true },
8646
10321
  GH_TOKEN: { optional: true },
8647
- PREMISE_FILE: { optional: true }
10322
+ PREMISE_FILE: { optional: true },
10323
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10324
+ GITHUB_ACTIONS: { optional: true }
8648
10325
  }
8649
10326
  },
8650
10327
  0
@@ -8696,7 +10373,9 @@ var REGISTRY = [
8696
10373
  PR_BODY: { optional: true },
8697
10374
  PR_BODY_FILE: { optional: true },
8698
10375
  GITHUB_TOKEN: { optional: true },
8699
- GH_TOKEN: { optional: true }
10376
+ GH_TOKEN: { optional: true },
10377
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10378
+ GITHUB_ACTIONS: { optional: true }
8700
10379
  }
8701
10380
  },
8702
10381
  1
@@ -8712,7 +10391,13 @@ var REGISTRY = [
8712
10391
  principalOwed: true,
8713
10392
  env: {
8714
10393
  PR_BODY: { optional: true },
8715
- BRANCH: { optional: true }
10394
+ BRANCH: { optional: true },
10395
+ PULL_REQUEST_HEAD_SHA: { optional: true },
10396
+ GITHUB_REPOSITORY: { optional: true },
10397
+ GITHUB_TOKEN: { optional: true },
10398
+ GH_TOKEN: { optional: true },
10399
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10400
+ GITHUB_ACTIONS: { optional: true }
8716
10401
  }
8717
10402
  },
8718
10403
  1
@@ -8728,7 +10413,13 @@ var REGISTRY = [
8728
10413
  ownWorkflow: true,
8729
10414
  env: {
8730
10415
  PR_BODY: { optional: true },
8731
- BRANCH: { optional: true }
10416
+ BRANCH: { optional: true },
10417
+ PULL_REQUEST_HEAD_SHA: { optional: true },
10418
+ GITHUB_REPOSITORY: { optional: true },
10419
+ GITHUB_TOKEN: { optional: true },
10420
+ GH_TOKEN: { optional: true },
10421
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10422
+ GITHUB_ACTIONS: { optional: true }
8732
10423
  }
8733
10424
  },
8734
10425
  1
@@ -8747,7 +10438,9 @@ var REGISTRY = [
8747
10438
  PR_NUMBER: { optional: true },
8748
10439
  GITHUB_REPOSITORY: { optional: true },
8749
10440
  GITHUB_TOKEN: { optional: true },
8750
- GH_TOKEN: { optional: true }
10441
+ GH_TOKEN: { optional: true },
10442
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10443
+ GITHUB_ACTIONS: { optional: true }
8751
10444
  }
8752
10445
  },
8753
10446
  1
@@ -8787,7 +10480,9 @@ var REGISTRY = [
8787
10480
  PR_NUMBER: { optional: true },
8788
10481
  GITHUB_REPOSITORY: { optional: true },
8789
10482
  GITHUB_TOKEN: { optional: true },
8790
- GH_TOKEN: { optional: true }
10483
+ GH_TOKEN: { optional: true },
10484
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10485
+ GITHUB_ACTIONS: { optional: true }
8791
10486
  }
8792
10487
  },
8793
10488
  1
@@ -8840,12 +10535,15 @@ var REGISTRY = [
8840
10535
  {
8841
10536
  name: "doc-coverage-push",
8842
10537
  validates: "body",
10538
+ advisory: true,
8843
10539
  run: bin("check-doc-coverage-push"),
8844
10540
  scope: "diff",
8845
10541
  timeoutMs: 15000,
8846
10542
  env: {
8847
10543
  OVERRIDE_DOCS: { optional: true },
8848
10544
  BASE_SHA: { optional: true },
10545
+ GIT_INDEX_FILE: { optional: true },
10546
+ VINAYA_COMMIT_HOOK: { optional: true },
8849
10547
  PR_BODY: { optional: true },
8850
10548
  PR_BODY_FILE: { optional: true },
8851
10549
  PR_LABELS: { optional: true },
@@ -8857,21 +10555,6 @@ var REGISTRY = [
8857
10555
  },
8858
10556
  0
8859
10557
  ],
8860
- [
8861
- {
8862
- name: "issue-assignment",
8863
- run: bin("check-issue-assignment"),
8864
- scope: "full",
8865
- timeoutMs: 30000,
8866
- env: {
8867
- AEG_REPO: { optional: true },
8868
- BRANCH: { optional: true },
8869
- GITHUB_TOKEN: { optional: true },
8870
- GH_TOKEN: { optional: true }
8871
- }
8872
- },
8873
- 0
8874
- ],
8875
10558
  [
8876
10559
  {
8877
10560
  name: "evidence-fresh",
@@ -8885,7 +10568,9 @@ var REGISTRY = [
8885
10568
  PR_BODY: { optional: true },
8886
10569
  BASE_SHA: { optional: true },
8887
10570
  GITHUB_TOKEN: { optional: true },
8888
- GH_TOKEN: { optional: true }
10571
+ GH_TOKEN: { optional: true },
10572
+ VINAYA_FORGE_SNAPSHOT_DIR: { optional: true },
10573
+ GITHUB_ACTIONS: { optional: true }
8889
10574
  }
8890
10575
  },
8891
10576
  1
@@ -8896,7 +10581,11 @@ var REGISTRY = [
8896
10581
  run: bin("check-reader-resolvable-prose"),
8897
10582
  scope: "full",
8898
10583
  timeoutMs: 30000,
8899
- env: {},
10584
+ env: {
10585
+ BASE_SHA: { optional: true },
10586
+ GIT_INDEX_FILE: { optional: true },
10587
+ VINAYA_COMMIT_HOOK: { optional: true }
10588
+ },
8900
10589
  include: [
8901
10590
  "aeg-root/**/*.md",
8902
10591
  "apps/cli/src/**",
@@ -8914,7 +10603,11 @@ var REGISTRY = [
8914
10603
  run: bin("check-retired-vocabulary"),
8915
10604
  scope: "full",
8916
10605
  timeoutMs: 30000,
8917
- env: {},
10606
+ env: {
10607
+ BASE_SHA: { optional: true },
10608
+ GIT_INDEX_FILE: { optional: true },
10609
+ VINAYA_COMMIT_HOOK: { optional: true }
10610
+ },
8918
10611
  include: ["aeg-root/**/*.md"]
8919
10612
  },
8920
10613
  0
@@ -8922,10 +10615,15 @@ var REGISTRY = [
8922
10615
  [
8923
10616
  {
8924
10617
  name: "doctrine-portability",
10618
+ advisory: true,
8925
10619
  run: bin("check-doctrine-portability"),
8926
10620
  scope: "full",
8927
10621
  timeoutMs: 30000,
8928
- env: { BASE_SHA: { optional: true } },
10622
+ env: {
10623
+ BASE_SHA: { optional: true },
10624
+ GIT_INDEX_FILE: { optional: true },
10625
+ VINAYA_COMMIT_HOOK: { optional: true }
10626
+ },
8929
10627
  include: ["aeg-root/**/*.md"]
8930
10628
  },
8931
10629
  0
@@ -8958,7 +10656,11 @@ var REGISTRY = [
8958
10656
  run: bin("check-exec-bits"),
8959
10657
  scope: "diff",
8960
10658
  timeoutMs: 30000,
8961
- env: {}
10659
+ env: {
10660
+ BASE_SHA: { optional: true },
10661
+ GIT_INDEX_FILE: { optional: true },
10662
+ VINAYA_COMMIT_HOOK: { optional: true }
10663
+ }
8962
10664
  },
8963
10665
  0
8964
10666
  ],
@@ -8968,17 +10670,26 @@ var REGISTRY = [
8968
10670
  run: bin("check-ci-shard-coverage"),
8969
10671
  scope: "diff",
8970
10672
  timeoutMs: 15000,
8971
- env: {}
10673
+ env: {
10674
+ BASE_SHA: { optional: true },
10675
+ GIT_INDEX_FILE: { optional: true },
10676
+ VINAYA_COMMIT_HOOK: { optional: true }
10677
+ }
8972
10678
  },
8973
10679
  0
8974
10680
  ],
8975
10681
  [
8976
10682
  {
8977
10683
  name: "workspace-escape",
10684
+ advisory: true,
8978
10685
  run: bin("check-workspace-escape"),
8979
10686
  scope: "full",
8980
10687
  timeoutMs: 30000,
8981
- env: {},
10688
+ env: {
10689
+ BASE_SHA: { optional: true },
10690
+ GIT_INDEX_FILE: { optional: true },
10691
+ VINAYA_COMMIT_HOOK: { optional: true }
10692
+ },
8982
10693
  include: ["aeg-root/**/*.md"]
8983
10694
  },
8984
10695
  0
@@ -8989,17 +10700,23 @@ var REGISTRY = [
8989
10700
  run: bin("check-changeset-coverage"),
8990
10701
  scope: "diff",
8991
10702
  timeoutMs: 15000,
8992
- env: {}
10703
+ env: {
10704
+ BASE_SHA: { optional: true },
10705
+ GIT_INDEX_FILE: { optional: true },
10706
+ VINAYA_COMMIT_HOOK: { optional: true }
10707
+ }
8993
10708
  },
8994
10709
  0
8995
10710
  ],
8996
10711
  [
8997
10712
  {
8998
10713
  name: "quoted-command",
10714
+ advisory: true,
8999
10715
  run: bin("check-quoted-command"),
9000
- scope: "diff",
10716
+ scope: "full",
9001
10717
  timeoutMs: 15000,
9002
- env: {}
10718
+ env: {},
10719
+ include: ["aeg-root/**/*.md"]
9003
10720
  },
9004
10721
  0
9005
10722
  ],
@@ -9007,7 +10724,7 @@ var REGISTRY = [
9007
10724
  {
9008
10725
  name: "main-branch-refusal",
9009
10726
  run: bin("check-main-branch-refusal"),
9010
- scope: "full",
10727
+ scope: "diff",
9011
10728
  timeoutMs: 15000,
9012
10729
  env: { VINAYA_PUSH_REFS: { optional: true } }
9013
10730
  },
@@ -9074,18 +10791,6 @@ var REGISTRY = [
9074
10791
  },
9075
10792
  1
9076
10793
  ],
9077
- [
9078
- {
9079
- name: "issue-tranche-label",
9080
- run: bin("check-issue-tranche-label"),
9081
- validates: "issue",
9082
- scope: "full",
9083
- ownWorkflow: true,
9084
- timeoutMs: 15000,
9085
- env: { ISSUE_BODY: { optional: true }, ISSUE_LABELS: { optional: true } }
9086
- },
9087
- 1
9088
- ],
9089
10794
  [
9090
10795
  {
9091
10796
  name: "issue-milestone-attach",
@@ -9109,30 +10814,30 @@ function coreCheckRegistry() {
9109
10814
  var CORE_CHECK_RING = Object.fromEntries(REGISTRY.map(([spec, ring]) => [spec.name, ring]));
9110
10815
 
9111
10816
  // src/lib/log-sink.ts
9112
- import { execFile as execFile5 } from "node:child_process";
10817
+ import { execFile as execFile6 } from "node:child_process";
9113
10818
  import { randomUUID as randomUUID2 } from "node:crypto";
9114
10819
  import {
9115
10820
  appendFileSync,
9116
10821
  closeSync as closeSync4,
9117
10822
  constants as fsConstants4,
9118
- existsSync as existsSync7,
10823
+ existsSync as existsSync8,
9119
10824
  fstatSync as fstatSync3,
9120
10825
  mkdirSync as mkdirSync4,
9121
- lstatSync as lstatSync2,
10826
+ lstatSync as lstatSync3,
9122
10827
  openSync as openSync4,
9123
- readFileSync as readFileSync7,
10828
+ readFileSync as readFileSync8,
9124
10829
  renameSync as renameSync2,
9125
- writeFileSync as writeFileSync3,
10830
+ writeFileSync as writeFileSync4,
9126
10831
  writeSync as writeSync3
9127
10832
  } from "node:fs";
9128
10833
  import { hostname as osHostname, homedir as homedir3 } from "node:os";
9129
- import { dirname as dirname7, join as join8 } from "node:path";
9130
- import { promisify as promisify5 } from "node:util";
10834
+ import { dirname as dirname7, join as join9 } from "node:path";
10835
+ import { promisify as promisify6 } from "node:util";
9131
10836
 
9132
10837
  // src/lib/run-paths.ts
9133
10838
  import { execFileSync as execFileSync7 } from "node:child_process";
9134
- import { chmodSync, existsSync as existsSync5, realpathSync as realpathSync3 } from "node:fs";
9135
- import { dirname as dirname4, join as join6, resolve as resolvePath } from "node:path";
10839
+ import { chmodSync, existsSync as existsSync6, realpathSync as realpathSync3 } from "node:fs";
10840
+ import { dirname as dirname4, join as join7, resolve as resolvePath } from "node:path";
9136
10841
  var TASKS_EXECUTION_DIRNAME = "tasks-execution";
9137
10842
  var RUN_AREA_DIRNAMES = {
9138
10843
  control: CONTROL_AREA_DIRNAME,
@@ -9151,7 +10856,7 @@ function repoSegment(repo) {
9151
10856
  return `${repo.owner}-${repo.repo}`;
9152
10857
  }
9153
10858
  function defaultRuntimeDir(repo, home = GLOBAL_VINAYA_HOME) {
9154
- return join6(home, "runtime", repoSegment(repo));
10859
+ return join7(home, "runtime", repoSegment(repo));
9155
10860
  }
9156
10861
  function resolveRuntimeDir(input) {
9157
10862
  const local = resolveRuntimeDirSetting(input.localConfig);
@@ -9172,27 +10877,27 @@ function isInsideRepo(candidate, repoRoot) {
9172
10877
  return target === root || target.startsWith(`${root}/`);
9173
10878
  }
9174
10879
  function runPath(runtimeDir, scope, location) {
9175
- const dir = join6(runtimeDir, TASKS_EXECUTION_DIRNAME, scopeSegment(scope));
10880
+ const dir = join7(runtimeDir, TASKS_EXECUTION_DIRNAME, scopeSegment(scope));
9176
10881
  switch (location.area) {
9177
10882
  case "task":
9178
- return location.file ? join6(dir, location.file) : dir;
10883
+ return location.file ? join7(dir, location.file) : dir;
9179
10884
  case "control": {
9180
- const controlDir = join6(dir, RUN_AREA_DIRNAMES.control);
9181
- return location.file ? join6(controlDir, location.file) : controlDir;
10885
+ const controlDir = join7(dir, RUN_AREA_DIRNAMES.control);
10886
+ return location.file ? join7(controlDir, location.file) : controlDir;
9182
10887
  }
9183
10888
  case "rounds":
9184
- return join6(dir, RUN_AREA_DIRNAMES.rounds);
10889
+ return join7(dir, RUN_AREA_DIRNAMES.rounds);
9185
10890
  case "round": {
9186
- const roundDir = join6(dir, RUN_AREA_DIRNAMES.rounds, String(location.round));
9187
- return location.file ? join6(roundDir, location.file) : roundDir;
10891
+ const roundDir = join7(dir, RUN_AREA_DIRNAMES.rounds, String(location.round));
10892
+ return location.file ? join7(roundDir, location.file) : roundDir;
9188
10893
  }
9189
10894
  case "developer": {
9190
- const developerDir = join6(dir, RUN_AREA_DIRNAMES.rounds, String(location.round), "developer");
9191
- return location.file ? join6(developerDir, location.file) : developerDir;
10895
+ const developerDir = join7(dir, RUN_AREA_DIRNAMES.rounds, String(location.round), "developer");
10896
+ return location.file ? join7(developerDir, location.file) : developerDir;
9192
10897
  }
9193
10898
  default: {
9194
- const areaDir = join6(dir, RUN_AREA_DIRNAMES[location.area]);
9195
- return location.file ? join6(areaDir, location.file) : areaDir;
10899
+ const areaDir = join7(dir, RUN_AREA_DIRNAMES[location.area]);
10900
+ return location.file ? join7(areaDir, location.file) : areaDir;
9196
10901
  }
9197
10902
  }
9198
10903
  }
@@ -9261,7 +10966,7 @@ function repoRootSync(start = process.cwd()) {
9261
10966
  return null;
9262
10967
  }
9263
10968
  for (;; ) {
9264
- if (existsSync5(join6(dir, ".git")))
10969
+ if (existsSync6(join7(dir, ".git")))
9265
10970
  return dir;
9266
10971
  const parent = dirname4(dir);
9267
10972
  if (parent === dir)
@@ -9305,11 +11010,11 @@ function runtimeDirForThisRepo() {
9305
11010
  import {
9306
11011
  closeSync as closeSync2,
9307
11012
  constants as fsConstants2,
9308
- existsSync as existsSync6,
11013
+ existsSync as existsSync7,
9309
11014
  fstatSync as fstatSync2,
9310
11015
  mkdirSync as mkdirSync2,
9311
11016
  openSync as openSync2,
9312
- readFileSync as readFileSync5,
11017
+ readFileSync as readFileSync6,
9313
11018
  readSync,
9314
11019
  statSync,
9315
11020
  writeSync
@@ -9342,21 +11047,21 @@ function appendLoopLogLine(path, line) {
9342
11047
  import {
9343
11048
  closeSync as closeSync3,
9344
11049
  constants as fsConstants3,
9345
- lstatSync,
11050
+ lstatSync as lstatSync2,
9346
11051
  mkdirSync as mkdirSync3,
9347
11052
  openSync as openSync3,
9348
11053
  linkSync,
9349
- readFileSync as readFileSync6,
11054
+ readFileSync as readFileSync7,
9350
11055
  renameSync,
9351
11056
  statSync as statSync2,
9352
11057
  unlinkSync,
9353
11058
  utimesSync,
9354
- writeFileSync as writeFileSync2,
11059
+ writeFileSync as writeFileSync3,
9355
11060
  writeSync as writeSync2
9356
11061
  } from "node:fs";
9357
11062
  import { randomUUID } from "node:crypto";
9358
11063
  import { homedir as homedir2 } from "node:os";
9359
- import { dirname as dirname6, join as join7 } from "node:path";
11064
+ import { dirname as dirname6, join as join8 } from "node:path";
9360
11065
  var MAX_WEBHOOK_BODY_BYTES = 5 * 1024 * 1024;
9361
11066
  var WEBHOOK_FETCH_TIMEOUT_MS = 30000;
9362
11067
  var SAFE_PATH_SEGMENT2 = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
@@ -9437,7 +11142,7 @@ function acquireDrainLock(lockPath) {
9437
11142
  function renewDrainLock(lockPath, token) {
9438
11143
  let holder;
9439
11144
  try {
9440
- holder = readFileSync6(lockPath, "utf8").trim();
11145
+ holder = readFileSync7(lockPath, "utf8").trim();
9441
11146
  } catch (err) {
9442
11147
  if (!isEnoent(err))
9443
11148
  throw err;
@@ -9457,7 +11162,7 @@ function renewDrainLock(lockPath, token) {
9457
11162
  }
9458
11163
  function releaseDrainLock(lockPath, token) {
9459
11164
  try {
9460
- const holder = readFileSync6(lockPath, "utf8").trim();
11165
+ const holder = readFileSync7(lockPath, "utf8").trim();
9461
11166
  if (holder !== token)
9462
11167
  return;
9463
11168
  unlinkSync(lockPath);
@@ -9507,13 +11212,13 @@ function queueLines(buf) {
9507
11212
  return lines;
9508
11213
  }
9509
11214
  function removeQueueHead(path, cut) {
9510
- const remaining = readFileSync6(path);
9511
- writeFileSync2(path, remaining.subarray(Math.min(cut, remaining.byteLength)));
11215
+ const remaining = readFileSync7(path);
11216
+ writeFileSync3(path, remaining.subarray(Math.min(cut, remaining.byteLength)));
9512
11217
  }
9513
11218
  function queueBucketSize(path) {
9514
11219
  let lstat;
9515
11220
  try {
9516
- lstat = lstatSync(path);
11221
+ lstat = lstatSync2(path);
9517
11222
  } catch (err) {
9518
11223
  if (!isEnoent(err))
9519
11224
  throw err;
@@ -9528,7 +11233,7 @@ function queueBucketSize(path) {
9528
11233
  function readQueueFile(path) {
9529
11234
  if (queueBucketSize(path) === null)
9530
11235
  return null;
9531
- return readFileSync6(path);
11236
+ return readFileSync7(path);
9532
11237
  }
9533
11238
  function rejectLine(rejectedPath, reason, status, identity, raw) {
9534
11239
  const record = JSON.stringify({
@@ -9643,7 +11348,7 @@ async function drainRenamedAside(args, livePath, source) {
9643
11348
  async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeoutMs = WEBHOOK_FETCH_TIMEOUT_MS) {
9644
11349
  const resolved = await resolveRepo();
9645
11350
  const repo = resolved && isSafeRepoSegment2(resolved.owner) && isSafeRepoSegment2(resolved.repo) ? resolved : null;
9646
- const outboxRoot = () => join7(GLOBAL_VINAYA_HOME, "outbox");
11351
+ const outboxRoot = () => join8(GLOBAL_VINAYA_HOME, "outbox");
9647
11352
  const path = outboxPathFor({ outboxRoot }, repo, outboxTask);
9648
11353
  const lockPath = `${path}.flush-lock`;
9649
11354
  const lockToken = acquireDrainLock(lockPath);
@@ -9680,6 +11385,7 @@ async function drainOutboxToWebhook(outboxTask, webhookUrl, headers, fetchTimeou
9680
11385
 
9681
11386
  // src/lib/log-sink.ts
9682
11387
  var OUTBOX_MAX_BYTES = 8 * 1024 * 1024;
11388
+ var LOG_FOLDER_ONLY_ENV = "VINAYA_LOG_FOLDER_ONLY";
9683
11389
  function describeFolderFallback(reason) {
9684
11390
  if (reason.kind === "anchor-unreadable") {
9685
11391
  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`";
@@ -9719,6 +11425,9 @@ function logsCredentialMissing(headers, env) {
9719
11425
  return false;
9720
11426
  }
9721
11427
  function resolveLogDestinationFrom(input) {
11428
+ if (input.localConfig?.logs === false || input.unattended && input.trustAnchorConfig?.logs === false) {
11429
+ return { kind: "none", reason: "logs: false disables Log recording" };
11430
+ }
9722
11431
  const spoolDir = input.env.VINAYA_LOG_SPOOL_DIR;
9723
11432
  if (spoolDir !== undefined && spoolDir.trim() !== "") {
9724
11433
  return { kind: "folder", folder: spoolDir };
@@ -9738,6 +11447,10 @@ function resolveLogDestinationFrom(input) {
9738
11447
  } else {
9739
11448
  effective = local;
9740
11449
  }
11450
+ if (input.folderOnly || input.env[LOG_FOLDER_ONLY_ENV] === "1") {
11451
+ const folder = effective && "folder" in effective && !isInsideRepo(effective.folder, input.repoRoot) ? effective.folder : input.defaultFolder;
11452
+ return { kind: "folder", folder };
11453
+ }
9741
11454
  if (hostFromEnv(input.env) === "ci") {
9742
11455
  if (effective && "url" in effective) {
9743
11456
  if (logsCredentialMissing(effective.headers, input.env)) {
@@ -9762,41 +11475,73 @@ function resolveLogDestinationFrom(input) {
9762
11475
  const folder = effective && "folder" in effective ? effective.folder : input.defaultFolder;
9763
11476
  return fallbackReason ? { kind: "folder", folder, fallbackReason } : { kind: "folder", folder };
9764
11477
  }
9765
- var processTrustAnchorByRepo = new Map;
11478
+ var LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS = 30000;
11479
+ var LOG_DESTINATION_ANCHOR_MAX_RETRIES = 5;
11480
+ function createTrustAnchorCache(read, now = Date.now, bounds = {
11481
+ retryIntervalMs: LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS,
11482
+ maxRetries: LOG_DESTINATION_ANCHOR_MAX_RETRIES
11483
+ }) {
11484
+ const slots = new Map;
11485
+ const start = (repoRoot, retries) => {
11486
+ const slot = {
11487
+ reading: Promise.resolve().then(read).catch(() => null),
11488
+ retries,
11489
+ missedAt: null
11490
+ };
11491
+ slots.set(repoRoot, slot);
11492
+ slot.reading.then((config) => {
11493
+ if (config === null)
11494
+ slot.missedAt = now();
11495
+ });
11496
+ return slot.reading;
11497
+ };
11498
+ return {
11499
+ get: (repoRoot) => {
11500
+ const slot = slots.get(repoRoot);
11501
+ if (slot === undefined)
11502
+ return start(repoRoot, 0);
11503
+ if (slot.missedAt === null)
11504
+ return slot.reading;
11505
+ if (slot.retries >= bounds.maxRetries || now() - slot.missedAt < bounds.retryIntervalMs)
11506
+ return slot.reading;
11507
+ return start(repoRoot, slot.retries + 1);
11508
+ },
11509
+ clear: () => slots.clear()
11510
+ };
11511
+ }
11512
+ var processTrustAnchorByRepo = createTrustAnchorCache(safeLoadTrustAnchorConfig);
9766
11513
  function processTrustAnchor(repoRoot) {
9767
- const cached = processTrustAnchorByRepo.get(repoRoot);
9768
- if (cached !== undefined)
9769
- return cached;
9770
- const reading = safeLoadTrustAnchorConfig();
9771
- processTrustAnchorByRepo.set(repoRoot, reading);
9772
- return reading;
11514
+ return processTrustAnchorByRepo.get(repoRoot);
9773
11515
  }
9774
- async function defaultResolveLogDestination(repo, env) {
11516
+ async function defaultResolveLogDestination(repo, env, folderOnly = false) {
9775
11517
  const localConfig = loadConfig();
9776
11518
  const unattended = isUnattendedProcess(process.env);
9777
11519
  const repoRoot = repoRootSync();
9778
11520
  return resolveLogDestinationFrom({
9779
11521
  localConfig,
11522
+ folderOnly,
9780
11523
  trustAnchorConfig: unattended ? await processTrustAnchor(repoRoot) : null,
9781
11524
  unattended,
9782
11525
  env,
9783
- defaultFolder: join8(await runtimeDirForRepoAsync(repo), "logs"),
11526
+ defaultFolder: join9(await runtimeDirForRepoAsync(repo), "logs"),
9784
11527
  repoRoot
9785
11528
  });
9786
11529
  }
9787
11530
  function unresolvedLogDestination(env) {
11531
+ const loaded = loadConfig();
11532
+ if (loaded?.logs === false)
11533
+ return { kind: "none", reason: "logs: false disables Log recording" };
9788
11534
  if (hostFromEnv(env) === "ci") {
9789
11535
  return {
9790
11536
  kind: "none",
9791
11537
  reason: "the process ended before its log destination was resolved, and a CI job never records to a folder"
9792
11538
  };
9793
11539
  }
9794
- const loaded = loadConfig();
9795
- const localConfig = loaded?.logs?.url !== undefined ? { ...loaded, logs: undefined } : loaded;
11540
+ const localConfig = loaded?.logs && loaded.logs.url !== undefined ? { ...loaded, logs: undefined } : loaded;
9796
11541
  const unattended = isUnattendedProcess(process.env);
9797
11542
  const repoRoot = repoRootSync();
9798
11543
  const runtimeDir = process.env[RUNTIME_DIR_ENV_KEY] || resolveRuntimeDir({ repo: null, localConfig, trustAnchorConfig: null, unattended, repoRoot });
9799
- const defaultFolder = join8(runtimeDir, "logs");
11544
+ const defaultFolder = join9(runtimeDir, "logs");
9800
11545
  const resolved = resolveLogDestinationFrom({
9801
11546
  localConfig,
9802
11547
  trustAnchorConfig: null,
@@ -9809,7 +11554,7 @@ function unresolvedLogDestination(env) {
9809
11554
  }
9810
11555
  function folderFallbackStatePath(repo, stateRoot = GLOBAL_VINAYA_HOME) {
9811
11556
  const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
9812
- return join8(stateRoot, "fallback", `${dirName}.json`);
11557
+ return join9(stateRoot, "fallback", `${dirName}.json`);
9813
11558
  }
9814
11559
  function recordFolderFallback(repo, issue, reason, now, runtimeDir, stateRoot = GLOBAL_VINAYA_HOME) {
9815
11560
  const message = describeFolderFallback(reason);
@@ -9825,25 +11570,25 @@ function recordFolderFallback(repo, issue, reason, now, runtimeDir, stateRoot =
9825
11570
  };
9826
11571
  const path = folderFallbackStatePath(repo, stateRoot);
9827
11572
  mkdirSync4(dirname7(path), { recursive: true, mode: 448 });
9828
- writeFileSync3(path, `${JSON.stringify(record)}
11573
+ writeFileSync4(path, `${JSON.stringify(record)}
9829
11574
  `, { mode: 384 });
9830
11575
  } catch {}
9831
11576
  }
9832
11577
  function isEnoent2(err) {
9833
11578
  return typeof err === "object" && err !== null && err.code === "ENOENT";
9834
11579
  }
9835
- var execFileAsync5 = promisify5(execFile5);
11580
+ var execFileAsync6 = promisify6(execFile6);
9836
11581
  async function resolveDoctrine(cwd, vinayaVersion) {
9837
11582
  let toplevel;
9838
11583
  try {
9839
- toplevel = (await execFileAsync5("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8" })).stdout.trim();
11584
+ toplevel = (await execFileAsync6("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { encoding: "utf8" })).stdout.trim();
9840
11585
  } catch (err) {
9841
11586
  return isEnoent2(err) ? "unknown" : vinayaVersion;
9842
11587
  }
9843
- if (!existsSync7(join8(toplevel, "aeg-root", "roles")))
11588
+ if (!existsSync8(join9(toplevel, "aeg-root", "roles")))
9844
11589
  return vinayaVersion;
9845
11590
  try {
9846
- const sha = (await execFileAsync5("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], { encoding: "utf8" })).stdout.trim();
11591
+ const sha = (await execFileAsync6("git", ["-C", toplevel, "rev-parse", "HEAD:aeg-root"], { encoding: "utf8" })).stdout.trim();
9847
11592
  return `aeg-root@${sha}`;
9848
11593
  } catch {
9849
11594
  return vinayaVersion;
@@ -9866,7 +11611,7 @@ var TRANCHE_ISSUE_LIST_LIMIT = 200;
9866
11611
  async function issueForTrancheTask(tranche, taskId, cwd, repo) {
9867
11612
  let stdout;
9868
11613
  try {
9869
- ({ stdout } = await execFileAsync5("gh", [
11614
+ ({ stdout } = await execFileAsync6("gh", [
9870
11615
  "issue",
9871
11616
  "list",
9872
11617
  "--state",
@@ -9904,7 +11649,7 @@ async function issueForTrancheTask(tranche, taskId, cwd, repo) {
9904
11649
  async function confirmBacklogIssue(issue, cwd, repo) {
9905
11650
  let stdout;
9906
11651
  try {
9907
- ({ stdout } = await execFileAsync5("gh", ["issue", "view", String(issue), "--json", "number", ...repo === null ? [] : ["--repo", repo]], {
11652
+ ({ stdout } = await execFileAsync6("gh", ["issue", "view", String(issue), "--json", "number", ...repo === null ? [] : ["--repo", repo]], {
9908
11653
  cwd,
9909
11654
  encoding: "utf8",
9910
11655
  timeout: LOG_CONTEXT_LOOKUP_DEADLINE_MS,
@@ -9923,7 +11668,7 @@ async function confirmBacklogIssue(issue, cwd, repo) {
9923
11668
  async function resolveBranchIssue(cwd, env = process.env, repo = null) {
9924
11669
  let branch;
9925
11670
  try {
9926
- branch = (await execFileAsync5("git", ["-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"], {
11671
+ branch = (await execFileAsync6("git", ["-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"], {
9927
11672
  encoding: "utf8",
9928
11673
  timeout: LOG_CONTEXT_LOOKUP_DEADLINE_MS,
9929
11674
  killSignal: "SIGKILL"
@@ -9941,7 +11686,7 @@ async function resolveBranchIssue(cwd, env = process.env, repo = null) {
9941
11686
  }
9942
11687
  function readVinayaVersion() {
9943
11688
  try {
9944
- const pkg = JSON.parse(readFileSync7(join8(packageRoot(import.meta.url), "package.json"), "utf8"));
11689
+ const pkg = JSON.parse(readFileSync8(join9(packageRoot(import.meta.url), "package.json"), "utf8"));
9945
11690
  return pkg.version ?? "unknown";
9946
11691
  } catch {
9947
11692
  return "unknown";
@@ -9959,7 +11704,7 @@ function safeRepoSlug(repo) {
9959
11704
  function outboxPathFor(deps, repo, issue) {
9960
11705
  const dirName = repo ? `${repo.owner}-${repo.repo}` : "unresolved";
9961
11706
  const fileName = `${issue ?? "none"}.ndjson`;
9962
- return join8(deps.outboxRoot(), dirName, fileName);
11707
+ return join9(deps.outboxRoot(), dirName, fileName);
9963
11708
  }
9964
11709
  function hostFromEnv(env) {
9965
11710
  if (env.GITHUB_ACTIONS)
@@ -10006,7 +11751,7 @@ function headShaRead(key, read, shared) {
10006
11751
  }
10007
11752
  async function resolveHeadSha(cwd) {
10008
11753
  try {
10009
- const out = (await execFileAsync5("git", ["-C", cwd, "rev-parse", "HEAD"], { encoding: "utf8" })).stdout.trim();
11754
+ const out = (await execFileAsync6("git", ["-C", cwd, "rev-parse", "HEAD"], { encoding: "utf8" })).stdout.trim();
10010
11755
  return /^[0-9a-f]{40}$/.test(out) ? out : null;
10011
11756
  } catch {
10012
11757
  return null;
@@ -10014,7 +11759,8 @@ async function resolveHeadSha(cwd) {
10014
11759
  }
10015
11760
  function defaultDeps() {
10016
11761
  return {
10017
- outboxRoot: () => join8(GLOBAL_VINAYA_HOME, "outbox"),
11762
+ readConfig: loadConfig,
11763
+ outboxRoot: () => join9(GLOBAL_VINAYA_HOME, "outbox"),
10018
11764
  home: () => homedir3(),
10019
11765
  hostname: () => osHostname(),
10020
11766
  cwd: () => process.cwd(),
@@ -10059,7 +11805,7 @@ function appendHardenedLine(path, line) {
10059
11805
  function reportRotationOverflow(backupPath, warn) {
10060
11806
  let raw;
10061
11807
  try {
10062
- raw = readFileSync7(backupPath, "utf8");
11808
+ raw = readFileSync8(backupPath, "utf8");
10063
11809
  } catch {
10064
11810
  return;
10065
11811
  }
@@ -10197,23 +11943,59 @@ function createLogSink(overrides = {}) {
10197
11943
  };
10198
11944
  let contextCache;
10199
11945
  let settledContext;
11946
+ let contextEnv = {};
11947
+ const resolveDestination = async (repo, env) => deps.readConfig()?.logs === false ? { kind: "none", reason: "logs: false disables Log recording" } : await deps.resolveLogDestination(repo, env, deps.folderOnly);
10200
11948
  const context = () => {
10201
11949
  if (contextCache === undefined) {
10202
11950
  const env = deps.env();
11951
+ contextEnv = env;
10203
11952
  contextCache = Promise.all([
10204
11953
  withDeadline(resolveRepoOnce(), LOG_CONTEXT_LOOKUP_DEADLINE_MS, null),
10205
11954
  doctrine()
10206
11955
  ]).then(async ([resolved, doctrineValue]) => {
10207
11956
  const repo = resolved && isSafeRepoSegment3(resolved.owner) && isSafeRepoSegment3(resolved.repo) ? resolved : null;
10208
- settledContext = { repo, doctrine: doctrineValue, destination: await deps.resolveLogDestination(repo, env) };
11957
+ settledContext = { repo, doctrine: doctrineValue, destination: await resolveDestination(repo, env) };
11958
+ destinationRetryDueAt = deps.now().getTime() + LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS;
10209
11959
  return settledContext;
10210
11960
  });
10211
11961
  }
10212
11962
  return contextCache;
10213
11963
  };
11964
+ let destinationRetries = 0;
11965
+ let destinationRetryDueAt = 0;
11966
+ let destinationRetryInFlight = false;
11967
+ const retryDestinationIfDue = (ctx) => {
11968
+ if (ctx.destination.kind !== "folder" || ctx.destination.fallbackReason?.kind !== "anchor-unreadable")
11969
+ return;
11970
+ if (destinationRetryInFlight || destinationRetries >= LOG_DESTINATION_ANCHOR_MAX_RETRIES)
11971
+ return;
11972
+ if (deps.now().getTime() < destinationRetryDueAt)
11973
+ return;
11974
+ destinationRetryInFlight = true;
11975
+ destinationRetries++;
11976
+ const generation = contextCache;
11977
+ Promise.resolve().then(() => resolveDestination(ctx.repo, contextEnv)).then((destination) => {
11978
+ if (contextCache !== generation)
11979
+ return;
11980
+ if (destination.kind === "server") {
11981
+ settledContext = { ...ctx, destination };
11982
+ contextCache = Promise.resolve(settledContext);
11983
+ return;
11984
+ }
11985
+ if (destination.kind !== "folder" || destination.fallbackReason?.kind !== "anchor-unreadable") {
11986
+ destinationRetries = LOG_DESTINATION_ANCHOR_MAX_RETRIES;
11987
+ }
11988
+ }, () => {
11989
+ return;
11990
+ }).finally(() => {
11991
+ destinationRetryInFlight = false;
11992
+ destinationRetryDueAt = deps.now().getTime() + LOG_DESTINATION_ANCHOR_RETRY_INTERVAL_MS;
11993
+ });
11994
+ };
10214
11995
  const resetContext = () => {
10215
11996
  contextCache = undefined;
10216
11997
  settledContext = undefined;
11998
+ destinationRetries = 0;
10217
11999
  };
10218
12000
  let drainChain = Promise.resolve();
10219
12001
  const pendingWrites = new Set;
@@ -10226,24 +12008,30 @@ function createLogSink(overrides = {}) {
10226
12008
  `);
10227
12009
  });
10228
12010
  };
10229
- const snapshot = () => {
12011
+ const snapshot = (attribution) => {
10230
12012
  const env = deps.env();
10231
12013
  return {
12014
+ attributed: attribution !== undefined,
10232
12015
  host: hostFromEnv(env),
10233
12016
  now: deps.now(),
10234
12017
  seq: seq++,
10235
12018
  envFields: {
10236
- role: env.VINAYA_ROLE,
12019
+ role: attribution?.role ?? env.VINAYA_ROLE,
10237
12020
  task: env.VINAYA_TASK,
10238
- round: env.VINAYA_ROUND,
12021
+ round: attribution ? String(attribution.round) : env.VINAYA_ROUND,
10239
12022
  pr: env.VINAYA_PR,
10240
12023
  run: env.VINAYA_RUN || runId,
10241
- attempt: env.VINAYA_ATTEMPT,
12024
+ attempt: attribution ? String(attribution.attempt) : env.VINAYA_ATTEMPT,
10242
12025
  parent: env.VINAYA_PARENT_EVENT,
10243
12026
  workRef: env.VINAYA_WORK_REF,
10244
12027
  flow: env.VINAYA_FLOW,
10245
12028
  flowVersion: env.VINAYA_FLOW_VERSION,
10246
12029
  runtime: env.VINAYA_RUNTIME,
12030
+ processId: env.VINAYA_PROCESS_ID,
12031
+ processVersion: env.VINAYA_PROCESS_VERSION,
12032
+ processDigest: env.VINAYA_PROCESS_DIGEST,
12033
+ runnerId: env.VINAYA_RUNNER_ID,
12034
+ runnerVersion: env.VINAYA_RUNNER_VERSION,
10247
12035
  source: env.VINAYA_SOURCE
10248
12036
  }
10249
12037
  };
@@ -10272,12 +12060,14 @@ function createLogSink(overrides = {}) {
10272
12060
  branchIssue,
10273
12061
  eventId: randomUUID2(),
10274
12062
  processId,
12063
+ revision: headSha,
12064
+ provenance: call.attributed ? "parent_attributed" : deps.provenance,
10275
12065
  inputVersions: deps.inputVersions()
10276
12066
  });
10277
12067
  const header = headSha === null ? built : { ...built, subject: { ...built.subject, sha: headSha } };
10278
12068
  if (destination.kind === "folder" && destination.fallbackReason && !folderFallbackRecorded) {
10279
12069
  folderFallbackRecorded = true;
10280
- recordFolderFallback(repo, header.subject.issue, destination.fallbackReason, call.now, dirname7(destination.folder), join8(deps.home(), ".vinaya"));
12070
+ recordFolderFallback(repo, header.subject.issue, destination.fallbackReason, call.now, dirname7(destination.folder), join9(deps.home(), ".vinaya"));
10281
12071
  }
10282
12072
  const full = { ...e, ...header };
10283
12073
  const parsed = LogEventSchema.safeParse(full);
@@ -10296,11 +12086,14 @@ function createLogSink(overrides = {}) {
10296
12086
  appendLine(outboxPathFor({ outboxRoot: () => destination.folder }, repo, header.subject.issue), line, warnOnce);
10297
12087
  }
10298
12088
  };
10299
- function log(e) {
12089
+ function log(e, attribution) {
10300
12090
  try {
10301
- const call = snapshot();
12091
+ const call = snapshot(attribution);
10302
12092
  const write = async () => {
10303
12093
  const ctx = await context();
12094
+ try {
12095
+ retryDestinationIfDue(ctx);
12096
+ } catch {}
10304
12097
  if (ctx.destination.kind === "none") {
10305
12098
  writeEvent(e, call, ctx, null, null, true);
10306
12099
  return;
@@ -10324,9 +12117,13 @@ function createLogSink(overrides = {}) {
10324
12117
  function logSync(e, opts = {}) {
10325
12118
  try {
10326
12119
  const call = snapshot();
10327
- let ctx = settledContext;
12120
+ let ctx = deps.readConfig()?.logs === false ? {
12121
+ repo: null,
12122
+ doctrine: "unknown",
12123
+ destination: { kind: "none", reason: "logs: false disables Log recording" }
12124
+ } : settledContext;
10328
12125
  if (ctx === undefined) {
10329
- const destination = deps.unresolvedLogDestination(deps.env());
12126
+ const destination = deps.readConfig()?.logs === false ? { kind: "none", reason: "logs: false disables Log recording" } : deps.unresolvedLogDestination(deps.env());
10330
12127
  if (destination.kind === "folder" && !opts.quiet) {
10331
12128
  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
10332
12129
  `);
@@ -10402,17 +12199,37 @@ function parseChangedLineRanges(diffOutput) {
10402
12199
 
10403
12200
  // src/lib/diff-evidence.ts
10404
12201
  function fileDiffAgainst(ref, path) {
10405
- let out;
12202
+ let committed;
10406
12203
  try {
10407
- out = execFileSync8("git", ["diff", `${ref}...HEAD`, "--", path], {
12204
+ committed = execFileSync8("git", ["diff", `${ref}...HEAD`, "--", path], {
10408
12205
  encoding: "utf8",
10409
12206
  stdio: ["ignore", "pipe", "pipe"]
10410
12207
  }).trim();
10411
12208
  } catch {
10412
12209
  return null;
10413
12210
  }
12211
+ const staged = stagedDiff(["--", path]);
12212
+ if (staged === null)
12213
+ return null;
12214
+ const out = [committed, staged].filter(Boolean).join(`
12215
+ `);
10414
12216
  return out === "" ? null : out;
10415
12217
  }
12218
+ function readsStagedDiff() {
12219
+ return process.env.VINAYA_COMMIT_HOOK === "1" && Boolean(process.env.GIT_INDEX_FILE);
12220
+ }
12221
+ function stagedDiff(args) {
12222
+ if (!readsStagedDiff())
12223
+ return "";
12224
+ try {
12225
+ return execFileSync8("git", ["diff", "--cached", ...args], {
12226
+ encoding: "utf8",
12227
+ stdio: ["ignore", "pipe", "pipe"]
12228
+ }).trim();
12229
+ } catch {
12230
+ return null;
12231
+ }
12232
+ }
10416
12233
  function revParse(ref) {
10417
12234
  try {
10418
12235
  return execFileSync8("git", ["rev-parse", "--verify", ref], {
@@ -10446,6 +12263,13 @@ function changedFiles(base) {
10446
12263
  return out === "" ? [] : out.split(`
10447
12264
  `).map((s) => s.trim()).filter(Boolean);
10448
12265
  }
12266
+ function stagedChangedFiles() {
12267
+ const out = stagedDiff(["--name-only"]);
12268
+ if (out === null)
12269
+ return null;
12270
+ return out === "" ? [] : out.split(`
12271
+ `).map((s) => s.trim()).filter(Boolean);
12272
+ }
10449
12273
  function resolveChangedFiles(base = process.env.BASE_SHA || "origin/main") {
10450
12274
  return resolveDiff(base)?.files ?? null;
10451
12275
  }
@@ -10461,7 +12285,30 @@ function resolveDiff(base = process.env.BASE_SHA || "origin/main") {
10461
12285
  const relPaths = changedFiles(ref);
10462
12286
  if (relPaths === null)
10463
12287
  continue;
10464
- return { base: ref, root, files: relPaths.map((p) => join9(root, p)) };
12288
+ const stagedPaths = stagedChangedFiles();
12289
+ if (stagedPaths === null)
12290
+ return null;
12291
+ const paths = [...new Set([...relPaths, ...stagedPaths])];
12292
+ return { base: ref, root, files: paths.map((p) => join10(root, p)) };
12293
+ }
12294
+ return null;
12295
+ }
12296
+ function resolveAddedFiles(base = process.env.BASE_SHA || "origin/main") {
12297
+ if (repoRoot() === null)
12298
+ return null;
12299
+ const head = revParse("HEAD");
12300
+ for (const ref of new Set([base, "origin/main", "main"])) {
12301
+ const resolved = revParse(ref);
12302
+ if (resolved === null || resolved === head)
12303
+ continue;
12304
+ try {
12305
+ const out = execFileSync8("git", ["diff", "--name-only", "--diff-filter=A", `${ref}...HEAD`], {
12306
+ encoding: "utf8",
12307
+ stdio: ["ignore", "pipe", "pipe"]
12308
+ }).trim();
12309
+ return out === "" ? [] : out.split(`
12310
+ `).map((p) => p.trim()).filter(Boolean);
12311
+ } catch {}
10465
12312
  }
10466
12313
  return null;
10467
12314
  }
@@ -10494,13 +12341,14 @@ function findingsInThisDiff(findings) {
10494
12341
 
10495
12342
  // src/checks/bin/check-reader-resolvable-prose.ts
10496
12343
  var CHECK_NAME = "reader-resolvable-prose";
10497
- var proseGates = loadConfig()?.proseGates;
12344
+ var CONFIG = loadConfigChecked();
12345
+ var proseGates = CONFIG.ok ? CONFIG.config?.proseGates : undefined;
10498
12346
  function resolveCheckDoctrineRoot() {
10499
12347
  if (proseGates?.doctrineRoot !== undefined)
10500
12348
  return proseGates.doctrineRoot;
10501
12349
  const root = repoRoot();
10502
12350
  if (root !== null) {
10503
- const candidate = join10(root, "aeg-root");
12351
+ const candidate = join11(root, "aeg-root");
10504
12352
  if (hasDoctrineEntry(candidate))
10505
12353
  return candidate;
10506
12354
  }
@@ -10515,13 +12363,18 @@ var SOURCE_COMMENTS_GLOBS = proseGates?.sourceComments?.globs ?? [];
10515
12363
  var SOURCE_COMMENTS_ALLOWLIST = proseGates?.sourceComments?.allowlist ?? [];
10516
12364
  var SOURCE_COMMENTS_SEVERITY = proseGates?.sourceComments?.severity ?? "warning";
10517
12365
  var SPEC_GRANDFATHER = proseGates?.specGrandfather ?? [];
10518
- var SPEC_PATHS = [...DEFAULT_SPEC_PATHS, ...proseGates?.specPaths ?? []].map(normalizeSpecPath);
12366
+ var PRODUCT_PATHS = proseGates?.productPaths ?? PRODUCT_SLUG_SCOPE;
12367
+ var DECISION_RECORDS_PATH = CONFIG.ok ? CONFIG.config?.decisionRecords?.path : undefined;
12368
+ var DECISION_RECORDS_PATHS = DECISION_RECORDS_PATH === undefined ? [] : [DECISION_RECORDS_PATH];
12369
+ var SPEC_PATHS = [
12370
+ ...new Set([...DEFAULT_SPEC_PATHS, ...proseGates?.specPaths ?? [], ...DECISION_RECORDS_PATHS].map(normalizeSpecPath))
12371
+ ];
10519
12372
  function containedRelativePath(root, path) {
10520
12373
  const abs = resolve3(root, path);
10521
12374
  const lexical = relative3(resolve3(root), abs);
10522
12375
  if (escapesRoot(lexical))
10523
12376
  return null;
10524
- if (existsSync8(abs) && escapesRoot(relative3(realPathOrSelf(resolve3(root)), realPathOrSelf(abs))))
12377
+ if (existsSync9(abs) && escapesRoot(relative3(realPathOrSelf(resolve3(root)), realPathOrSelf(abs))))
10525
12378
  return null;
10526
12379
  return normalizeSpecPath(lexical);
10527
12380
  }
@@ -10543,7 +12396,7 @@ function collect(dir, out = []) {
10543
12396
  return out;
10544
12397
  }
10545
12398
  for (const name of entries) {
10546
- const full = join10(dir, name);
12399
+ const full = join11(dir, name);
10547
12400
  let isDir;
10548
12401
  try {
10549
12402
  isDir = statSync3(full).isDirectory();
@@ -10561,13 +12414,13 @@ function collect(dir, out = []) {
10561
12414
  return out;
10562
12415
  }
10563
12416
  function readAll(paths) {
10564
- return paths.map((p) => ({ path: p, content: readFileSync8(p, "utf8") }));
12417
+ return paths.map((p) => ({ path: p, content: readFileSync9(p, "utf8") }));
10565
12418
  }
10566
12419
  var PRODUCT_SCOPE_EXTENSIONS = new Set([".ts", ".tsx", ".yml", ".md"]);
10567
12420
  function collectProductScopeFiles(root) {
10568
12421
  const out = [];
10569
- for (const prefix of PRODUCT_SLUG_SCOPE) {
10570
- const abs = join10(root, prefix);
12422
+ for (const prefix of PRODUCT_PATHS) {
12423
+ const abs = join11(root, prefix);
10571
12424
  let isDir;
10572
12425
  try {
10573
12426
  isDir = statSync3(abs).isDirectory();
@@ -10587,7 +12440,7 @@ function collectProductScopeFiles(root) {
10587
12440
  return out;
10588
12441
  }
10589
12442
  function readProductFiles(root, relPaths) {
10590
- return relPaths.map((rel) => ({ path: rel, content: readFileSync8(join10(root, rel), "utf8") }));
12443
+ return relPaths.map((rel) => ({ path: rel, content: readFileSync9(join11(root, rel), "utf8") }));
10591
12444
  }
10592
12445
  function collectSpecFiles(root, specPaths) {
10593
12446
  const out = [];
@@ -10597,7 +12450,7 @@ function collectSpecFiles(root, specPaths) {
10597
12450
  console.log(`${CHECK_NAME}: ignoring spec path "${entry}" — it resolves outside the repository under check, and this class only ever reads this repository's own files.`);
10598
12451
  continue;
10599
12452
  }
10600
- const abs = join10(root, rel);
12453
+ const abs = join11(root, rel);
10601
12454
  let isDir;
10602
12455
  try {
10603
12456
  isDir = statSync3(abs).isDirectory();
@@ -10614,12 +12467,12 @@ function collectSpecFiles(root, specPaths) {
10614
12467
  out.push(rel);
10615
12468
  }
10616
12469
  }
10617
- const appsDir = join10(root, "apps");
12470
+ const appsDir = join11(root, "apps");
10618
12471
  let appNames;
10619
12472
  try {
10620
12473
  appNames = readdirSync3(appsDir).filter((name) => {
10621
12474
  try {
10622
- return statSync3(join10(appsDir, name)).isDirectory();
12475
+ return statSync3(join11(appsDir, name)).isDirectory();
10623
12476
  } catch {
10624
12477
  return false;
10625
12478
  }
@@ -10628,7 +12481,7 @@ function collectSpecFiles(root, specPaths) {
10628
12481
  return [...new Set(out)];
10629
12482
  }
10630
12483
  for (const app of appNames) {
10631
- const specsDir = join10(appsDir, app, "specs");
12484
+ const specsDir = join11(appsDir, app, "specs");
10632
12485
  let isDir;
10633
12486
  try {
10634
12487
  isDir = statSync3(specsDir).isDirectory();
@@ -10648,7 +12501,7 @@ function collectSpecFiles(root, specPaths) {
10648
12501
  function collectSourceCommentFiles(root, globs) {
10649
12502
  const out = [];
10650
12503
  for (const prefix of globs) {
10651
- const abs = join10(root, prefix);
12504
+ const abs = join11(root, prefix);
10652
12505
  let isDir;
10653
12506
  try {
10654
12507
  isDir = statSync3(abs).isDirectory();
@@ -10668,7 +12521,7 @@ function collectSourceCommentFiles(root, globs) {
10668
12521
  return out;
10669
12522
  }
10670
12523
  function legacySlugs(legacySlugDir) {
10671
- if (!existsSync8(legacySlugDir))
12524
+ if (!existsSync9(legacySlugDir))
10672
12525
  return { slugs: [], dormant: true };
10673
12526
  try {
10674
12527
  const slugs = readdirSync3(legacySlugDir).filter((f) => f.endsWith(".md") && !f.endsWith(".tokens.md")).map((f) => f.slice(0, -3)).filter((slug) => !/-v[0-9]+$/.test(slug));
@@ -10678,7 +12531,20 @@ function legacySlugs(legacySlugDir) {
10678
12531
  return { slugs: [], dormant: true };
10679
12532
  }
10680
12533
  }
12534
+ var CUSTOM_RULE_RECOVERY = "This text matches one of this repository's own writing rules (proseGates.rules.custom in vinaya.config.json); " + "the finding names the rule and what it means. Rewrite the text so it no longer matches, or, where the rule " + "should not read this file, add the path to that rule's exempt list.";
12535
+ var DECISION_RECORD_RECOVERY = "This text cites a decision record by its number (decision-record-citation, on while decisionRecords.path is " + "set in vinaya.config.json). A number tells a reader nothing without the folder in front of them: state the " + "decision itself in this sentence instead. Only a record inside the decision-record folder may name another " + "record, such as the one it supersedes.";
10681
12536
  function main() {
12537
+ if (!CONFIG.ok) {
12538
+ console.log(`${CHECK_NAME}: configuration refused — sweep did not run.`);
12539
+ emitCheckError({
12540
+ schema: CHECK_SCHEMA_VERSION,
12541
+ check: CHECK_NAME,
12542
+ severity: "error",
12543
+ message: `${CONFIG.path}: ${CONFIG.error}`,
12544
+ agent_recovery_prompt: "Fix the vinaya.config.json keys named above; every refused key is named with the reason. This check does " + "not fall back to its defaults while the configuration is malformed."
12545
+ });
12546
+ process.exit(2);
12547
+ }
10682
12548
  if (DOCTRINE_ROOT === null) {
10683
12549
  console.log(`${CHECK_NAME}: doctrine root unresolvable — sweep did not run.`);
10684
12550
  emitCheckError({
@@ -10694,6 +12560,13 @@ function main() {
10694
12560
  const shipsPaths = collect(DOCTRINE_ROOT).filter((p) => p.endsWith(".md"));
10695
12561
  const readerFacingPaths = READER_FACING_ACTIVE && READER_FACING_SUFFIX !== null ? collect(READER_FACING_PREFIX).filter((p) => p.endsWith(READER_FACING_SUFFIX)) : [];
10696
12562
  const productRoot = repoRoot() ?? process.cwd();
12563
+ const rules = resolveProseRules(proseGates?.rules, {
12564
+ sourceCommentSeverity: SOURCE_COMMENTS_SEVERITY,
12565
+ repoRoot: productRoot,
12566
+ decisionRecordsPath: DECISION_RECORDS_PATH
12567
+ });
12568
+ const customIds = new Set(rulesOfGroup(rules, "reader-resolvable").filter((rule) => rule.custom).map((rule) => rule.id));
12569
+ const isCustom = (finding) => customIds.has(finding.rule);
10697
12570
  const productRelPaths = collectProductScopeFiles(productRoot);
10698
12571
  const productFiles = readProductFiles(productRoot, productRelPaths);
10699
12572
  const sourceCommentRelPaths = collectSourceCommentFiles(productRoot, SOURCE_COMMENTS_GLOBS);
@@ -10701,13 +12574,13 @@ function main() {
10701
12574
  const specRelPaths = collectSpecFiles(productRoot, SPEC_PATHS);
10702
12575
  const specFiles = readProductFiles(productRoot, specRelPaths);
10703
12576
  const files = [...readAll([...shipsPaths, ...readerFacingPaths]), ...productFiles, ...specFiles];
10704
- const glossaryPath = join10(DOCTRINE_ROOT, "glossary.md");
10705
- const glossaryTerms = existsSync8(glossaryPath) ? parseGlossaryTerms(readFileSync8(glossaryPath, "utf8")) : [];
12577
+ const glossaryPath = join11(DOCTRINE_ROOT, "glossary.md");
12578
+ const glossaryTerms = existsSync9(glossaryPath) ? parseGlossaryTerms(readFileSync9(glossaryPath, "utf8")) : [];
10706
12579
  const legacySlugDir = LEGACY_SLUG_DIR ?? `${DOCTRINE_ROOT}/tranches/completed`;
10707
12580
  const { slugs, dormant: legacySlugsDormant } = legacySlugs(legacySlugDir);
10708
12581
  const readerFacingPrefix = READER_FACING_ACTIVE && READER_FACING_PREFIX !== null ? `${READER_FACING_PREFIX}/` : "/no-reader-facing-surface";
10709
12582
  const readerFacingSuffix = READER_FACING_ACTIVE && READER_FACING_SUFFIX !== null ? READER_FACING_SUFFIX : "/page.tsx";
10710
- const findings = checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, slugs, shipsPrefix, SPEC_GRANDFATHER, SPEC_PATHS);
12583
+ const findings = checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, slugs, shipsPrefix, SPEC_GRANDFATHER, SPEC_PATHS, { rules, productPaths: PRODUCT_PATHS });
10711
12584
  const reportable = findingsInThisDiff(findings);
10712
12585
  if (Array.isArray(SPEC_GRANDFATHER)) {
10713
12586
  for (const path of SPEC_GRANDFATHER) {
@@ -10721,9 +12594,9 @@ function main() {
10721
12594
  });
10722
12595
  }
10723
12596
  }
10724
- const sourceCommentFindings = checkSourceComments(sourceCommentFiles, SOURCE_COMMENTS_ALLOWLIST);
12597
+ const sourceCommentFindings = checkSourceComments(sourceCommentFiles, SOURCE_COMMENTS_ALLOWLIST, { rules });
10725
12598
  const reportableSourceComments = findingsInThisDiff(sourceCommentFindings);
10726
- console.log(`${CHECK_NAME}: doctrine root "${DOCTRINE_ROOT}"; reader-facing class ${READER_FACING_ACTIVE ? "ran" : "dormant — proseGates.readerFacingPrefix/readerFacingSuffix not both set"}; ` + `legacy-slug class ${legacySlugsDormant ? `dormant — ${legacySlugDir} is absent` : `ran (${slugs.length} slug(s))`}; ` + `product class ran (${productRelPaths.length} file(s) swept); ` + `spec class ran (${specRelPaths.length} file(s) swept, ${specGrandfatherPaths(SPEC_GRANDFATHER).length} grandfathered); ` + `source-comment class ${SOURCE_COMMENTS_GLOBS.length === 0 ? "dormant — proseGates.sourceComments.globs not set" : `ran (${sourceCommentRelPaths.length} file(s) swept, severity: ${SOURCE_COMMENTS_SEVERITY})`}; ` + `${findings.length + sourceCommentFindings.length} finding(s) swept, ${reportable.length + reportableSourceComments.length} in this diff`);
12599
+ console.log(`${CHECK_NAME}: doctrine root "${DOCTRINE_ROOT}"; reader-facing class ${READER_FACING_ACTIVE ? "ran" : "dormant — proseGates.readerFacingPrefix/readerFacingSuffix not both set"}; ` + `legacy-slug class ${legacySlugsDormant ? `dormant — ${legacySlugDir} is absent` : `ran (${slugs.length} slug(s))`}; ` + `product class ran (${productRelPaths.length} file(s) swept); ` + `spec class ran (${specRelPaths.length} file(s) swept, ${specGrandfatherPaths(SPEC_GRANDFATHER).length} grandfathered); ` + `source-comment class ${SOURCE_COMMENTS_GLOBS.length === 0 ? "dormant — proseGates.sourceComments.globs not set" : `ran (${sourceCommentRelPaths.length} file(s) swept, severity: ${SOURCE_COMMENTS_SEVERITY})`}; ` + `${rulesOfGroup(rules, "reader-resolvable").length} rule(s) (${customIds.size} custom); ` + `${findings.length + sourceCommentFindings.length} finding(s) swept, ${reportable.length + reportableSourceComments.length} in this diff`);
10727
12600
  let hasBlocking = false;
10728
12601
  for (const finding of reportable) {
10729
12602
  if (finding.blocking)
@@ -10735,11 +12608,11 @@ function main() {
10735
12608
  message: `${finding.file}:${finding.line}: ${finding.message}`,
10736
12609
  file: finding.file,
10737
12610
  line: finding.line,
10738
- agent_recovery_prompt: finding.message.includes("coined term") ? "This page uses AEG/Vinaya-internal vocabulary a first-time reader cannot resolve. Either define the term " + 'inline (the same "Term — one-sentence definition" shape the glossary uses) at its first use on this page, ' + "or link to the glossary. Do not simply delete the word if the sentence needs it." : finding.blocking && !finding.message.includes("in product code") ? "This spec cites a tranche, a task number, an Issue/PR number, or names a document outside this " + "repository as its authority — a reader with no forge to resolve it against (a fork, an export, someone " + "reading this spec after the Issue is closed) gets nothing from the citation, and a copied task number " + "goes stale the moment the plan is renumbered. Rewrite the sentence to state the fact " + "plainly instead. If this spec is pre-existing backlog, list its path in " + "`proseGates.specGrandfather` with its current finding count rather than fixing it as a drive-by in an " + "unrelated PR — a listed file that gains a citation exceeds its count and fails." : finding.blocking ? "This product-code file cites an internal tranche slug a reader outside this repo cannot resolve " + "(the reader-resolvable-prose product class). Remove the citation or rewrite the comment/doc to state " + "the fact plainly instead of pointing at the tranche that did it. This finding blocks the push and CI." : "This doctrine or page cites a forge number or an internal tranche slug the reader has no tracker to " + "resolve. Rewrite the sentence to state the fact plainly instead of pointing at the citation — say " + "what was learned/decided, not where it was logged."
12611
+ agent_recovery_prompt: isCustom(finding) ? CUSTOM_RULE_RECOVERY : finding.rule === DECISION_RECORD_CITATION_ID ? DECISION_RECORD_RECOVERY : finding.message.includes("coined term") ? "This page uses AEG/Vinaya-internal vocabulary a first-time reader cannot resolve. Either define the term " + 'inline (the same "Term — one-sentence definition" shape the glossary uses) at its first use on this page, ' + "or link to the glossary. Do not simply delete the word if the sentence needs it." : finding.blocking && !finding.message.includes("in product code") ? "This spec cites a tranche, a task number, an Issue/PR number, or names a document outside this " + "repository as its authority — a reader with no forge to resolve it against (a fork, an export, someone " + "reading this spec after the Issue is closed) gets nothing from the citation, and a copied task number " + "goes stale the moment the plan is renumbered. Rewrite the sentence to state the fact " + "plainly instead. If this spec is pre-existing backlog, list its path in " + "`proseGates.specGrandfather` with its current finding count rather than fixing it as a drive-by in an " + "unrelated PR — a listed file that gains a citation exceeds its count and fails." : finding.blocking ? "This product-code file cites an internal tranche slug a reader outside this repo cannot resolve " + "(the reader-resolvable-prose product class). Remove the citation or rewrite the comment/doc to state " + "the fact plainly instead of pointing at the tranche that did it. This finding blocks the push and CI." : "This doctrine or page cites a forge number or an internal tranche slug the reader has no tracker to " + "resolve. Rewrite the sentence to state the fact plainly instead of pointing at the citation — say " + "what was learned/decided, not where it was logged."
10739
12612
  });
10740
12613
  }
10741
12614
  for (const finding of reportableSourceComments) {
10742
- const blocking = SOURCE_COMMENTS_SEVERITY === "error";
12615
+ const blocking = finding.blocking;
10743
12616
  if (blocking)
10744
12617
  hasBlocking = true;
10745
12618
  emitCheckError({
@@ -10749,7 +12622,7 @@ function main() {
10749
12622
  message: `${finding.file}:${finding.line}: ${finding.message}`,
10750
12623
  file: finding.file,
10751
12624
  line: finding.line,
10752
- agent_recovery_prompt: "This source comment cites a tranche name or a forge number a reader outside this repo cannot resolve. " + "Rewrite the comment to state the fact it pointed at, or, for a comment that deliberately pins historical " + "content (a test fixture), add its file path to proseGates.sourceComments.allowlist in vinaya.config.json."
12625
+ agent_recovery_prompt: isCustom(finding) ? CUSTOM_RULE_RECOVERY : finding.rule === DECISION_RECORD_CITATION_ID ? DECISION_RECORD_RECOVERY : "This source comment cites a tranche name or a forge number a reader outside this repo cannot resolve. " + "Rewrite the comment to state the fact it pointed at, or, for a comment that deliberately pins historical " + "content (a test fixture), add its file path to proseGates.sourceComments.allowlist in vinaya.config.json."
10753
12626
  });
10754
12627
  }
10755
12628
  process.exit(hasBlocking ? 1 : 0);