@attalabs/vinaya 0.35.0 → 0.37.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 (246) hide show
  1. package/README.md +6 -6
  2. package/aeg-root/contracts/developer-reviewer.md +1 -1
  3. package/aeg-root/contracts/planner-operator.md +1 -1
  4. package/aeg-root/contracts/principal-operator.md +6 -6
  5. package/aeg-root/contracts/security-archivist.md +1 -1
  6. package/aeg-root/enforcement.md +9 -10
  7. package/aeg-root/process.md +3 -1
  8. package/aeg-root/roles/archivist.md +2 -2
  9. package/aeg-root/roles/developer/reference.md +13 -16
  10. package/aeg-root/roles/developer.md +7 -3
  11. package/aeg-root/roles/operator.md +18 -18
  12. package/aeg-root/roles/planner/reference.md +23 -8
  13. package/aeg-root/roles/planner.md +2 -0
  14. package/aeg-root/roles/principal.md +6 -1
  15. package/aeg-root/roles/reviewer.md +11 -3
  16. package/aeg-root/roles/security.md +19 -9
  17. package/aeg-root/roles/tranche-archivist.md +14 -2
  18. package/aeg-root/state-machine.md +11 -10
  19. package/aeg-root/templates/brief-template.md +10 -4
  20. package/aeg-root/templates/pr-report-template.md +1 -9
  21. package/aeg-root/tranche-model.md +4 -4
  22. package/dist/checks/bin/check-body-bare-digits.js +2081 -1883
  23. package/dist/checks/bin/check-branch-topology.js +1376 -1139
  24. package/dist/checks/bin/check-brief-shape.js +2081 -1883
  25. package/dist/checks/bin/check-changeset-coverage.js +2564 -2025
  26. package/dist/checks/bin/check-closes-n.js +1376 -1139
  27. package/dist/checks/bin/check-coherence.js +1480 -1228
  28. package/dist/checks/bin/check-dead-branch-push.js +1339 -1156
  29. package/dist/checks/bin/check-dispatch-readiness.js +1480 -1228
  30. package/dist/checks/bin/check-doc-coverage-push.js +2563 -2024
  31. package/dist/checks/bin/check-doc-coverage.js +2565 -2026
  32. package/dist/checks/bin/check-doctrine-no-procedures.js +2081 -1883
  33. package/dist/checks/bin/check-doctrine-portability.js +2563 -2024
  34. package/dist/checks/bin/check-evidence-fresh.js +1906 -1536
  35. package/dist/checks/bin/check-exec-bits.js +2136 -1597
  36. package/dist/checks/bin/check-first-push-dispatch.js +1480 -1228
  37. package/dist/checks/bin/check-issue-assignment.js +1376 -1139
  38. package/dist/checks/bin/check-issue-milestone-attach.js +1339 -1156
  39. package/dist/checks/bin/check-issue-objectives-numbering.js +2081 -1883
  40. package/dist/checks/bin/check-issue-parts-coverage.js +1339 -1156
  41. package/dist/checks/bin/check-issue-surface-globs.js +1488 -1227
  42. package/dist/checks/bin/check-issue-title-grammar.js +1339 -1156
  43. package/dist/checks/bin/check-issue-tranche-label.js +1339 -1156
  44. package/dist/checks/bin/check-main-branch-refusal.js +1342 -1159
  45. package/dist/checks/bin/check-no-disk-state.js +1342 -1159
  46. package/dist/checks/bin/check-pr-premise-reassert.js +2081 -1883
  47. package/dist/checks/bin/check-pr-report-density.js +1342 -1159
  48. package/dist/checks/bin/check-principal-test-plan-wait.js +1342 -1159
  49. package/dist/checks/bin/check-quoted-command.js +4063 -3526
  50. package/dist/checks/bin/check-reader-resolvable-prose.js +4082 -3533
  51. package/dist/checks/bin/check-registry-gates.js +1363 -1167
  52. package/dist/checks/bin/check-retired-vocabulary.js +4057 -3520
  53. package/dist/checks/bin/check-review-gate.js +2081 -1883
  54. package/dist/checks/bin/check-single-plan-pr.js +1339 -1156
  55. package/dist/checks/bin/check-surface-scope.js +1376 -1139
  56. package/dist/checks/bin/check-test-plan.js +1339 -1156
  57. package/dist/checks/bin/check-token-collection-wired.js +1342 -1159
  58. package/dist/checks/bin/check-token-report.js +1409 -1342
  59. package/dist/checks/bin/check-workspace-escape.js +2562 -2023
  60. package/dist/index.js +14171 -6490
  61. package/dist/lib/pre-push-cache-test-run.js +1044 -641
  62. package/dist/lib/pre-push-select-tests.js +641 -444
  63. package/package.json +2 -2
  64. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-render.ts +38 -0
  65. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/records.ts +19 -0
  66. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/assess-round.ts +257 -10
  67. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/fakes.ts +7 -2
  68. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/index.ts +2 -0
  69. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/render-summary.ts +69 -11
  70. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/types.ts +139 -2
  71. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doc-claim.ts +32 -6
  72. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/index.ts +27 -1
  73. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-validation.ts +757 -0
  74. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema.ts +8 -1
  75. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-gate.ts +52 -4
  76. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-policy.ts +163 -21
  77. package/studio-standalone/apps/vinaya-studio/web/.next/BUILD_ID +1 -1
  78. package/studio-standalone/apps/vinaya-studio/web/.next/app-path-routes-manifest.json +0 -1
  79. package/studio-standalone/apps/vinaya-studio/web/.next/build-manifest.json +3 -3
  80. package/studio-standalone/apps/vinaya-studio/web/.next/prerender-manifest.json +3 -3
  81. package/studio-standalone/apps/vinaya-studio/web/.next/required-server-files.json +0 -5
  82. package/studio-standalone/apps/vinaya-studio/web/.next/routes-manifest.json +0 -6
  83. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error/page.js +1 -1
  84. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error/page.js.nft.json +1 -1
  85. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.html +1 -1
  86. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.rsc +1 -1
  87. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  88. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  89. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  90. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  91. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  92. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page/server-reference-manifest.json +2 -2
  93. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page.js +1 -1
  94. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page.js.nft.json +1 -1
  95. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  96. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page/server-reference-manifest.json +2 -2
  97. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page.js +1 -1
  98. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page.js.nft.json +1 -1
  99. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page_client-reference-manifest.js +1 -1
  100. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page/server-reference-manifest.json +2 -2
  101. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js +3 -3
  102. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js.nft.json +1 -1
  103. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page_client-reference-manifest.js +1 -1
  104. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page/server-reference-manifest.json +2 -2
  105. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js +3 -3
  106. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js.nft.json +1 -1
  107. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page_client-reference-manifest.js +1 -1
  108. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page/server-reference-manifest.json +2 -2
  109. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js +3 -3
  110. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js.nft.json +1 -1
  111. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page_client-reference-manifest.js +1 -1
  112. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page/server-reference-manifest.json +3 -3
  113. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js +5 -5
  114. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js.nft.json +1 -1
  115. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page_client-reference-manifest.js +1 -1
  116. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page/server-reference-manifest.json +2 -2
  117. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js +3 -3
  118. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js.nft.json +1 -1
  119. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page_client-reference-manifest.js +1 -1
  120. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page/server-reference-manifest.json +2 -2
  121. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js +3 -3
  122. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js.nft.json +1 -1
  123. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page_client-reference-manifest.js +1 -1
  124. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page/server-reference-manifest.json +2 -2
  125. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js +3 -3
  126. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js.nft.json +1 -1
  127. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page_client-reference-manifest.js +1 -1
  128. package/studio-standalone/apps/vinaya-studio/web/.next/server/app-paths-manifest.json +0 -1
  129. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/044u_vinaya-studio_web_src_app_studio_backlog__components_BacklogTable_tsx_0oha0bt._.js +3 -0
  130. 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
  131. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__1bh2awk._.js → [root-of-the-server]__038scsm._.js} +2 -2
  132. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__1widio3._.js → [root-of-the-server]__03__s45._.js} +2 -2
  133. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{_15gdg48._.js → [root-of-the-server]__04adkz-._.js} +3 -3
  134. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__05zwn98._.js +14 -0
  135. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__08e39jo._.js +3 -0
  136. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0ls23oh._.js +1 -1
  137. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__10riywf._.js +3 -0
  138. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__13znegp._.js → [root-of-the-server]__134x-65._.js} +2 -2
  139. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__0zc_0gx._.js → [root-of-the-server]__14ui9sz._.js} +2 -2
  140. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__13eeix2._.js → [root-of-the-server]__1_l_l1u._.js} +2 -2
  141. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1f4bb3_._.js +3 -0
  142. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1gjqmhq._.js +1 -1
  143. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__1dky4g0._.js → [root-of-the-server]__1my83lt._.js} +2 -2
  144. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1ng2x88._.js +3 -0
  145. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__040smoa._.js → [root-of-the-server]__1qpc6at._.js} +2 -2
  146. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1snpgaw._.js +56 -0
  147. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1wc4-ip._.js +2 -2
  148. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_06h3wbl._.js +3 -0
  149. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_08onyya._.js +1 -1
  150. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_096f46i._.js +1 -1
  151. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0af2one._.js +1 -1
  152. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0e5tkdd._.js +1 -1
  153. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0gs4gvl._.js +3 -0
  154. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0kf2g72._.js +1 -1
  155. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0zf4d27._.js +1 -1
  156. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1-wo68i._.js +1 -1
  157. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_121lrn5._.js +3 -0
  158. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1achbh9._.js +1 -1
  159. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1o4v6lb._.js +3 -0
  160. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1q7h5mz._.js +1 -1
  161. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1ztd4i3._.js +3 -0
  162. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_209-ugd._.js +3 -0
  163. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_214d71c._.js +3 -0
  164. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/apps_vinaya-studio_web_src_app_studio_projects_[name]_tranches_[slug]_17dho0f._.js +3 -0
  165. 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
  166. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/node_modules_next_dist_1lzmr5o._.js +1 -1
  167. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/packages_ui_libraries_animate_components_index_ts_186fje1._.js +1 -1
  168. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/packages_ui_libraries_basic_components_index_ts_0xk1vda._.js +1 -1
  169. package/studio-standalone/apps/vinaya-studio/web/.next/server/middleware-build-manifest.js +3 -3
  170. package/studio-standalone/apps/vinaya-studio/web/.next/server/pages/500.html +1 -1
  171. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.js +1 -1
  172. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.json +4 -4
  173. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/09fcolor69bun.js +1 -0
  174. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/0lcwmwzxacdie.js +1 -0
  175. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/0ojry7lrbzkfd.css +1 -0
  176. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/0vtfb0g813gki.js +1 -0
  177. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/1giu47hrbhroj.js +1 -0
  178. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/1shz6lwruld25.js +1 -0
  179. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/1ytvuy1mmnc6j.js +1 -0
  180. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{3oxhhhm_psozq.js → 21a6_5cr956wj.js} +1 -1
  181. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/2g8mwnydod96u.js +1 -0
  182. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{3li0ueedy-ozv.js → 2nrnuawd5fwpv.js} +1 -1
  183. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/2nw47832_uvfe.js +1 -0
  184. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/2qdxnj8wk2h0s.js +1 -0
  185. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/3b9q75p-z5ma5.js +1 -0
  186. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/3cv-oe7153242.js +1 -0
  187. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{3ip5z3cf43bgo.js → 3l56x8wjdzvaw.js} +5 -5
  188. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/3m310lbjj4p5u.js +1 -0
  189. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{3goaig_rysc6p.js → 3qtt1v3ya-ofe.js} +1 -1
  190. package/studio-standalone/apps/vinaya-studio/web/package.json +2 -2
  191. package/studio-standalone/apps/vinaya-studio/web/server.js +1 -1
  192. package/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/aeg-core/bin/verify-coherence.ts +0 -1089
  193. package/studio-standalone/_node_modules/next/dist/compiled/next-server/app-route-turbo.runtime.prod.js +0 -6
  194. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route/app-paths-manifest.json +0 -3
  195. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route/build-manifest.json +0 -9
  196. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route/server-reference-manifest.json +0 -4
  197. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route.js +0 -6
  198. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route.js.map +0 -5
  199. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route.js.nft.json +0 -1
  200. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route_client-reference-manifest.js +0 -3
  201. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/044u_vinaya-studio_web__next-internal_server_app_api_coherence_route_actions_1rnzea1.js +0 -3
  202. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/[externals]__0cki-x_._.js +0 -3
  203. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/[root-of-the-server]__02a-3g8._.js +0 -15
  204. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/[turbopack]_runtime.js +0 -903
  205. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__074w9nf._.js +0 -3
  206. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0ln09ua._.js +0 -3
  207. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0oegopp._.js +0 -3
  208. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__13yxbjd._.js +0 -51
  209. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1duqmtm._.js +0 -3
  210. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1z7dml9._.js +0 -9
  211. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0bfs_u4._.js +0 -3
  212. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0g8_eot._.js +0 -3
  213. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0hrh_v-._.js +0 -181
  214. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0i4-dea._.js +0 -3
  215. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0o54suy._.js +0 -3
  216. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0rxd7s0._.js +0 -3
  217. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0y1jv16._.js +0 -3
  218. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_151m4rz._.js +0 -3
  219. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1a9dieq._.js +0 -3
  220. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1sxsf5q._.js +0 -3
  221. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1sy_yfr._.js +0 -3
  222. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_219v2an._.js +0 -3
  223. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/apps_vinaya-studio_web_src_app_studio_projects_[name]_tranches_[slug]_05ufo8i._.js +0 -3
  224. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/packages_ui_libraries_basic_components_form_input_tsx_0es8d8b._.js +0 -3
  225. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/packages_ui_libraries_brutal_components_index_ts_0n_lcc4._.js +0 -3
  226. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/packages_ui_libraries_retro_components_index_ts_0wvpm_z._.js +0 -3
  227. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/0bjnj-5fy4e7l.js +0 -1
  228. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/0c8uwz_-m8s99.js +0 -165
  229. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/0ct0c-xj0baf6.js +0 -1
  230. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/0ko698wh8xx2g.css +0 -1
  231. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/0t5n_r4xm__t-.js +0 -1
  232. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/0vc2u252q5q6o.js +0 -1
  233. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/16r_o07lw0vm0.js +0 -1
  234. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/1cah7_e5a1zvu.js +0 -1
  235. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/1gjo9-6dz7nup.js +0 -1
  236. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/24tz8aro1uto4.js +0 -1
  237. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/2ef2g5fozszw7.js +0 -1
  238. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/2ka8dg687auhj.js +0 -1
  239. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/2pf3f50gbrkyv.js +0 -1
  240. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/2qq49pct3q51-.js +0 -1
  241. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/3et66z7glk65w.js +0 -1
  242. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/3u9emqjwpd0t9.js +0 -1
  243. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/3y6u3prmrkea-.js +0 -1
  244. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{ca66rAHI_w9D7S7ceXDvR → yR5RsCxb1OGnYggiaO09S}/_buildManifest.js +0 -0
  245. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{ca66rAHI_w9D7S7ceXDvR → yR5RsCxb1OGnYggiaO09S}/_clientMiddlewareManifest.js +0 -0
  246. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{ca66rAHI_w9D7S7ceXDvR → yR5RsCxb1OGnYggiaO09S}/_ssgManifest.js +0 -0
@@ -1884,45 +1884,6 @@ var DERIVED_STATUSES = [
1884
1884
  "incoherent"
1885
1885
  ];
1886
1886
  var DERIVABLE_STATUSES = DERIVED_STATUSES.filter((s) => s !== "backlog");
1887
- // ../../packages/aeg-core/src/parse-ledger.ts
1888
- function rowFromCells(cells) {
1889
- if (cells.length < 7)
1890
- return null;
1891
- const phase = (cells[0] ?? "").trim();
1892
- if (!phase)
1893
- return null;
1894
- return {
1895
- phase,
1896
- role: (cells[1] ?? "").trim(),
1897
- agentModel: (cells[2] ?? "").trim(),
1898
- tokensIn: parseIntCell(cells[3] ?? ""),
1899
- tokensOut: parseIntCell(cells[4] ?? ""),
1900
- cost: parseCostCell(cells[5] ?? ""),
1901
- date: (cells[6] ?? "").trim()
1902
- };
1903
- }
1904
- function parseIntCell(cell) {
1905
- const trimmed = cell.replace(/`/g, "").trim();
1906
- if (!trimmed || isEmDashOrDash(trimmed))
1907
- return null;
1908
- const normalized = trimmed.replace(/[,_\s]/g, "");
1909
- if (!/^-?\d+$/.test(normalized))
1910
- return null;
1911
- return Number(normalized);
1912
- }
1913
- function parseCostCell(cell) {
1914
- const trimmed = cell.replace(/`/g, "").trim();
1915
- if (!trimmed || isEmDashOrDash(trimmed))
1916
- return null;
1917
- const normalized = trimmed.replace(/^\$/, "").replace(/[,_\s]/g, "");
1918
- if (!/^-?\d+(\.\d+)?$/.test(normalized))
1919
- return null;
1920
- return Number(normalized);
1921
- }
1922
- function isEmDashOrDash(s) {
1923
- const t = s.trim();
1924
- return t === "—" || t === "-" || t === "–";
1925
- }
1926
1887
  // ../../packages/aeg-core/src/waiver-label.ts
1927
1888
  var WAIVER_LABEL = label("waiver-docs");
1928
1889
  var WAIVER_LABEL_REVIEW = label("waiver-review");
@@ -1938,61 +1899,6 @@ function isWaiverLabelActorVerified(opts) {
1938
1899
  return false;
1939
1900
  return isPrincipal(opts.labelActor, opts.principalAllowlist);
1940
1901
  }
1941
-
1942
- // ../../packages/aeg-core/src/parse-token-report.ts
1943
- var TOKEN_REPORT_HEADING = /^\s*(?:#{1,6}\s*Token report\s*|\*\*Token report\*\*)\s*$/i;
1944
- var INLINE_FIELD_LIST = /Phase:\s*([^|]+?)\s*\|\s*Role:\s*([^|]+?)\s*\|\s*Agent\/Model:\s*([^|]+?)\s*\|\s*Tokens in:\s*([^|]+?)\s*\|\s*Tokens out:\s*([^|]+?)\s*\|\s*Cost:\s*([^|]+?)\s*\|\s*Date:\s*(.+?)\s*$/im;
1945
- function parseTokenReportEntries(body) {
1946
- const lines = body.split(/\r?\n/);
1947
- const headingIdxs = [];
1948
- lines.forEach((line, i) => {
1949
- if (TOKEN_REPORT_HEADING.test(line))
1950
- headingIdxs.push(i);
1951
- });
1952
- const out = [];
1953
- for (let h = 0;h < headingIdxs.length; h++) {
1954
- const start = headingIdxs[h] + 1;
1955
- const end = h + 1 < headingIdxs.length ? headingIdxs[h + 1] : lines.length;
1956
- const section = lines.slice(start, end).join(`
1957
- `);
1958
- const tableRows = parseTableSection(section);
1959
- if (tableRows.length > 0) {
1960
- out.push(...tableRows);
1961
- continue;
1962
- }
1963
- const inlineRow = parseInlineFieldList(section);
1964
- if (inlineRow)
1965
- out.push(inlineRow);
1966
- }
1967
- return out;
1968
- }
1969
- function parseTableSection(section) {
1970
- const lines = section.split(/\r?\n/);
1971
- let i = 0;
1972
- for (;i < lines.length; i++) {
1973
- if ((lines[i] ?? "").trim().startsWith("|"))
1974
- break;
1975
- }
1976
- if (i + 1 >= lines.length)
1977
- return [];
1978
- i += 2;
1979
- const out = [];
1980
- for (;i < lines.length; i++) {
1981
- const trimmed = (lines[i] ?? "").trim();
1982
- if (!trimmed.startsWith("|"))
1983
- break;
1984
- const row = rowFromCells(splitTableRow(trimmed));
1985
- if (row)
1986
- out.push(row);
1987
- }
1988
- return out;
1989
- }
1990
- function parseInlineFieldList(section) {
1991
- const m = section.match(INLINE_FIELD_LIST);
1992
- if (!m)
1993
- return null;
1994
- return rowFromCells([m[1], m[2], m[3], m[4], m[5], m[6], m[7]]);
1995
- }
1996
1902
  // ../../packages/aeg-core/src/verdict-extraction.ts
1997
1903
  var HEAD_SHA_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Judged head:\s*([0-9a-f]{7,40})(?![A-Za-z0-9])/im;
1998
1904
  var OBJECTIVES_VERSION_PATTERN = /^[ \t]*(?:\*{1,3}|_{1,3})?Objectives version:\s*([0-9a-f]{64})(?![A-Za-z0-9])/im;
@@ -2441,10 +2347,12 @@ function evaluateC5(changed, docOwnersContent, prBody, fileExists, waiverActive,
2441
2347
  var CODE_REVIEW_SEVERITY_ORDER = ["BLOCKER", "MAJOR", "MINOR"];
2442
2348
  var SECURITY_SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW"];
2443
2349
  var DEFAULT_MAX_ROUNDS = 3;
2350
+ var DEFAULT_MAX_TASK_MINUTES = 180;
2444
2351
  var DEFAULT_REVIEW_POLICY = {
2445
2352
  codeReviewThreshold: "BLOCKER",
2446
2353
  securityThreshold: "HIGH",
2447
- maxRounds: DEFAULT_MAX_ROUNDS
2354
+ maxRounds: DEFAULT_MAX_ROUNDS,
2355
+ maxTaskMinutes: DEFAULT_MAX_TASK_MINUTES
2448
2356
  };
2449
2357
  var FILE_SHAPED_LOCATION = /\.[a-zA-Z0-9]{1,10}(:\d+)?\s*$/;
2450
2358
  var PROSE_LOCATION_PATTERNS = [/\bpr\s*body\b/i, /\bcomment\b/i];
@@ -2464,16 +2372,42 @@ function blockingSeverities(scale, threshold) {
2464
2372
  }
2465
2373
  return scale.slice(0, idx + 1);
2466
2374
  }
2467
- function evaluateReviewFindings(findings, scale, threshold) {
2468
- const blocking = new Set(blockingSeverities(scale, threshold));
2469
- const blockingFindings = findings.filter((f) => {
2470
- if (!scale.includes(f.severity)) {
2471
- throw new Error(`evaluateReviewFindings: severity "${f.severity}" is not one of ${scale.join(" > ")}`);
2472
- }
2473
- const effectiveSeverity = f.location !== undefined && isProseLocation(f.location) ? PROSE_CAP_SEVERITY : f.severity;
2474
- return blocking.has(effectiveSeverity);
2475
- });
2476
- return { outcome: blockingFindings.length > 0 ? "blocked" : "clean", blockingFindings };
2375
+ var DEFERRAL_REASON_TEXT = {
2376
+ "unchanged-line": "unchanged line",
2377
+ "outside-surface": "outside the Surface"
2378
+ };
2379
+ var SECURITY_HIGH_AND_ABOVE = blockingSeverities(SECURITY_SEVERITY_ORDER, "HIGH");
2380
+ function classifyFinding(finding, scale, threshold, context = {}) {
2381
+ if (!scale.includes(finding.severity)) {
2382
+ throw new Error(`classifyFinding: severity "${finding.severity}" is not one of ${scale.join(" > ")}`);
2383
+ }
2384
+ const location = finding.location;
2385
+ const effectiveSeverity = location !== undefined && isProseLocation(location) ? PROSE_CAP_SEVERITY : finding.severity;
2386
+ const wouldBlock = blockingSeverities(scale, threshold).includes(effectiveSeverity);
2387
+ if (!wouldBlock)
2388
+ return { outcome: "non_blocking", deferralReason: null };
2389
+ const hasLocation = location !== undefined && location.length > 0;
2390
+ if (hasLocation && context.inSurface && !context.inSurface(location)) {
2391
+ return { outcome: "deferred", deferralReason: "outside-surface" };
2392
+ }
2393
+ if (hasLocation && context.changedLine && !SECURITY_HIGH_AND_ABOVE.includes(effectiveSeverity)) {
2394
+ if (!context.changedLine(location)) {
2395
+ return { outcome: "deferred", deferralReason: "unchanged-line" };
2396
+ }
2397
+ }
2398
+ return { outcome: "blocking", deferralReason: null };
2399
+ }
2400
+ function evaluateReviewFindings(findings, scale, threshold, context = {}) {
2401
+ const blockingFindings = [];
2402
+ const deferredFindings = [];
2403
+ for (const f of findings) {
2404
+ const c = classifyFinding(f, scale, threshold, context);
2405
+ if (c.outcome === "blocking")
2406
+ blockingFindings.push(f);
2407
+ else if (c.outcome === "deferred")
2408
+ deferredFindings.push({ finding: f, reason: c.deferralReason });
2409
+ }
2410
+ return { outcome: blockingFindings.length > 0 ? "blocked" : "clean", blockingFindings, deferredFindings };
2477
2411
  }
2478
2412
  function isConsequentialFinding(finding) {
2479
2413
  return finding.state !== "resolved";
@@ -2481,11 +2415,11 @@ function isConsequentialFinding(finding) {
2481
2415
  function consequentialFindings(findings) {
2482
2416
  return findings.filter((f) => isConsequentialFinding(f));
2483
2417
  }
2484
- function evaluateCodeReview(findings, policy) {
2485
- return evaluateReviewFindings(findings, CODE_REVIEW_SEVERITY_ORDER, policy.codeReviewThreshold);
2418
+ function evaluateCodeReview(findings, policy, context = {}) {
2419
+ return evaluateReviewFindings(findings, CODE_REVIEW_SEVERITY_ORDER, policy.codeReviewThreshold, context);
2486
2420
  }
2487
- function evaluateSecurityReview(findings, policy) {
2488
- return evaluateReviewFindings(findings, SECURITY_SEVERITY_ORDER, policy.securityThreshold);
2421
+ function evaluateSecurityReview(findings, policy, context = {}) {
2422
+ return evaluateReviewFindings(findings, SECURITY_SEVERITY_ORDER, policy.securityThreshold, context);
2489
2423
  }
2490
2424
  function isKnownSeverity(scale, value) {
2491
2425
  return scale.includes(value);
@@ -2819,11 +2753,13 @@ function checkDocUpdateList(prBody) {
2819
2753
  return headingCheck(prBody, "(?:documentation|doc)[- ]update(?:\\s+list)?", "Documentation-update list");
2820
2754
  }
2821
2755
  function checkWorktreeStep0(prBody) {
2822
- if (/git worktree add/.test(prBody))
2756
+ if (/git worktree add/.test(prBody) || /cd \.worktrees\//.test(prBody) || /bun install --frozen-lockfile/.test(prBody))
2823
2757
  return { status: "pass", errors: [] };
2824
2758
  return {
2825
2759
  status: "fail",
2826
- errors: ["brief-validation worktree Step 0: no `git worktree add` command found in the PR body."]
2760
+ errors: [
2761
+ "brief-validation worktree Step 0: no `git worktree add`, `cd .worktrees/`, or `bun install --frozen-lockfile` command found in the PR body."
2762
+ ]
2827
2763
  };
2828
2764
  }
2829
2765
  function checkStopConditions(prBody) {
@@ -3013,7 +2949,8 @@ function isCommandBlock(content) {
3013
2949
  return COMMAND_WORDS.includes(commandWordOf(firstNonBlankLine(content)));
3014
2950
  }
3015
2951
  function isStep0Block(content) {
3016
- return firstNonBlankLine(content).startsWith("git worktree add");
2952
+ const first = firstNonBlankLine(content);
2953
+ return first.startsWith("git worktree add") || first.startsWith("cd .worktrees/") || first.startsWith("bun install --frozen-lockfile");
3017
2954
  }
3018
2955
  function checkCommandsCarryOutput(prBody) {
3019
2956
  const errors = [];
@@ -3399,1513 +3336,1602 @@ function checkPrReportDensity(prBody) {
3399
3336
  const results = [checkDecisionsDensity(prBody), checkScopeDensity(prBody)];
3400
3337
  return { errors: results.flatMap((r) => r.errors) };
3401
3338
  }
3402
- // ../../packages/aeg-core/src/issue-validation.ts
3403
- function hasRationaleField(body, labelPattern) {
3404
- const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
3405
- return re.test(body);
3406
- }
3407
- var RATIONALE_FIELDS = [
3408
- { name: "Boundary", pattern: "Boundary" },
3409
- { name: "Sizing", pattern: "Sizing" },
3410
- { name: "Project(s) + blast radius", pattern: "Project\\(s\\)|Project(?:s)?\\s*\\+|blast radius" },
3411
- { name: "Dependency rationale", pattern: "Dependency rationale|Depends[- ]on" },
3412
- { name: "Traps to avoid", pattern: "Traps" },
3413
- { name: "Suggested agent-class", pattern: "(?:Suggested\\s+)?agent-class" },
3414
- { name: "Stop-and-escalate", pattern: "Stop-and-escalate" },
3415
- { name: "Docs to keep coherent", pattern: "Docs to keep coherent|§7" }
3339
+ // ../../packages/aeg-core/src/reader-resolvable-prose.ts
3340
+ var PRODUCT_SLUG_SCOPE = [
3341
+ "apps/cli/src",
3342
+ ".github/workflows",
3343
+ ".vinaya",
3344
+ "apps/cli/README.md",
3345
+ "packages/sources/README.md"
3416
3346
  ];
3417
- var DEPENDENCY_RATIONALE_FIELD_NAME = "Dependency rationale";
3418
- function checkIssueRationale(body) {
3419
- const errors = [];
3420
- for (const f of RATIONALE_FIELDS) {
3421
- if (!hasRationaleField(body, f.pattern)) {
3422
- errors.push(`issue-validation ${f.name}: rationale field not found in the Issue body — every task Issue carries the full Planner's rationale (aeg-root/contracts/planner-brief.md).`);
3423
- continue;
3424
- }
3425
- if (f.name === DEPENDENCY_RATIONALE_FIELD_NAME && !SECTION_HEADER.test(body)) {
3426
- errors.push(`issue-validation ${f.name}: rationale field found, but not in the form amend-deps requires — ` + "write `**Dependency rationale** — …`, not `**Dependency rationale:** …`. " + "`amendRationaleDeps` (the only sanctioned way to edit Depends-on/Conflicts-with) locates this " + "section by the exact anchor `**Dependency rationale**`; a colon inside the bold breaks that match " + "and the Issue becomes unamendable.");
3427
- }
3428
- }
3429
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3430
- }
3431
- var OBJECTIVES_SINCE_ISSUE = 404;
3432
- function checkIssueObjectives(body, issueNumber, sinceIssue = OBJECTIVES_SINCE_ISSUE) {
3433
- if (sinceIssue !== null && issueNumber !== null && issueNumber < sinceIssue)
3434
- return { status: "pass", errors: [] };
3435
- const result = objectivesOf(body);
3436
- if (result.ok)
3437
- return { status: "pass", errors: [] };
3438
- return { status: "fail", errors: result.errors.map((e) => `issue-validation objectives: ${e}`) };
3347
+ function isUnderOrEqual(path, prefix) {
3348
+ return path === prefix || path.startsWith(`${prefix}/`);
3439
3349
  }
3440
- function topLevelSectionText(body, headingName) {
3441
- const headingRe = new RegExp(`^##[ \\t]*${headingName}[ \\t]*$`, "im");
3442
- const heading = headingRe.exec(body);
3443
- if (!heading)
3444
- return null;
3445
- const afterHeading = body.slice(heading.index + heading[0].length);
3446
- const next = /^##[ \t]/m.exec(afterHeading);
3447
- return next ? afterHeading.slice(0, next.index) : afterHeading;
3350
+ function isProductScopeFile(path) {
3351
+ return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
3448
3352
  }
3449
- function partHasBacktickedPath(text) {
3450
- let i = 0;
3451
- while (i < text.length) {
3452
- const start = text.indexOf("`", i);
3453
- if (start === -1)
3454
- return false;
3455
- const end = text.indexOf("`", start + 1);
3456
- if (end === -1)
3457
- return false;
3458
- if (text.slice(start + 1, end).includes("/"))
3459
- return true;
3460
- i = end + 1;
3461
- }
3462
- return false;
3353
+ var SHIPS_PREFIX = "aeg-root/";
3354
+ function shipsArchivePrefix(shipsPrefix) {
3355
+ return `${shipsPrefix}tranches/completed/`;
3463
3356
  }
3464
- var PART_MIN_WORDS_OUTSIDE_BACKTICKS = 3;
3465
- function stripPartBackticks(text) {
3466
- return text.replace(/`[^`\n]*`/g, " ");
3357
+ var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
3358
+ function normalizeSpecPath(entry) {
3359
+ let out = entry.replace(/\\/g, "/");
3360
+ while (out.startsWith("./"))
3361
+ out = out.slice(2);
3362
+ out = out.replace(/\/{2,}/g, "/");
3363
+ while (out.endsWith("/"))
3364
+ out = out.slice(0, -1);
3365
+ return out;
3467
3366
  }
3468
- function partWordCount(text) {
3469
- return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
3367
+ function isSpecFile2(path, specPaths) {
3368
+ if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
3369
+ return true;
3370
+ if (!path.endsWith(".md"))
3371
+ return false;
3372
+ return specPaths.some((entry) => isUnderOrEqual(path, normalizeSpecPath(entry)));
3470
3373
  }
3471
- function looksLikeFilePath(entry) {
3472
- const stripped = entry.replace(/\/\*\*?$/, "");
3473
- const lastSegment = stripped.split("/").pop() ?? stripped;
3474
- const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment);
3475
- return extMatch !== null && extMatch.index > 0;
3374
+ function isClaudeMdFile(path) {
3375
+ return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
3476
3376
  }
3477
- function splitGlobList(raw) {
3478
- return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
3377
+ function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
3378
+ if (path.startsWith(shipsPrefix)) {
3379
+ return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
3380
+ }
3381
+ if (path.startsWith(readerFacingPrefix) && path.endsWith(readerFacingSuffix)) {
3382
+ return "reader-facing";
3383
+ }
3384
+ if (isClaudeMdFile(path))
3385
+ return "internal";
3386
+ if (isSpecFile2(path, specPaths))
3387
+ return "spec";
3388
+ if (isProductScopeFile(path))
3389
+ return "product";
3390
+ return null;
3479
3391
  }
3480
- function parseIssueSurface(body) {
3481
- const section = topLevelSectionText(body, "Surface");
3482
- if (section === null)
3483
- return { ok: false, errors: ["no `## Surface` heading found in the body."] };
3484
- const inLine = /^in:\s*(.+)$/im.exec(section);
3485
- const outLine = /^out:\s*(.+)$/im.exec(section);
3486
- const errors = [];
3487
- if (!inLine)
3488
- errors.push("`## Surface` has no `in:` line.");
3489
- if (!outLine)
3490
- errors.push("`## Surface` has no `out:` line.");
3491
- if (errors.length > 0)
3492
- return { ok: false, errors };
3493
- const inGlobs = splitGlobList(inLine[1]);
3494
- const outGlobs = splitGlobList(outLine[1]);
3495
- for (const g of [...inGlobs, ...outGlobs]) {
3496
- if (looksLikeFilePath(g)) {
3497
- errors.push(`\`${g}\` in \`## Surface\` looks like a file path — Surface entries are directory-level globs, never file paths.`);
3498
- }
3392
+ var SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
3393
+ function stripNonProse(path, content) {
3394
+ if (path.endsWith(".md")) {
3395
+ return content.replace(/```.*?```/gs, (m) => m.replace(/[^\n]/g, "")).replace(/`[^`\n]*`/g, (m) => m.replace(/[^\n]/g, ""));
3499
3396
  }
3500
- if (inGlobs.length === 0)
3501
- errors.push("`## Surface`'s `in:` line resolved to zero globs.");
3502
- if (errors.length > 0)
3503
- return { ok: false, errors };
3504
- return { ok: true, value: { in: inGlobs, out: outGlobs } };
3397
+ if (path.endsWith(".tsx") || path.endsWith(".ts")) {
3398
+ return content.replace(/\/\*.*?\*\//gs, (m) => m.replace(/[^\n]/g, "")).replace(/(^|[^:])\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, ""));
3399
+ }
3400
+ return content;
3505
3401
  }
3506
- function globCoversPath(glob, path) {
3507
- const g = glob.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
3508
- const p = path.replace(/\/+$/, "");
3509
- if (g === "*")
3510
- return !p.includes("/");
3511
- return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
3402
+ function stripNonProseForProduct(path, content) {
3403
+ return path.endsWith(".md") ? stripNonProse(path, content) : content;
3512
3404
  }
3513
- function checkSurfaceGlobsResolve(body, resolvesToFile) {
3514
- const surface = parseIssueSurface(body);
3515
- if (!surface.ok)
3516
- return { status: "pass", errors: [] };
3517
- const errors = [];
3518
- for (const glob of surface.value.in) {
3519
- if (!resolvesToFile(glob)) {
3520
- 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.`);
3521
- }
3405
+ function lineAt(content, index) {
3406
+ let line = 1;
3407
+ for (let i = 0;i < index; i++) {
3408
+ if (content.charCodeAt(i) === 10)
3409
+ line++;
3522
3410
  }
3523
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3411
+ return line;
3524
3412
  }
3525
- function checkSurfaceScope(changedFiles, outGlobs) {
3526
- if (outGlobs.length === 0)
3527
- return { ok: true };
3528
- const violations = [];
3529
- for (const file of changedFiles) {
3530
- const glob = outGlobs.find((g) => globCoversPath(g, file));
3531
- if (glob)
3532
- violations.push({ file, glob });
3533
- }
3534
- return violations.length > 0 ? { ok: false, violations } : { ok: true };
3413
+ var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
3414
+ var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
3415
+ var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
3416
+ function legacySlugPattern(legacySlugs) {
3417
+ if (legacySlugs.length === 0)
3418
+ return null;
3419
+ const alternation = legacySlugs.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
3420
+ return new RegExp(`(^|[^a-zA-Z0-9\\n-])(${alternation})([^a-zA-Z0-9\\n-]|$)`, "g");
3535
3421
  }
3536
- var ISSUE_PART_LINE_RE = /^Part\s+(\d+)\s*\(([^)]*)\)\s*[-—–]\s*(.*)$/i;
3537
- function parseIssueParts(body) {
3538
- const section = topLevelSectionText(body, "Parts");
3539
- if (section === null)
3540
- return { ok: false, errors: ["no `## Parts` heading found in the body."] };
3541
- const lines = section.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
3542
- const parts = [];
3543
- const errors = [];
3544
- for (const line of lines) {
3545
- const m = ISSUE_PART_LINE_RE.exec(line);
3546
- if (!m) {
3547
- errors.push(`"${line}" is not a well-formed Parts line — expected \`Part <n> (<refs>) — <outcome>\`.`);
3548
- continue;
3549
- }
3550
- const n = Number.parseInt(m[1], 10);
3551
- const refs = m[2];
3552
- const text = m[3].trim();
3553
- if (text.length === 0) {
3554
- errors.push(`Part ${n} has no outcome text after the dash — every Part states one observable outcome.`);
3555
- continue;
3556
- }
3557
- if (partHasBacktickedPath(text) && partWordCount(stripPartBackticks(text)) < PART_MIN_WORDS_OUTSIDE_BACKTICKS) {
3558
- errors.push(`Part ${n} is little more than a file path — a Part names an outcome and symbols, never a bare path.`);
3422
+ function specGrandfatherPaths(specGrandfather) {
3423
+ return Array.isArray(specGrandfather) ? [...specGrandfather] : Object.keys(specGrandfather);
3424
+ }
3425
+ function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
3426
+ const findings = [];
3427
+ const legacyPattern = legacySlugPattern(legacySlugs);
3428
+ const grandfatheredWhole = new Set(Array.isArray(specGrandfather) ? specGrandfather : []);
3429
+ const limits = new Map(Array.isArray(specGrandfather) ? [] : Object.entries(specGrandfather));
3430
+ const patterns = [
3431
+ { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
3432
+ { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
3433
+ ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
3434
+ ];
3435
+ const productPatterns = [
3436
+ { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
3437
+ ];
3438
+ const specPatterns = [
3439
+ ...patterns,
3440
+ { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
3441
+ ];
3442
+ for (const file of files) {
3443
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
3444
+ if (!cls || cls === "internal")
3445
+ continue;
3446
+ if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
3447
+ continue;
3448
+ if (cls === "spec" && grandfatheredWhole.has(file.path))
3559
3449
  continue;
3450
+ const blocking = cls === "product" || cls === "spec";
3451
+ const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
3452
+ const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
3453
+ const fileFindings = [];
3454
+ for (const { pattern, what, group } of patternsToRun) {
3455
+ pattern.lastIndex = 0;
3456
+ let match = pattern.exec(scrubbed);
3457
+ while (match !== null) {
3458
+ const cited = group !== undefined ? match[group] ?? match[0] : match[0];
3459
+ const citedIndex = match.index + match[0].indexOf(cited);
3460
+ fileFindings.push({
3461
+ file: file.path,
3462
+ line: lineAt(scrubbed, citedIndex),
3463
+ message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
3464
+ blocking
3465
+ });
3466
+ match = pattern.exec(scrubbed);
3467
+ }
3560
3468
  }
3561
- const objectiveIds = [...refs.matchAll(/O(\d+)/g)].map((r) => Number.parseInt(r[1], 10));
3562
- parts.push({ n, objectiveIds, text });
3563
- }
3564
- if (parts.length === 0) {
3565
- errors.push("the `## Parts` section has no well-formed `Part <n> (<refs>) — <outcome>` lines.");
3566
- }
3567
- if (errors.length > 0)
3568
- return { ok: false, errors };
3569
- return { ok: true, value: parts };
3570
- }
3571
- function checkPartsCiteDefinedObjectives(body) {
3572
- const parts = parseIssueParts(body);
3573
- const objectives = objectivesOf(body);
3574
- if (!parts.ok || !objectives.ok)
3575
- return { status: "pass", errors: [] };
3576
- const definedIds = new Set(objectives.objectives.map((o) => Number.parseInt(o.id.slice(1), 10)));
3577
- const errors = [];
3578
- for (const part of parts.value) {
3579
- for (const objectiveId of part.objectiveIds) {
3580
- if (!definedIds.has(objectiveId)) {
3581
- errors.push(`issue-validation Parts: Part ${part.n} cites O${objectiveId}, which the Issue's own \`## Objectives\` section does not define.`);
3469
+ const limit = cls === "spec" ? limits.get(file.path) : undefined;
3470
+ if (limit !== undefined) {
3471
+ if (fileFindings.length <= limit)
3472
+ continue;
3473
+ for (const f of fileFindings) {
3474
+ f.message += `; ${file.path} carries ${fileFindings.length} such findings, over its proseGates.specGrandfather limit of ${limit}`;
3582
3475
  }
3583
3476
  }
3477
+ findings.push(...fileFindings);
3584
3478
  }
3585
- return { status: errors.length > 0 ? "fail" : "pass", errors };
3586
- }
3587
- function isTaskIssueLabelSet(labels) {
3588
- return hasLabel("tranche", labels);
3589
- }
3590
- function checkTrancheLabelPresence(_body, _labels) {
3591
- return { status: "pass", errors: [] };
3592
- }
3593
- function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
3594
- if (!isTaskIssueLabelSet(labels))
3595
- return { status: "pass", errors: [] };
3596
- if (resolvedMilestoneTitle === null)
3597
- return { status: "pass", errors: [] };
3598
- if (currentMilestoneTitle === resolvedMilestoneTitle)
3599
- return { status: "pass", errors: [] };
3600
- return {
3601
- status: "fail",
3602
- errors: [
3603
- `issue-validation milestone attach: this task Issue's tranche label resolves to Milestone "${resolvedMilestoneTitle}", but its live Milestone is ${currentMilestoneTitle === null ? "unset" : `"${currentMilestoneTitle}"`} — attach it to "${resolvedMilestoneTitle}".`
3604
- ]
3605
- };
3606
- }
3607
- var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
3608
- function isControlCodePoint(codePoint) {
3609
- return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
3610
- }
3611
- function isDisplayControlCodePoint(codePoint) {
3612
- return codePoint >= 8203 && codePoint <= 8207 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 || codePoint === 65279;
3479
+ return findings;
3613
3480
  }
3614
- var MESSAGE_VALUE_COUNT_MAX = 5;
3615
- function residueForMessage(values) {
3616
- const shown = values.slice(0, MESSAGE_VALUE_COUNT_MAX).map((v) => `\`${forMessage(v)}\``);
3617
- const rest = values.length - shown.length;
3618
- return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(", ");
3481
+ function escapeTerm(term) {
3482
+ return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3619
3483
  }
3620
- var MESSAGE_VALUE_MAX = 64;
3621
- function forMessage(value) {
3622
- const kept = [];
3623
- for (const ch of value.replace(/\s+/g, " ")) {
3624
- const codePoint = ch.codePointAt(0) ?? 0;
3625
- if (isControlCodePoint(codePoint) || isDisplayControlCodePoint(codePoint))
3626
- continue;
3627
- kept.push(ch);
3628
- }
3629
- const cleaned = kept.join("").trim();
3630
- if (cleaned.length === 0)
3631
- return "(unprintable)";
3632
- const points = Array.from(cleaned);
3633
- return points.length > MESSAGE_VALUE_MAX ? `${points.slice(0, MESSAGE_VALUE_MAX).join("")}…` : cleaned;
3484
+ function containsWholeWord(text, term) {
3485
+ const escaped = escapeTerm(term);
3486
+ const re = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)`, "i");
3487
+ return re.test(text);
3634
3488
  }
3635
- function checkProjectsRegistered(body, _labels, registeredNames) {
3636
- if (registeredNames.length === 0)
3637
- return { status: "pass", errors: [] };
3638
- const field = projectFieldFromBody(body);
3639
- if (!field.declared)
3640
- return { status: "pass", errors: [] };
3641
- const known = new Set(registeredNames.map((n) => n.trim()));
3642
- const registeredList = [...registeredNames].map(forMessage).join(", ");
3643
- const errors = [];
3644
- if (field.unreadable) {
3645
- return {
3646
- status: "fail",
3647
- errors: [
3648
- `issue-validation project registry: the body has an unterminated code fence, so its \`**Project:**\` field could not be read reliably — the fence runs to end of body (CommonMark, and how the forge renders it), swallowing everything after it including the foot field where the declaration lives by convention. Read from the raw body the field says ${residueForMessage(field.unparsed) || "(nothing)"}, but a line inside a swallowed region may be a quoted example rather than a real declaration, so this gate refuses rather than guessing which. Balance the fences — every opening run of backticks or tildes needs a closing run at least as long — and the field reads normally.`
3649
- ]
3650
- };
3651
- }
3652
- const unregistered = field.names.filter((p) => !known.has(p));
3653
- if (unregistered.length > 0) {
3654
- const caseHints = unregistered.map((p) => {
3655
- const row = [...known].find((k) => k.toLowerCase() === p.toLowerCase());
3656
- return row ? `\`${forMessage(p)}\` differs from the registered \`${forMessage(row)}\` only in case` : null;
3657
- }).filter((h) => h !== null);
3658
- errors.push(`issue-validation project registry: the \`**Project:**\` field declares ${unregistered.map(forMessage).join(", ")} — no such row in \`.vinaya/projects.md\`, which is the authority for valid project names (registered: ${registeredList}). Fix the name, or register the project with \`vinaya init product <name> --path <folder>\` first; an unregistered project has no specs to read and no per-project state to update.${caseHints.length > 0 ? ` Note: ${caseHints.join("; ")} — project names are matched exactly, because every downstream consumer compares them literally.` : ""} This reads the same field \`projectsFromBody\` derives the task's project from, so a name here that is not a row is a task that resolves to a project that does not exist.`);
3659
- }
3660
- if (field.names.length === 0) {
3661
- const residue = field.unparsed.length > 0 ? ` — ${residueForMessage(field.unparsed)}` : " — the field is empty";
3662
- errors.push(`issue-validation project registry: the \`**Project:**\` field is present but resolves to no project name${residue} (registered: ${registeredList}). A project name is a slug (\`[a-z0-9][a-z0-9-]*\`, matched exactly); prose, a parenthetical, or a sentence in this field resolves to no project at all, and this gate cannot check a name it never receives — which is how a declaration like this used to pass. Write the registered name on its own, or register the project with \`vinaya init product <name> --path <folder>\` first. If the task genuinely touches no registered project, omit the field rather than explaining its absence inside it — \`checkIssueRationale\` already requires the \`Project(s) + blast radius\` narrative field for that.`);
3663
- } else if (field.unparsed.length > 0) {
3664
- errors.push(`issue-validation project registry: the \`**Project:**\` field declares a value that is not a project name — ${residueForMessage(field.unparsed)} (registered: ${registeredList}). The rest of the field parsed, so this is a name the gate silently could not check rather than a field it could not read at all. A project name is a slug (\`[a-z0-9][a-z0-9-]*\`, matched exactly); write it on its own, or drop it if it names no project.`);
3489
+ function findWholeWordLine(content, term) {
3490
+ const lines = content.split(`
3491
+ `);
3492
+ let lineNo = 0;
3493
+ for (const line of lines) {
3494
+ lineNo++;
3495
+ if (containsWholeWord(line, term))
3496
+ return lineNo;
3665
3497
  }
3666
- return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
3667
- }
3668
- 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;
3669
- var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
3670
-
3671
- // ../../packages/aeg-core/src/task-branch-identity.ts
3672
- var ISSUE_BRANCH_PATTERN = /^task\/issue-(\d+)$/;
3673
- var TRANCHE_BRANCH_PATTERN = /^task\/([^/]+)\/([^/]+)$/;
3674
- function parseTaskBranchIdentity(branch) {
3675
- const issueMatch = ISSUE_BRANCH_PATTERN.exec(branch);
3676
- if (issueMatch)
3677
- return { kind: "issue", issueNumber: Number(issueMatch[1]) };
3678
- const trancheMatch = TRANCHE_BRANCH_PATTERN.exec(branch);
3679
- if (trancheMatch)
3680
- return { kind: "tranche", tranche: trancheMatch[1], taskId: trancheMatch[2] };
3681
3498
  return null;
3682
3499
  }
3683
-
3684
- // ../../packages/aeg-core/src/coherence-checks.ts
3685
- var COHERENCE_ENFORCED_FROM = "2026-07-01";
3686
- function isGrandfathered(isoDate) {
3687
- if (!isoDate)
3688
- return false;
3689
- return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
3500
+ function definesOrLinksGlossary(content, term) {
3501
+ const escaped = escapeTerm(term);
3502
+ const definesInline = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)[^\\n]{0,3}—`, "i").test(content);
3503
+ if (definesInline)
3504
+ return true;
3505
+ return /docs\/glossary|glossary\.md/i.test(content);
3690
3506
  }
3691
- var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
3692
- function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
3693
- const failures = [];
3694
- for (const e of entries) {
3695
- if (!e.facts)
3696
- continue;
3697
- if (e.facts.stateReason === "not_planned")
3507
+ function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
3508
+ const findings = [];
3509
+ for (const file of files) {
3510
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3511
+ if (!cls || !SWEPT_CLASSES.has(cls))
3698
3512
  continue;
3699
- if (e.facts.issueState === "closed" && e.facts.prState !== "merged") {
3700
- const handClosed = e.facts.stateReason === "completed" && isPrincipal(e.facts.closedByActor, principalAllowlist);
3701
- if (handClosed)
3513
+ const scrubbed = stripNonProse(file.path, file.content);
3514
+ for (const term of glossaryTerms) {
3515
+ const line = findWholeWordLine(scrubbed, term);
3516
+ if (line === null)
3702
3517
  continue;
3703
- failures.push({
3704
- code: "closed-without-merge",
3705
- issue: e.task.issue,
3706
- tranche: e.trancheSlug,
3707
- task: e.task.id,
3708
- reason: `Issue closed but closing PR is not merged (prState: ${e.facts.prState})`,
3709
- grandfathered: isGrandfathered(e.facts.closedAt)
3710
- });
3711
- }
3712
- }
3713
- const activeFails = failures.filter((f) => !f.grandfathered);
3714
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3715
- return {
3716
- check: "A1",
3717
- status,
3718
- failures,
3719
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3720
- };
3721
- }
3722
- function checkA3(entries) {
3723
- const failures = [];
3724
- for (const e of entries) {
3725
- if (!e.facts)
3726
- continue;
3727
- if (e.facts.prState === "merged" && e.facts.issueState !== "closed") {
3728
- failures.push({
3729
- code: "auto-close-misfire",
3730
- issue: e.task.issue,
3731
- tranche: e.trancheSlug,
3732
- task: e.task.id,
3733
- reason: "Closing PR is merged but Issue is still open (GitHub auto-close misfire)",
3734
- grandfathered: isGrandfathered(e.facts.mergedAt)
3518
+ if (definesOrLinksGlossary(scrubbed, term))
3519
+ continue;
3520
+ findings.push({
3521
+ file: file.path,
3522
+ line,
3523
+ message: `uses coined term "${term}" without defining it inline or linking the glossary`,
3524
+ blocking: false
3735
3525
  });
3736
3526
  }
3737
3527
  }
3738
- const activeFails = failures.filter((f) => !f.grandfathered);
3739
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3740
- return {
3741
- check: "A3",
3742
- status,
3743
- failures,
3744
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3745
- };
3528
+ return findings;
3746
3529
  }
3747
- function checkT1(entries) {
3748
- const failures = [];
3749
- for (const e of entries) {
3750
- if (e.task.issue === null)
3751
- continue;
3752
- if (e.facts === undefined) {
3753
- failures.push({
3754
- code: "phantom-issue-ref",
3755
- issue: e.task.issue,
3756
- tranche: e.trancheSlug,
3757
- task: e.task.id,
3758
- reason: `Issue #${e.task.issue} in topology does not resolve to a real GitHub Issue`
3759
- });
3760
- }
3761
- }
3762
- return { check: "T1", status: failures.length > 0 ? "fail" : "pass", failures };
3763
- }
3764
- function checkT2(openIssuesBySlug, topologyIssuesBySlug, ciTrancheSlug) {
3765
- const failures = [];
3766
- for (const [slug, openNums] of openIssuesBySlug) {
3767
- if (ciTrancheSlug && slug !== ciTrancheSlug)
3768
- continue;
3769
- const topologySet = topologyIssuesBySlug.get(slug) ?? new Set;
3770
- for (const num of openNums) {
3771
- if (!topologySet.has(num)) {
3772
- failures.push({
3773
- code: "orphan-task",
3774
- issue: num,
3775
- tranche: slug,
3776
- reason: `Issue #${num} is open and labeled ${trancheLabel(slug)} but does not appear in the topology file`
3777
- });
3530
+ var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
3531
+ var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
3532
+ function extractComments(path, content) {
3533
+ if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
3534
+ return content.replace(/[^\n]/g, "");
3535
+ let state = "code";
3536
+ let out = "";
3537
+ const n = content.length;
3538
+ let i = 0;
3539
+ const blank = (ch) => ch === `
3540
+ ` ? `
3541
+ ` : " ";
3542
+ while (i < n) {
3543
+ const c = content[i];
3544
+ const next = i + 1 < n ? content[i + 1] : "";
3545
+ if (state === "code") {
3546
+ if (c === "/" && next === "/") {
3547
+ state = "line-comment";
3548
+ out += c;
3549
+ i++;
3550
+ continue;
3778
3551
  }
3779
- }
3780
- }
3781
- return { check: "T2", status: failures.length > 0 ? "fail" : "pass", failures };
3782
- }
3783
- function scopeT2ToPlanPr(result, isPlanPr) {
3784
- if (isPlanPr || result.status !== "fail")
3785
- return result;
3786
- return {
3787
- ...result,
3788
- status: "info",
3789
- note: result.note ?? "T2 findings are non-blocking outside plan PRs (point-of-power principle) — see aeg-root/enforcement.md."
3790
- };
3791
- }
3792
- function checkT3(entries, ciTrancheSlug, enrichedEntries, forgeUnavailableSlugs) {
3793
- const preEnforcement = new Set;
3794
- if (enrichedEntries) {
3795
- for (const e of enrichedEntries) {
3796
- if (isGrandfathered(e.facts?.closedAt) || isGrandfathered(e.facts?.mergedAt)) {
3797
- preEnforcement.add(e.trancheSlug);
3552
+ if (c === "/" && next === "*") {
3553
+ state = "block-comment";
3554
+ out += c;
3555
+ i++;
3556
+ continue;
3557
+ }
3558
+ if (c === "'") {
3559
+ state = "single-quote";
3560
+ out += blank(c);
3561
+ i++;
3562
+ continue;
3563
+ }
3564
+ if (c === '"') {
3565
+ state = "double-quote";
3566
+ out += blank(c);
3567
+ i++;
3568
+ continue;
3569
+ }
3570
+ if (c === "`") {
3571
+ state = "template";
3572
+ out += blank(c);
3573
+ i++;
3574
+ continue;
3798
3575
  }
3576
+ out += blank(c);
3577
+ i++;
3578
+ continue;
3799
3579
  }
3800
- }
3801
- const failures = [];
3802
- for (const e of entries) {
3803
- if (!e.archived && e.task.issue === null) {
3804
- if (ciTrancheSlug && e.trancheSlug !== ciTrancheSlug)
3580
+ if (state === "line-comment") {
3581
+ if (c === `
3582
+ `) {
3583
+ state = "code";
3584
+ out += `
3585
+ `;
3586
+ i++;
3805
3587
  continue;
3806
- if (forgeUnavailableSlugs?.has(e.trancheSlug)) {
3807
- failures.push({
3808
- code: "tbd-in-active-tranche",
3809
- issue: null,
3810
- tranche: e.trancheSlug,
3811
- task: e.task.id,
3812
- reason: `Task ${e.task.id} in active tranche has no Issue ref (#TBD or empty), but forge data for tranche "${e.trancheSlug}" was unavailable — cannot evaluate grandfather status, not silently failed`,
3813
- grandfathered: true
3814
- });
3588
+ }
3589
+ out += c;
3590
+ i++;
3591
+ continue;
3592
+ }
3593
+ if (state === "block-comment") {
3594
+ if (c === "*" && next === "/") {
3595
+ out += c;
3596
+ out += next;
3597
+ state = "code";
3598
+ i += 2;
3815
3599
  continue;
3816
3600
  }
3817
- failures.push({
3818
- code: "tbd-in-active-tranche",
3819
- issue: null,
3820
- tranche: e.trancheSlug,
3821
- task: e.task.id,
3822
- reason: `Task ${e.task.id} in active tranche has no Issue ref (#TBD or empty) — the model requires all active tasks to have Issue numbers`,
3823
- grandfathered: preEnforcement.has(e.trancheSlug)
3824
- });
3601
+ out += c === `
3602
+ ` ? `
3603
+ ` : c;
3604
+ i++;
3605
+ continue;
3606
+ }
3607
+ const closer = state === "single-quote" ? "'" : state === "double-quote" ? '"' : "`";
3608
+ if (c === "\\") {
3609
+ out += blank(c);
3610
+ i++;
3611
+ if (i < n) {
3612
+ out += blank(content[i]);
3613
+ i++;
3614
+ }
3615
+ continue;
3616
+ }
3617
+ if (c === closer) {
3618
+ state = "code";
3619
+ out += blank(c);
3620
+ i++;
3621
+ continue;
3825
3622
  }
3623
+ out += blank(c);
3624
+ i++;
3826
3625
  }
3827
- const activeFails = failures.filter((f) => !f.grandfathered);
3828
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3829
- return {
3830
- check: "T3",
3831
- status,
3832
- failures,
3833
- note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
3834
- };
3626
+ return out;
3835
3627
  }
3836
- function checkD1(entries, issueToEntry, taskToEntry) {
3837
- const failures = [];
3838
- for (const e of entries) {
3839
- if (!e.facts)
3628
+ function checkSourceComments(files, allowlist = []) {
3629
+ const findings = [];
3630
+ const allowed = new Set(allowlist);
3631
+ const patterns = [
3632
+ { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
3633
+ { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
3634
+ ];
3635
+ for (const file of files) {
3636
+ if (!file.path.endsWith(".ts"))
3840
3637
  continue;
3841
- if (e.facts.prState !== "open")
3638
+ if (allowed.has(file.path))
3842
3639
  continue;
3843
- for (const dep of e.task.dependsOn) {
3844
- const depEntry = resolveDepEntry(dep, e.trancheSlug, issueToEntry, taskToEntry);
3845
- if (!depEntry)
3846
- continue;
3847
- const sameTask = depEntry.trancheSlug === e.trancheSlug && depEntry.task.id === e.task.id;
3848
- const sameIssue = depEntry.task.issue !== null && e.task.issue !== null && depEntry.task.issue === e.task.issue;
3849
- if (sameTask || sameIssue) {
3850
- failures.push({
3851
- code: "d1-self-dependency",
3852
- issue: e.task.issue,
3853
- tranche: e.trancheSlug,
3854
- task: e.task.id,
3855
- reason: `INTERNAL: parsed a self-dependency (depends-on ${dep}) — this is a parser bug in parseRationaleDeps, not a real dependency. Please report it upstream.`
3856
- });
3857
- continue;
3858
- }
3859
- const depFacts = depEntry.facts;
3860
- const depClosed = depFacts?.issueState === "closed";
3861
- if (!depClosed) {
3862
- failures.push({
3863
- code: "dispatched-on-unmet-deps",
3864
- issue: e.task.issue,
3865
- tranche: e.trancheSlug,
3866
- task: e.task.id,
3867
- reason: `Task has open PR but depends-on ${dep} (issue #${depEntry.task.issue ?? "?"}) is not closed`
3640
+ const comments = extractComments(file.path, file.content);
3641
+ for (const { pattern, what } of patterns) {
3642
+ pattern.lastIndex = 0;
3643
+ let match = pattern.exec(comments);
3644
+ while (match !== null) {
3645
+ findings.push({
3646
+ file: file.path,
3647
+ line: lineAt(comments, match.index),
3648
+ message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
3649
+ blocking: false
3868
3650
  });
3651
+ match = pattern.exec(comments);
3869
3652
  }
3870
3653
  }
3871
3654
  }
3872
- return { check: "D1", status: failures.length > 0 ? "fail" : "pass", failures };
3655
+ return findings;
3873
3656
  }
3874
- function resolveDepEntry(dep, trancheSlug, issueToEntry, taskToEntry) {
3875
- const issueMatch = dep.match(/^#(\d+)$/);
3876
- if (issueMatch?.[1])
3877
- return issueToEntry.get(Number(issueMatch[1]));
3878
- return taskToEntry.get(`${trancheSlug}/${dep}`) ?? taskToEntry.get(dep);
3657
+ function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
3658
+ return [
3659
+ ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
3660
+ ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
3661
+ ];
3879
3662
  }
3880
- function checkR1(issuesBySlug, grandfatheredIssues, registeredNames = [], objectivesSinceIssue) {
3881
- const failures = [];
3882
- for (const [slug, issues] of issuesBySlug) {
3883
- for (const issue of issues) {
3884
- if (!isTaskIssueLabelSet(issue.labels))
3885
- continue;
3886
- const errors = [
3887
- ...checkIssueRationale(issue.body).errors,
3888
- ...checkProjectsRegistered(issue.body, issue.labels, registeredNames).errors,
3889
- ...checkIssueObjectives(issue.body, issue.number, objectivesSinceIssue).errors,
3890
- ...checkPartsCiteDefinedObjectives(issue.body).errors
3891
- ];
3892
- if (errors.length === 0)
3893
- continue;
3894
- failures.push({
3895
- code: "missing-rationale-field",
3896
- issue: issue.number,
3897
- tranche: slug,
3898
- reason: `Issue #${issue.number} fails the rationale gate: ${errors.join(" | ")}`,
3899
- grandfathered: grandfatheredIssues.has(issue.number)
3900
- });
3901
- }
3663
+ function parseGlossaryTerms(glossaryContent) {
3664
+ const terms = [];
3665
+ const re = /^\*\*(.+?)\*\* —/gm;
3666
+ let match = re.exec(glossaryContent);
3667
+ while (match !== null) {
3668
+ if (match[1] !== undefined)
3669
+ terms.push(match[1]);
3670
+ match = re.exec(glossaryContent);
3902
3671
  }
3903
- const activeFails = failures.filter((f) => !f.grandfathered);
3904
- const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
3905
- return {
3906
- check: "R1",
3907
- status,
3908
- failures,
3909
- note: status === "info" ? `${failures.length} grandfathered task Issue(s) predate this check's grammar (rationale fields and/or the project registry)` : undefined
3910
- };
3672
+ return terms;
3911
3673
  }
3912
- function checkL1(files, entriesBySlug) {
3913
- const failures = [];
3914
- for (const f of files) {
3915
- if (f.archived)
3916
- continue;
3917
- const entries = entriesBySlug.get(f.slug) ?? [];
3918
- const withFacts = entries.filter((e) => e.facts !== undefined);
3919
- if (withFacts.length === 0)
3674
+
3675
+ // ../../packages/aeg-core/src/quoted-command.ts
3676
+ var QUOTED_COMMAND_SHIPS_PREFIX = "aeg-root/";
3677
+ var QUOTED_COMMAND_SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
3678
+ var START_PATTERN = /<!--\s*AEG:QUOTES-FILE:START:(\S+?)\s*-->/g;
3679
+ var END_PATTERN = /<!--\s*AEG:QUOTES-FILE:END\s*-->/;
3680
+ function isValidCitedFilePath(path) {
3681
+ if (path.length === 0)
3682
+ return false;
3683
+ if (path.startsWith("/") || path.startsWith("\\"))
3684
+ return false;
3685
+ if (/^[A-Za-z]:[\\/]/.test(path))
3686
+ return false;
3687
+ return !path.split(/[\\/]+/).includes("..");
3688
+ }
3689
+ function quotedCommandLineAt(content, index) {
3690
+ let line = 1;
3691
+ for (let i = 0;i < index; i++) {
3692
+ if (content.charCodeAt(i) === 10)
3693
+ line++;
3694
+ }
3695
+ return line;
3696
+ }
3697
+ function extractQuotedText(raw) {
3698
+ const trimmed = raw.trim();
3699
+ const fenced = /^(?:`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n?(?:`{3,}|~{3,})$/.exec(trimmed);
3700
+ if (fenced)
3701
+ return (fenced[1] ?? "").trim();
3702
+ const inline = /^`([^`]+)`$/.exec(trimmed);
3703
+ if (inline)
3704
+ return (inline[1] ?? "").trim();
3705
+ return trimmed;
3706
+ }
3707
+ function findQuotesInFile(path, content) {
3708
+ const masked = maskCode(content);
3709
+ const quotes = [];
3710
+ START_PATTERN.lastIndex = 0;
3711
+ let start = START_PATTERN.exec(masked);
3712
+ while (start !== null) {
3713
+ const citedFile = start[1];
3714
+ const innerStart = start.index + start[0].length;
3715
+ const end = END_PATTERN.exec(masked.slice(innerStart));
3716
+ if (end === null) {
3717
+ START_PATTERN.lastIndex = innerStart;
3718
+ start = START_PATTERN.exec(masked);
3920
3719
  continue;
3921
- const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
3922
- if (allClosed) {
3923
- failures.push({
3924
- code: "archive-recommended",
3925
- tranche: f.slug,
3926
- reason: "Active tranche has no open task-Issues — consider archiving to completed/"
3927
- });
3928
3720
  }
3721
+ const innerEnd = innerStart + end.index;
3722
+ if (isValidCitedFilePath(citedFile)) {
3723
+ const quotedText = extractQuotedText(content.slice(innerStart, innerEnd));
3724
+ if (quotedText.length > 0) {
3725
+ quotes.push({ file: path, line: quotedCommandLineAt(content, innerStart), quotedText, citedFile });
3726
+ }
3727
+ }
3728
+ START_PATTERN.lastIndex = innerEnd + end[0].length;
3729
+ start = START_PATTERN.exec(masked);
3929
3730
  }
3930
- return {
3931
- check: "L1",
3932
- status: "info",
3933
- failures,
3934
- note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
3935
- };
3936
- }
3937
- function checkL3(files) {
3938
- const active = files.filter((f) => !f.archived);
3939
- return {
3940
- check: "L3",
3941
- status: "info",
3942
- failures: [],
3943
- note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
3944
- };
3731
+ return quotes;
3945
3732
  }
3946
- function extractClosesReferences(prBody) {
3947
- const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
3948
- const stripped = stripCode(prBody);
3949
- const searchIn = anchoredRegion(stripped, "CLOSES") ?? stripped;
3950
- const referenced = new Set;
3951
- for (const hit of searchIn.matchAll(closesPattern)) {
3952
- referenced.add(Number(hit[1]));
3733
+ function findCitedQuotes(files, readerFacingPrefix, readerFacingSuffix, shipsPrefix = QUOTED_COMMAND_SHIPS_PREFIX) {
3734
+ const quotes = [];
3735
+ for (const file of files) {
3736
+ const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
3737
+ if (!cls || !QUOTED_COMMAND_SWEPT_CLASSES.has(cls))
3738
+ continue;
3739
+ quotes.push(...findQuotesInFile(file.path, file.content));
3953
3740
  }
3954
- return referenced;
3741
+ return quotes;
3955
3742
  }
3956
- function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
3957
- const referenced = extractClosesReferences(prBody);
3958
- if (taskIssueRefs) {
3959
- for (const n of referenced) {
3960
- const ref = taskIssueRefs.get(n);
3961
- if (!ref)
3962
- continue;
3963
- const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
3964
- if (branch !== expectedBranch) {
3965
- return {
3966
- ok: false,
3967
- message: `closes-n-reverse: branch "${branch}" closes #${n} (task ${ref.taskId} of tranche "${ref.trancheSlug}") but is not named "${expectedBranch}" — rename the branch and re-push, or if this work is intentionally outside AEG's dispatch flow, remove the Closes reference.`
3968
- };
3969
- }
3743
+ function evaluateCitedQuotes(citedQuotes, citedFileContents) {
3744
+ const findings = [];
3745
+ for (const quote of citedQuotes) {
3746
+ const content = citedFileContents.get(quote.citedFile);
3747
+ if (content === undefined) {
3748
+ findings.push({
3749
+ file: quote.file,
3750
+ line: quote.line,
3751
+ citedFile: quote.citedFile,
3752
+ quotedText: quote.quotedText,
3753
+ message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but that file could not be read`
3754
+ });
3755
+ continue;
3970
3756
  }
3971
- }
3972
- const ref = parseTaskBranchIdentity(branch);
3973
- if (!ref)
3974
- return { ok: true };
3975
- if (ref.kind === "issue") {
3976
- const expectedIssue = ref.issueNumber;
3977
- if (!referenced.has(expectedIssue)) {
3978
- return {
3979
- ok: false,
3980
- expectedIssue,
3981
- message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
3982
- };
3757
+ if (!content.includes(quote.quotedText)) {
3758
+ findings.push({
3759
+ file: quote.file,
3760
+ line: quote.line,
3761
+ citedFile: quote.citedFile,
3762
+ quotedText: quote.quotedText,
3763
+ message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but \`${quote.citedFile}\` no longer contains that text verbatim`
3764
+ });
3983
3765
  }
3984
- return { ok: true, expectedIssue };
3985
- }
3986
- const trancheSlug = ref.tranche;
3987
- const taskId = ref.taskId;
3988
- const trancheFile = trancheFiles.find((f) => f.slug === trancheSlug);
3989
- if (!trancheFile) {
3990
- return {
3991
- ok: false,
3992
- message: `closes-n: branch "${branch}" references tranche "${trancheSlug}" but no topology file found at aeg-root/tranches/${trancheSlug}.md. Ensure the tranche file exists before opening the PR.`
3993
- };
3994
- }
3995
- const task = trancheFile.tranche.tasks.find((t) => t.id === taskId);
3996
- if (!task) {
3997
- return {
3998
- ok: false,
3999
- message: `closes-n: branch "${branch}" references task "${taskId}" not found in ${trancheSlug} topology. Verify the task ID matches the tranche file.`
4000
- };
4001
- }
4002
- if (task.issue === null) {
4003
- return {
4004
- ok: false,
4005
- message: `closes-n: task "${taskId}" in "${trancheSlug}" has no Issue number (#TBD). The Planner must cut the Issue before this PR can be validated.`
4006
- };
4007
- }
4008
- const expectedIssue = task.issue;
4009
- if (!referenced.has(expectedIssue)) {
4010
- return {
4011
- ok: false,
4012
- expectedIssue,
4013
- message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for task "${taskId}" in tranche "${trancheSlug}"). Add it to the PR body Summary section.`
4014
- };
4015
3766
  }
4016
- return { ok: true, expectedIssue };
3767
+ return findings;
4017
3768
  }
4018
- // ../../packages/aeg-core/src/archive-task.ts
4019
- function closesRefs(text) {
4020
- return [...new Set([...text.matchAll(/Closes #(\d+)/gi)].map((m) => Number(m[1])))];
3769
+
3770
+ // ../../packages/aeg-core/src/issue-validation.ts
3771
+ function hasRationaleField(body, labelPattern) {
3772
+ const re = new RegExp(`(?:\\*\\*|^#{1,4}\\s+)\\s*(?:${labelPattern})`, "im");
3773
+ return re.test(body);
4021
3774
  }
4022
- function extractIssue(body) {
4023
- const stripped = stripCode(body);
4024
- const bodyNums = closesRefs(stripped);
4025
- const anchored = anchoredRegion(stripped, "CLOSES");
4026
- if (anchored !== null) {
4027
- const anchorNums = closesRefs(anchored);
4028
- if (anchorNums.length === 0)
4029
- return { issue: null, extraIssues: bodyNums, outsideHeader: false };
4030
- const issue = anchorNums[0];
4031
- return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: false };
3775
+ var RATIONALE_FIELDS = [
3776
+ { name: "Boundary", pattern: "Boundary" },
3777
+ { name: "Sizing", pattern: "Sizing" },
3778
+ { name: "Project(s) + blast radius", pattern: "Project\\(s\\)|Project(?:s)?\\s*\\+|blast radius" },
3779
+ { name: "Dependency rationale", pattern: "Dependency rationale|Depends[- ]on" },
3780
+ { name: "Traps to avoid", pattern: "Traps" },
3781
+ { name: "Suggested agent-class", pattern: "(?:Suggested\\s+)?agent-class" },
3782
+ { name: "Stop-and-escalate", pattern: "Stop-and-escalate" },
3783
+ { name: "Docs to keep coherent", pattern: "Docs to keep coherent|§7" }
3784
+ ];
3785
+ var DEPENDENCY_RATIONALE_FIELD_NAME = "Dependency rationale";
3786
+ function checkIssueRationale(body) {
3787
+ const errors = [];
3788
+ for (const f of RATIONALE_FIELDS) {
3789
+ if (!hasRationaleField(body, f.pattern)) {
3790
+ errors.push(`issue-validation ${f.name}: rationale field not found in the Issue body — every task Issue carries the full Planner's rationale (aeg-root/contracts/planner-brief.md).`);
3791
+ continue;
3792
+ }
3793
+ if (f.name === DEPENDENCY_RATIONALE_FIELD_NAME && !SECTION_HEADER.test(body)) {
3794
+ errors.push(`issue-validation ${f.name}: rationale field found, but not in the form amend-deps requires — ` + "write `**Dependency rationale** — …`, not `**Dependency rationale:** …`. " + "`amendRationaleDeps` (the only sanctioned way to edit Depends-on/Conflicts-with) locates this " + "section by the exact anchor `**Dependency rationale**`; a colon inside the bold breaks that match " + "and the Issue becomes unamendable.");
3795
+ }
4032
3796
  }
4033
- const headerNums = closesRefs(headerRegion(stripped));
4034
- if (bodyNums.length === 0)
4035
- return { issue: null, extraIssues: [], outsideHeader: false };
4036
- const issue = headerNums.length > 0 ? headerNums[0] : bodyNums[0];
4037
- return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: headerNums.length === 0 };
4038
- }
4039
- // ../../packages/aeg-core/src/review-input-manifest.ts
4040
- import { createHash as createHash4 } from "node:crypto";
4041
- function briefHash(brief) {
4042
- return createHash4("sha256").update(`${brief}
4043
- `).digest("hex");
3797
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
4044
3798
  }
4045
- function policyDigest(policy) {
4046
- return createHash4("sha256").update(JSON.stringify({
4047
- codeReviewThreshold: policy.codeReviewThreshold,
4048
- securityThreshold: policy.securityThreshold,
4049
- maxRounds: policy.maxRounds
4050
- })).digest("hex");
3799
+ var OBJECTIVES_SINCE_ISSUE = 404;
3800
+ function checkIssueObjectives(body, issueNumber, sinceIssue = OBJECTIVES_SINCE_ISSUE) {
3801
+ if (sinceIssue !== null && issueNumber !== null && issueNumber < sinceIssue)
3802
+ return { status: "pass", errors: [] };
3803
+ const result = objectivesOf(body);
3804
+ if (result.ok)
3805
+ return { status: "pass", errors: [] };
3806
+ return { status: "fail", errors: result.errors.map((e) => `issue-validation objectives: ${e}`) };
4051
3807
  }
4052
- function isBoundToHead(echoed, headSha) {
4053
- if (!echoed.headSha)
4054
- return false;
4055
- return headSha.toLowerCase().startsWith(echoed.headSha.toLowerCase());
3808
+ function topLevelSectionText(body, headingName) {
3809
+ const headingRe = new RegExp(`^##[ \\t]*${headingName}[ \\t]*$`, "im");
3810
+ const heading = headingRe.exec(body);
3811
+ if (!heading)
3812
+ return null;
3813
+ const afterHeading = body.slice(heading.index + heading[0].length);
3814
+ const next = /^##[ \t]/m.exec(afterHeading);
3815
+ return next ? afterHeading.slice(0, next.index) : afterHeading;
4056
3816
  }
4057
- function isBoundByPatchIdentity(echoed, headSha, patchIdOf) {
4058
- if (patchIdOf === undefined || !echoed.headSha)
4059
- return false;
4060
- const judged = patchIdOf(echoed.headSha);
4061
- const current = patchIdOf(headSha);
4062
- if (judged === null || current === null)
4063
- return false;
4064
- return judged === current;
3817
+ function partHasBacktickedPath(text) {
3818
+ let i = 0;
3819
+ while (i < text.length) {
3820
+ const start = text.indexOf("`", i);
3821
+ if (start === -1)
3822
+ return false;
3823
+ const end = text.indexOf("`", start + 1);
3824
+ if (end === -1)
3825
+ return false;
3826
+ if (text.slice(start + 1, end).includes("/"))
3827
+ return true;
3828
+ i = end + 1;
3829
+ }
3830
+ return false;
4065
3831
  }
4066
- function isBoundToBase(echoed, currentBase) {
4067
- if (currentBase === null)
4068
- return true;
4069
- if (!echoed.baseSha)
4070
- return false;
4071
- return currentBase.toLowerCase().startsWith(echoed.baseSha.toLowerCase());
3832
+ var PART_MIN_WORDS_OUTSIDE_BACKTICKS = 3;
3833
+ function stripPartBackticks(text) {
3834
+ return text.replace(/`[^`\n]*`/g, " ");
4072
3835
  }
4073
- function isBoundToObjectives(echoed, currentVersion) {
4074
- if (currentVersion === null)
4075
- return true;
4076
- return echoed.objectivesVersion === currentVersion;
3836
+ function partWordCount(text) {
3837
+ return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length;
4077
3838
  }
4078
- function isBoundToRulings(echoed, currentOrdinal) {
4079
- if (echoed.rulingOrdinal === null)
4080
- return currentOrdinal === 0;
4081
- return echoed.rulingOrdinal === currentOrdinal;
3839
+ function looksLikeFilePath(entry) {
3840
+ const stripped = entry.replace(/\/\*\*?$/, "");
3841
+ const lastSegment = stripped.split("/").pop() ?? stripped;
3842
+ const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment);
3843
+ return extMatch !== null && extMatch.index > 0;
4082
3844
  }
4083
- function isBoundToBriefHash(echoed, currentHash) {
4084
- if (currentHash === null)
4085
- return true;
4086
- return echoed.briefHash === currentHash;
3845
+ function splitGlobList(raw) {
3846
+ return raw.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
4087
3847
  }
4088
- function isBoundToPolicy(echoed, currentDigest) {
4089
- return echoed.policyDigest === currentDigest;
3848
+ function parseIssueSurface(body) {
3849
+ const section = topLevelSectionText(body, "Surface");
3850
+ if (section === null)
3851
+ return { ok: false, errors: ["no `## Surface` heading found in the body."] };
3852
+ const inLine = /^in:\s*(.+)$/im.exec(section);
3853
+ const outLine = /^out:\s*(.+)$/im.exec(section);
3854
+ const errors = [];
3855
+ if (!inLine)
3856
+ errors.push("`## Surface` has no `in:` line.");
3857
+ if (!outLine)
3858
+ errors.push("`## Surface` has no `out:` line.");
3859
+ if (errors.length > 0)
3860
+ return { ok: false, errors };
3861
+ const inGlobs = splitGlobList(inLine[1]);
3862
+ const outGlobs = splitGlobList(outLine[1]);
3863
+ for (const g of [...inGlobs, ...outGlobs]) {
3864
+ if (looksLikeFilePath(g)) {
3865
+ errors.push(`\`${g}\` in \`## Surface\` looks like a file path — Surface entries are directory-level globs, never file paths.`);
3866
+ }
3867
+ }
3868
+ if (inGlobs.length === 0)
3869
+ errors.push("`## Surface`'s `in:` line resolved to zero globs.");
3870
+ if (errors.length > 0)
3871
+ return { ok: false, errors };
3872
+ return { ok: true, value: { in: inGlobs, out: outGlobs } };
4090
3873
  }
4091
- function compareManifest(echoed, current, patchIdOf) {
4092
- const exactHead = isBoundToHead(echoed, current.headSha);
4093
- const patchHead = exactHead ? false : isBoundByPatchIdentity(echoed, current.headSha, patchIdOf);
4094
- const head = exactHead || patchHead;
4095
- const echoedShaLen = echoed.baseSha?.length ?? 0;
4096
- const currentShaLen = current.baseSha?.length ?? 0;
4097
- const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4098
- const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4099
- const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4100
- const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4101
- const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4102
- const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4103
- return {
4104
- bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4105
- head,
4106
- base,
4107
- briefHash: briefHashBound,
4108
- objectivesVersion,
4109
- rulingOrdinal,
4110
- policyDigest: policyDigestBound
4111
- };
3874
+ function globCoversPath(glob, path) {
3875
+ const g = glob.replace(/\/\*\*?$/, "").replace(/\/+$/, "");
3876
+ const p = path.replace(/\/+$/, "");
3877
+ if (g === "*")
3878
+ return !p.includes("/");
3879
+ return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`);
4112
3880
  }
4113
-
4114
- // ../../packages/aeg-core/src/review-gate.ts
4115
- function checkReviewGate(input) {
4116
- const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
4117
- const waived = isWaiverLabelActorVerified({
4118
- label: WAIVER_LABEL_REVIEW,
4119
- labels: input.labels,
4120
- labelActor: input.waiverLabelActor,
4121
- principalAllowlist
4122
- });
4123
- if (waived) {
4124
- return {
4125
- verdict: "pass",
4126
- reason: `\`${WAIVER_LABEL_REVIEW}\` label is actor-verified — review requirement waived for this PR.`,
4127
- waived: true
4128
- };
3881
+ function checkSurfaceGlobsResolve(body, resolvesToFile) {
3882
+ const surface = parseIssueSurface(body);
3883
+ if (!surface.ok)
3884
+ return { status: "pass", errors: [] };
3885
+ const errors = [];
3886
+ for (const glob of surface.value.in) {
3887
+ if (!resolvesToFile(glob)) {
3888
+ 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.`);
3889
+ }
4129
3890
  }
4130
- const verified = input.comments.filter((c) => isPrincipal(c.author, principalAllowlist));
4131
- const ignoredCount = input.comments.filter((c) => !isPrincipal(c.author, principalAllowlist) && c.body.includes("VERDICT")).length;
4132
- const verifiedBodies = verified.map((c) => c.body);
4133
- const codeReview = extractCodeReviewVerdict(verifiedBodies);
4134
- const security = extractSecurityReviewVerdict(verifiedBodies);
4135
- const policy = input.policy ?? DEFAULT_REVIEW_POLICY;
4136
- let codeReviewPolicyEvaluation;
4137
- let securityPolicyEvaluation;
4138
- try {
4139
- codeReviewPolicyEvaluation = evaluateCodeReview(consequentialFindings(codeReview.findingSeverities), policy);
4140
- securityPolicyEvaluation = evaluateSecurityReview(consequentialFindings(security.findingSeverities), policy);
4141
- } catch (err) {
4142
- return {
4143
- verdict: "fail",
4144
- reason: `a verdict comment carries a finding severity this repository's policy does not recognize: ${err instanceof Error ? err.message : String(err)}`,
4145
- waived: false
4146
- };
3891
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
3892
+ }
3893
+ function checkSurfaceScope(changedFiles, outGlobs) {
3894
+ if (outGlobs.length === 0)
3895
+ return { ok: true };
3896
+ const violations = [];
3897
+ for (const file of changedFiles) {
3898
+ const glob = outGlobs.find((g) => globCoversPath(g, file));
3899
+ if (glob)
3900
+ violations.push({ file, glob });
4147
3901
  }
4148
- const codeReviewTextClean = codeReview.value === "APPROVE";
4149
- const securityTextClean = security.value === "PASS";
4150
- const codeReviewPolicyClean = codeReviewPolicyEvaluation.outcome === "clean";
4151
- const securityPolicyClean = securityPolicyEvaluation.outcome === "clean";
4152
- const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4153
- const securityClean = securityTextClean && securityPolicyClean;
4154
- const currentManifest = {
4155
- headSha: input.headSha,
4156
- baseSha: input.baseSha ?? null,
4157
- briefHash: input.briefHash ?? null,
4158
- objectivesVersion: input.objectivesVersion,
4159
- rulingOrdinal: input.rulingOrdinal,
4160
- policyDigest: policyDigest(policy)
4161
- };
4162
- const codeReviewEchoed = {
4163
- headSha: codeReview.headSha,
4164
- baseSha: codeReview.baseSha,
4165
- briefHash: codeReview.briefHash,
4166
- objectivesVersion: codeReview.objectivesVersion,
4167
- rulingOrdinal: codeReview.rulingOrdinal,
4168
- policyDigest: codeReview.policyDigest
4169
- };
4170
- const securityEchoed = {
4171
- headSha: security.headSha,
4172
- baseSha: security.baseSha,
4173
- briefHash: security.briefHash,
4174
- objectivesVersion: security.objectivesVersion,
4175
- rulingOrdinal: security.rulingOrdinal,
4176
- policyDigest: security.policyDigest
4177
- };
4178
- const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
4179
- const securityBinding = compareManifest(securityEchoed, currentManifest, input.patchIdOf);
4180
- const codeReviewBound = codeReviewBinding.head;
4181
- const securityBound = securityBinding.head;
4182
- const codeReviewObjectivesBound = codeReviewBinding.objectivesVersion;
4183
- const securityObjectivesBound = securityBinding.objectivesVersion;
4184
- const codeReviewRulingsBound = codeReviewBinding.rulingOrdinal;
4185
- const securityRulingsBound = securityBinding.rulingOrdinal;
4186
- if (codeReviewClean && codeReviewBinding.bound && securityClean && securityBinding.bound) {
4187
- return {
4188
- verdict: "pass",
4189
- reason: `code-reviewer verdict is a clean APPROVE and security-review verdict is a clean PASS, both covering head ${input.headSha}.`,
4190
- waived: false
4191
- };
3902
+ return violations.length > 0 ? { ok: false, violations } : { ok: true };
3903
+ }
3904
+ var ISSUE_PART_LINE_RE = /^Part\s+(\d+)\s*\(([^)]*)\)\s*[-—–]\s*(.*)$/i;
3905
+ function parseIssueParts(body) {
3906
+ const section = topLevelSectionText(body, "Parts");
3907
+ if (section === null)
3908
+ return { ok: false, errors: ["no `## Parts` heading found in the body."] };
3909
+ const lines = section.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
3910
+ const parts = [];
3911
+ const errors = [];
3912
+ for (const line of lines) {
3913
+ const m = ISSUE_PART_LINE_RE.exec(line);
3914
+ if (!m) {
3915
+ errors.push(`"${line}" is not a well-formed Parts line — expected \`Part <n> (<refs>) — <outcome>\`.`);
3916
+ continue;
3917
+ }
3918
+ const n = Number.parseInt(m[1], 10);
3919
+ const refs = m[2];
3920
+ const text = m[3].trim();
3921
+ if (text.length === 0) {
3922
+ errors.push(`Part ${n} has no outcome text after the dash — every Part states one observable outcome.`);
3923
+ continue;
3924
+ }
3925
+ if (partHasBacktickedPath(text) && partWordCount(stripPartBackticks(text)) < PART_MIN_WORDS_OUTSIDE_BACKTICKS) {
3926
+ errors.push(`Part ${n} is little more than a file path — a Part names an outcome and symbols, never a bare path.`);
3927
+ continue;
3928
+ }
3929
+ const objectiveIds = [...refs.matchAll(/O(\d+)/g)].map((r) => Number.parseInt(r[1], 10));
3930
+ parts.push({ n, objectiveIds, text });
4192
3931
  }
4193
- const problems = [];
4194
- if (!codeReviewTextClean) {
4195
- problems.push(`code-reviewer verdict is not a clean APPROVE (found: ${codeReview.value})`);
4196
- } else if (!codeReviewPolicyClean) {
4197
- problems.push(`code-reviewer verdict says APPROVE but carries a finding (${codeReviewPolicyEvaluation.blockingFindings.map((f) => f.severity).join(", ")}) at or above this repository's code-review policy threshold (${policy.codeReviewThreshold}) — a reviewer's own APPROVE never overrides policy`);
4198
- } else if (!codeReviewBound) {
4199
- problems.push(`the newest code-review verdict covers ${codeReview.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4200
- } else if (!codeReviewBinding.base) {
4201
- problems.push(`the newest code-review verdict was cast against base ${codeReview.baseSha ?? "no recorded base"}, the PR's base is now ${currentManifest.baseSha ?? "unresolved"} (a base-only change under an unchanged candidate — same patch text on a new base is not automatically equivalent)`);
4202
- } else if (!codeReviewObjectivesBound) {
4203
- problems.push(`the newest code-review verdict was cast against objectives version ${codeReview.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4204
- } else if (!codeReviewRulingsBound) {
4205
- problems.push(`the newest code-review verdict was cast against ruling ordinal ${codeReview.rulingOrdinal ?? "none"}, a newer ruling (ruling ${input.rulingOrdinal}) is now posted on this PR`);
4206
- } else if (!codeReviewBinding.briefHash) {
4207
- 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"}`);
4208
- } else if (!codeReviewBinding.policyDigest) {
4209
- 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}`);
3932
+ if (parts.length === 0) {
3933
+ errors.push("the `## Parts` section has no well-formed `Part <n> (<refs>) — <outcome>` lines.");
4210
3934
  }
4211
- if (!securityTextClean) {
4212
- problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
4213
- } else if (!securityPolicyClean) {
4214
- problems.push(`security-review verdict says PASS but carries a finding (${securityPolicyEvaluation.blockingFindings.map((f) => f.severity).join(", ")}) at or above this repository's security policy threshold (${policy.securityThreshold}) — a reviewer's own PASS never overrides policy`);
4215
- } else if (!securityBound) {
4216
- problems.push(`the newest security-review verdict covers ${security.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4217
- } else if (!securityBinding.base) {
4218
- problems.push(`the newest security-review verdict was cast against base ${security.baseSha ?? "no recorded base"}, the PR's base is now ${currentManifest.baseSha ?? "unresolved"} (a base-only change under an unchanged candidate — same patch text on a new base is not automatically equivalent)`);
4219
- } else if (!securityObjectivesBound) {
4220
- problems.push(`the newest security-review verdict was cast against objectives version ${security.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4221
- } else if (!securityRulingsBound) {
4222
- problems.push(`the newest security-review verdict was cast against ruling ordinal ${security.rulingOrdinal ?? "none"}, a newer ruling (ruling ${input.rulingOrdinal}) is now posted on this PR`);
4223
- } else if (!securityBinding.briefHash) {
4224
- 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"}`);
4225
- } else if (!securityBinding.policyDigest) {
4226
- 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}`);
3935
+ if (errors.length > 0)
3936
+ return { ok: false, errors };
3937
+ return { ok: true, value: parts };
3938
+ }
3939
+ function checkPartsCiteDefinedObjectives(body) {
3940
+ const parts = parseIssueParts(body);
3941
+ const objectives = objectivesOf(body);
3942
+ if (!parts.ok || !objectives.ok)
3943
+ return { status: "pass", errors: [] };
3944
+ const definedIds = new Set(objectives.objectives.map((o) => Number.parseInt(o.id.slice(1), 10)));
3945
+ const errors = [];
3946
+ for (const part of parts.value) {
3947
+ for (const objectiveId of part.objectiveIds) {
3948
+ if (!definedIds.has(objectiveId)) {
3949
+ errors.push(`issue-validation Parts: Part ${part.n} cites O${objectiveId}, which the Issue's own \`## Objectives\` section does not define.`);
3950
+ }
3951
+ }
4227
3952
  }
4228
- const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
3953
+ return { status: errors.length > 0 ? "fail" : "pass", errors };
3954
+ }
3955
+ function isTaskIssueLabelSet(labels) {
3956
+ return hasLabel("tranche", labels);
3957
+ }
3958
+ function checkTrancheLabelPresence(_body, _labels) {
3959
+ return { status: "pass", errors: [] };
3960
+ }
3961
+ function checkMilestoneAttach(labels, currentMilestoneTitle, resolvedMilestoneTitle) {
3962
+ if (!isTaskIssueLabelSet(labels))
3963
+ return { status: "pass", errors: [] };
3964
+ if (resolvedMilestoneTitle === null)
3965
+ return { status: "pass", errors: [] };
3966
+ if (currentMilestoneTitle === resolvedMilestoneTitle)
3967
+ return { status: "pass", errors: [] };
4229
3968
  return {
4230
- verdict: "fail",
4231
- reason: `${problems.join("; ")}. A principal can apply an actor-verified \`${WAIVER_LABEL_REVIEW}\` label to skip this requirement, or post the missing/clean verdict comment(s).${ignoredNote}`,
4232
- waived: false
3969
+ status: "fail",
3970
+ errors: [
3971
+ `issue-validation milestone attach: this task Issue's tranche label resolves to Milestone "${resolvedMilestoneTitle}", but its live Milestone is ${currentMilestoneTitle === null ? "unset" : `"${currentMilestoneTitle}"`} — attach it to "${resolvedMilestoneTitle}".`
3972
+ ]
4233
3973
  };
4234
3974
  }
4235
- var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4236
- var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4237
- function isChangesetsReleasePr(branch, author, expectedAuthor) {
4238
- return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
3975
+ var TYPE_LABEL_IDS = LABELS.filter((l) => l.category === "type").map((l) => l.id);
3976
+ function isControlCodePoint(codePoint) {
3977
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
4239
3978
  }
4240
- // ../../packages/aeg-core/src/ruling-ordinal.ts
4241
- var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4242
- function newestPrincipalRulingOrdinal(comments, allowlist) {
4243
- let best = 0;
4244
- for (const c of comments) {
4245
- if (!isPrincipal(c.author, allowlist))
4246
- continue;
4247
- const firstLine = (c.body.split(`
4248
- `)[0] ?? "").trim();
4249
- const m = RULING_MARKER_ORDINAL.exec(firstLine);
4250
- if (!m)
4251
- continue;
4252
- const k = Number.parseInt(m[1], 10);
4253
- if (k > best)
4254
- best = k;
4255
- }
4256
- return best;
3979
+ function isDisplayControlCodePoint(codePoint) {
3980
+ return codePoint >= 8203 && codePoint <= 8207 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8294 && codePoint <= 8297 || codePoint === 65279;
4257
3981
  }
4258
- // ../../packages/aeg-core/src/markdown-table.ts
4259
- function splitRow(line) {
4260
- const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
4261
- return trimmed.split("|").map((cell) => cell.trim());
3982
+ var MESSAGE_VALUE_COUNT_MAX = 5;
3983
+ function residueForMessage(values) {
3984
+ const shown = values.slice(0, MESSAGE_VALUE_COUNT_MAX).map((v) => `\`${forMessage(v)}\``);
3985
+ const rest = values.length - shown.length;
3986
+ return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(", ");
4262
3987
  }
4263
- var TABLE_ROW_PATTERN = /^\s*\|.*\|\s*$/;
4264
- var SEPARATOR_ROW_PATTERN = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
4265
- function findTable(lines, fromLine, stopAtHeading = true) {
4266
- let i = fromLine - 1;
4267
- while (i < lines.length) {
4268
- const line = lines[i] ?? "";
4269
- if (stopAtHeading && i > fromLine - 1 && /^##\s/.test(line))
4270
- return null;
4271
- if (TABLE_ROW_PATTERN.test(line)) {
4272
- const headerLine = line;
4273
- const sepLine = lines[i + 1] ?? "";
4274
- if (!SEPARATOR_ROW_PATTERN.test(sepLine)) {
4275
- i++;
4276
- continue;
4277
- }
4278
- const headers = splitRow(headerLine);
4279
- const rows = [];
4280
- let j = i + 2;
4281
- while (j < lines.length && TABLE_ROW_PATTERN.test(lines[j] ?? "")) {
4282
- rows.push({ cells: splitRow(lines[j] ?? ""), line: j + 1 });
4283
- j++;
4284
- }
4285
- return { headers, rows };
4286
- }
4287
- i++;
3988
+ var MESSAGE_VALUE_MAX = 64;
3989
+ function forMessage(value) {
3990
+ const kept = [];
3991
+ for (const ch of value.replace(/\s+/g, " ")) {
3992
+ const codePoint = ch.codePointAt(0) ?? 0;
3993
+ if (isControlCodePoint(codePoint) || isDisplayControlCodePoint(codePoint))
3994
+ continue;
3995
+ kept.push(ch);
4288
3996
  }
4289
- return null;
3997
+ const cleaned = kept.join("").trim();
3998
+ if (cleaned.length === 0)
3999
+ return "(unprintable)";
4000
+ const points = Array.from(cleaned);
4001
+ return points.length > MESSAGE_VALUE_MAX ? `${points.slice(0, MESSAGE_VALUE_MAX).join("")}…` : cleaned;
4290
4002
  }
4291
- function findHeadingLine(lines, pattern) {
4292
- for (let i = 0;i < lines.length; i++) {
4293
- if (pattern.test(lines[i] ?? ""))
4294
- return i + 1;
4003
+ function checkProjectsRegistered(body, _labels, registeredNames) {
4004
+ if (registeredNames.length === 0)
4005
+ return { status: "pass", errors: [] };
4006
+ const field = projectFieldFromBody(body);
4007
+ if (!field.declared)
4008
+ return { status: "pass", errors: [] };
4009
+ const known = new Set(registeredNames.map((n) => n.trim()));
4010
+ const registeredList = [...registeredNames].map(forMessage).join(", ");
4011
+ const errors = [];
4012
+ if (field.unreadable) {
4013
+ return {
4014
+ status: "fail",
4015
+ errors: [
4016
+ `issue-validation project registry: the body has an unterminated code fence, so its \`**Project:**\` field could not be read reliably — the fence runs to end of body (CommonMark, and how the forge renders it), swallowing everything after it including the foot field where the declaration lives by convention. Read from the raw body the field says ${residueForMessage(field.unparsed) || "(nothing)"}, but a line inside a swallowed region may be a quoted example rather than a real declaration, so this gate refuses rather than guessing which. Balance the fences — every opening run of backticks or tildes needs a closing run at least as long — and the field reads normally.`
4017
+ ]
4018
+ };
4295
4019
  }
4296
- return null;
4020
+ const unregistered = field.names.filter((p) => !known.has(p));
4021
+ if (unregistered.length > 0) {
4022
+ const caseHints = unregistered.map((p) => {
4023
+ const row = [...known].find((k) => k.toLowerCase() === p.toLowerCase());
4024
+ return row ? `\`${forMessage(p)}\` differs from the registered \`${forMessage(row)}\` only in case` : null;
4025
+ }).filter((h) => h !== null);
4026
+ errors.push(`issue-validation project registry: the \`**Project:**\` field declares ${unregistered.map(forMessage).join(", ")} — no such row in \`.vinaya/projects.md\`, which is the authority for valid project names (registered: ${registeredList}). Fix the name, or register the project with \`vinaya init product <name> --path <folder>\` first; an unregistered project has no specs to read and no per-project state to update.${caseHints.length > 0 ? ` Note: ${caseHints.join("; ")} — project names are matched exactly, because every downstream consumer compares them literally.` : ""} This reads the same field \`projectsFromBody\` derives the task's project from, so a name here that is not a row is a task that resolves to a project that does not exist.`);
4027
+ }
4028
+ if (field.names.length === 0) {
4029
+ const residue = field.unparsed.length > 0 ? ` — ${residueForMessage(field.unparsed)}` : " — the field is empty";
4030
+ errors.push(`issue-validation project registry: the \`**Project:**\` field is present but resolves to no project name${residue} (registered: ${registeredList}). A project name is a slug (\`[a-z0-9][a-z0-9-]*\`, matched exactly); prose, a parenthetical, or a sentence in this field resolves to no project at all, and this gate cannot check a name it never receives — which is how a declaration like this used to pass. Write the registered name on its own, or register the project with \`vinaya init product <name> --path <folder>\` first. If the task genuinely touches no registered project, omit the field rather than explaining its absence inside it — \`checkIssueRationale\` already requires the \`Project(s) + blast radius\` narrative field for that.`);
4031
+ } else if (field.unparsed.length > 0) {
4032
+ errors.push(`issue-validation project registry: the \`**Project:**\` field declares a value that is not a project name — ${residueForMessage(field.unparsed)} (registered: ${registeredList}). The rest of the field parsed, so this is a name the gate silently could not check rather than a field it could not read at all. A project name is a slug (\`[a-z0-9][a-z0-9-]*\`, matched exactly); write it on its own, or drop it if it names no project.`);
4033
+ }
4034
+ return errors.length > 0 ? { status: "fail", errors } : { status: "pass", errors: [] };
4297
4035
  }
4298
- // ../../packages/aeg-core/src/diagram-model.ts
4299
- import matter from "gray-matter";
4036
+ 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;
4037
+ var DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, "gi");
4038
+ var FILE_EXTENSIONS = new Set([
4039
+ "ts",
4040
+ "tsx",
4041
+ "js",
4042
+ "jsx",
4043
+ "mjs",
4044
+ "cjs",
4045
+ "json",
4046
+ "jsonc",
4047
+ "md",
4048
+ "mdx",
4049
+ "yml",
4050
+ "yaml",
4051
+ "txt",
4052
+ "sh",
4053
+ "lock",
4054
+ "toml",
4055
+ "ndjson",
4056
+ "html",
4057
+ "css"
4058
+ ]);
4300
4059
 
4301
- // ../../packages/aeg-core/src/registry-parse.ts
4302
- var RING_HEADINGS = [
4303
- { ring: "ring0", pattern: /^##\s+Ring 0\b/ },
4304
- { ring: "ring1", pattern: /^##\s+Ring 1\b/ },
4305
- { ring: "ring2", pattern: /^##\s+Ring 2\b/ }
4306
- ];
4307
- function stripBackticks2(cell) {
4308
- const trimmed = cell.trim();
4309
- if (trimmed.length >= 2 && trimmed.startsWith("`") && trimmed.endsWith("`")) {
4310
- return trimmed.slice(1, -1);
4311
- }
4312
- return trimmed;
4060
+ // ../../packages/aeg-core/src/task-branch-identity.ts
4061
+ var ISSUE_BRANCH_PATTERN = /^task\/issue-(\d+)$/;
4062
+ var TRANCHE_BRANCH_PATTERN = /^task\/([^/]+)\/([^/]+)$/;
4063
+ function parseTaskBranchIdentity(branch) {
4064
+ const issueMatch = ISSUE_BRANCH_PATTERN.exec(branch);
4065
+ if (issueMatch)
4066
+ return { kind: "issue", issueNumber: Number(issueMatch[1]) };
4067
+ const trancheMatch = TRANCHE_BRANCH_PATTERN.exec(branch);
4068
+ if (trancheMatch)
4069
+ return { kind: "tranche", tranche: trancheMatch[1], taskId: trancheMatch[2] };
4070
+ return null;
4313
4071
  }
4314
- function stripBold(cell) {
4315
- return cell.trim().replace(/\*\*/g, "");
4072
+
4073
+ // ../../packages/aeg-core/src/coherence-checks.ts
4074
+ var COHERENCE_ENFORCED_FROM = "2026-07-01";
4075
+ function isGrandfathered(isoDate) {
4076
+ if (!isoDate)
4077
+ return false;
4078
+ return isoDate.slice(0, 10) < COHERENCE_ENFORCED_FROM;
4316
4079
  }
4317
- function parseEnforcementRegistry(content) {
4318
- const lines = content.split(`
4319
- `);
4320
- const result = [];
4321
- for (const { ring, pattern } of RING_HEADINGS) {
4322
- const headingLine = findHeadingLine(lines, pattern);
4323
- if (headingLine === null)
4080
+ var R1_GRANDFATHERED_ISSUES = new Set([279, 280, 281, 282]);
4081
+ function checkA1(entries, principalAllowlist = PRINCIPAL_ALLOWLIST) {
4082
+ const failures = [];
4083
+ for (const e of entries) {
4084
+ if (!e.facts)
4324
4085
  continue;
4325
- const table = findTable(lines, headingLine + 1);
4326
- if (!table)
4086
+ if (e.facts.stateReason === "not_planned")
4327
4087
  continue;
4328
- const descriptionIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "description");
4329
- const implementationIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "implementation");
4330
- const audienceIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "audience");
4331
- for (const row of table.rows) {
4332
- const cells = row.cells;
4333
- if (cells.length < 3)
4088
+ if (e.facts.issueState === "closed" && e.facts.prState !== "merged") {
4089
+ const handClosed = e.facts.stateReason === "completed" && isPrincipal(e.facts.closedByActor, principalAllowlist);
4090
+ if (handClosed)
4334
4091
  continue;
4335
- const action = stripBold(cells[0] ?? "");
4336
- const summary = stripBackticks2(cells[1] ?? "");
4337
- const category = stripBackticks2(cells[2] ?? "");
4338
- const implementation = stripBackticks2((implementationIndex === -1 ? cells[cells.length - 1] : cells[implementationIndex]) ?? "");
4339
- const description = descriptionIndex === -1 ? undefined : stripBackticks2(cells[descriptionIndex] ?? "") || undefined;
4340
- const specIndex = (audienceIndex === -1 ? cells.length - 1 : audienceIndex) - 1;
4341
- const spec = specIndex >= 3 ? stripBackticks2(cells[specIndex] ?? "") || undefined : undefined;
4342
- const audience = audienceIndex === -1 ? "repo-own" : stripBackticks2(cells[audienceIndex] ?? "") === "product" ? "product" : "repo-own";
4343
- result.push({ ring, action, summary, category, description, spec, implementation, audience, line: row.line });
4344
- }
4345
- }
4346
- return result;
4347
- }
4348
- // ../../packages/aeg-core/src/registry-checks.ts
4349
- function checkG1(rows, existsFn) {
4350
- const findings = [];
4351
- for (const row of rows) {
4352
- if (row.implementation === "")
4353
- continue;
4354
- if (!existsFn(row.implementation)) {
4355
- findings.push({
4356
- row: row.action,
4357
- path: row.implementation,
4358
- reason: `${row.ring} row "${row.action}" names implementation "${row.implementation}", which does not exist on disk`
4092
+ failures.push({
4093
+ code: "closed-without-merge",
4094
+ issue: e.task.issue,
4095
+ tranche: e.trancheSlug,
4096
+ task: e.task.id,
4097
+ reason: `Issue closed but closing PR is not merged (prState: ${e.facts.prState})`,
4098
+ grandfathered: isGrandfathered(e.facts.closedAt)
4359
4099
  });
4360
4100
  }
4361
4101
  }
4362
- return { check: "G1", status: findings.length > 0 ? "fail" : "pass", findings };
4102
+ const activeFails = failures.filter((f) => !f.grandfathered);
4103
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4104
+ return {
4105
+ check: "A1",
4106
+ status,
4107
+ failures,
4108
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4109
+ };
4363
4110
  }
4364
- var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
4365
- var NON_GATE_BIN_NAMES = NON_GATE_BINS;
4366
- var TWIN_CANDIDATE_EXCEPTIONS = {
4367
- "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)',
4368
- "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)`,
4369
- "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
4370
- };
4371
- var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
4372
- function checkG2(rows, candidateFiles) {
4373
- const implementations = new Set(rows.map((r) => r.implementation).filter((p) => p !== ""));
4374
- const claimedNames = new Set(rows.flatMap((r) => claimedCheckNames(r.implementation)));
4375
- const findings = [];
4376
- for (const path of candidateFiles) {
4377
- if (implementations.has(path))
4378
- continue;
4379
- if (path.startsWith(AEG_CORE_BIN_PATH_PREFIX) && NON_GATE_BIN_NAMES.includes(basenameNoExt(path)))
4380
- continue;
4381
- if (NON_GATE_HOOK_SCRIPTS.includes(path))
4382
- continue;
4383
- if (path in TWIN_CANDIDATE_EXCEPTIONS)
4384
- continue;
4385
- const candidateNames = claimedCheckNames(path);
4386
- if (candidateNames.length > 0 && candidateNames.some((n) => claimedNames.has(n)))
4111
+ function checkA3(entries) {
4112
+ const failures = [];
4113
+ for (const e of entries) {
4114
+ if (!e.facts)
4387
4115
  continue;
4388
- findings.push({
4389
- path,
4390
- reason: `"${path}" is not named as the implementation of any row in enforcement.md's ring tables`
4391
- });
4392
- }
4393
- for (const row of rows) {
4394
- const carriesPlaceholder = [row.summary, row.description, row.spec].some((cell) => cell === SCAFFOLD_PLACEHOLDER);
4395
- if (carriesPlaceholder) {
4396
- findings.push({
4397
- row: row.action,
4398
- path: row.implementation,
4399
- reason: `${row.ring} row "${row.action}" still carries the scaffold placeholder marker — the why is owed`
4400
- });
4401
- }
4402
- }
4403
- return { check: "G2", status: findings.length > 0 ? "fail" : "pass", findings };
4404
- }
4405
- function checkG3(ring0Rows, crossingFiles) {
4406
- const ring0Implementations = new Set(ring0Rows.map((r) => r.implementation));
4407
- const findings = [];
4408
- for (const path of crossingFiles) {
4409
- if (!ring0Implementations.has(path)) {
4410
- findings.push({
4411
- path,
4412
- reason: `"${path}" makes a GitHub-crossing call but is not named by any Ring-0 row's implementation — a seventh, unlisted way into GitHub`
4116
+ if (e.facts.prState === "merged" && e.facts.issueState !== "closed") {
4117
+ failures.push({
4118
+ code: "auto-close-misfire",
4119
+ issue: e.task.issue,
4120
+ tranche: e.trancheSlug,
4121
+ task: e.task.id,
4122
+ reason: "Closing PR is merged but Issue is still open (GitHub auto-close misfire)",
4123
+ grandfathered: isGrandfathered(e.facts.mergedAt)
4413
4124
  });
4414
4125
  }
4415
4126
  }
4416
- return { check: "G3", status: findings.length > 0 ? "fail" : "pass", findings };
4127
+ const activeFails = failures.filter((f) => !f.grandfathered);
4128
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4129
+ return {
4130
+ check: "A3",
4131
+ status,
4132
+ failures,
4133
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4134
+ };
4417
4135
  }
4418
- function checkG4(content, resolveFn) {
4419
- const cited = new Set;
4420
- for (const hit of content.matchAll(/#(\d{3,})\b/g)) {
4421
- cited.add(Number(hit[1]));
4422
- }
4423
- const findings = [];
4424
- for (const n of cited) {
4425
- if (!resolveFn(n)) {
4426
- findings.push({
4427
- reason: `#${n} is cited in enforcement.md but does not resolve to a real Issue or PR in the forge`
4136
+ function checkT1(entries) {
4137
+ const failures = [];
4138
+ for (const e of entries) {
4139
+ if (e.task.issue === null)
4140
+ continue;
4141
+ if (e.facts === undefined) {
4142
+ failures.push({
4143
+ code: "phantom-issue-ref",
4144
+ issue: e.task.issue,
4145
+ tranche: e.trancheSlug,
4146
+ task: e.task.id,
4147
+ reason: `Issue #${e.task.issue} in topology does not resolve to a real GitHub Issue`
4428
4148
  });
4429
4149
  }
4430
4150
  }
4431
- return { check: "G4", status: findings.length > 0 ? "fail" : "pass", findings };
4151
+ return { check: "T1", status: failures.length > 0 ? "fail" : "pass", failures };
4432
4152
  }
4433
- function checkG5(roles, contracts) {
4434
- const roleIds = new Set(roles.map((r) => r.role_id));
4435
- const findings = [];
4436
- for (const contract of contracts) {
4437
- if (!roleIds.has(contract.producer)) {
4438
- findings.push({
4439
- path: contract.file,
4440
- reason: `contract "${contract.file}" names producer "${contract.producer}", which is not a real role_id`
4441
- });
4442
- }
4443
- if (!roleIds.has(contract.consumer)) {
4444
- findings.push({
4445
- path: contract.file,
4446
- reason: `contract "${contract.file}" names consumer "${contract.consumer}", which is not a real role_id`
4447
- });
4448
- }
4449
- }
4450
- for (const role of roles) {
4451
- if (role.performs.length === 0) {
4452
- findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty performs array` });
4453
- }
4454
- if (role.refuses_when.trim() === "") {
4455
- findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty refuses_when` });
4153
+ function checkT2(openIssuesBySlug, topologyIssuesBySlug, ciTrancheSlug) {
4154
+ const failures = [];
4155
+ for (const [slug, openNums] of openIssuesBySlug) {
4156
+ if (ciTrancheSlug && slug !== ciTrancheSlug)
4157
+ continue;
4158
+ const topologySet = topologyIssuesBySlug.get(slug) ?? new Set;
4159
+ for (const num of openNums) {
4160
+ if (!topologySet.has(num)) {
4161
+ failures.push({
4162
+ code: "orphan-task",
4163
+ issue: num,
4164
+ tranche: slug,
4165
+ reason: `Issue #${num} is open and labeled ${trancheLabel(slug)} but does not appear in the topology file`
4166
+ });
4167
+ }
4456
4168
  }
4457
4169
  }
4458
- return { check: "G5", status: findings.length > 0 ? "fail" : "pass", findings };
4170
+ return { check: "T2", status: failures.length > 0 ? "fail" : "pass", failures };
4459
4171
  }
4460
- var SHIPPED_BIN_PATH_PREFIX = "apps/cli/src/checks/bin/check-";
4461
- var AEG_CORE_BIN_PATH_PREFIX = "packages/aeg-core/bin/";
4462
- function basenameNoExt(path) {
4463
- const base = path.slice(path.lastIndexOf("/") + 1);
4464
- return base.replace(/\.ts$/, "");
4172
+ function scopeT2ToPlanPr(result, isPlanPr) {
4173
+ if (isPlanPr || result.status !== "fail")
4174
+ return result;
4175
+ return {
4176
+ ...result,
4177
+ status: "info",
4178
+ note: result.note ?? "T2 findings are non-blocking outside plan PRs (point-of-power principle) — see aeg-root/enforcement.md."
4179
+ };
4465
4180
  }
4466
- function claimedCheckNames(implementation) {
4467
- if (implementation.startsWith(SHIPPED_BIN_PATH_PREFIX) && implementation.endsWith(".ts")) {
4468
- return [implementation.slice(SHIPPED_BIN_PATH_PREFIX.length, -".ts".length)];
4181
+ function checkT3(entries, ciTrancheSlug, enrichedEntries, forgeUnavailableSlugs) {
4182
+ const preEnforcement = new Set;
4183
+ if (enrichedEntries) {
4184
+ for (const e of enrichedEntries) {
4185
+ if (isGrandfathered(e.facts?.closedAt) || isGrandfathered(e.facts?.mergedAt)) {
4186
+ preEnforcement.add(e.trancheSlug);
4187
+ }
4188
+ }
4469
4189
  }
4470
- if (implementation.startsWith(AEG_CORE_BIN_PATH_PREFIX)) {
4471
- const audience = GATE_AUDIENCE[basenameNoExt(implementation)];
4472
- if (audience && isShipped(audience)) {
4473
- return Array.isArray(audience.shippedAs) ? audience.shippedAs : [audience.shippedAs];
4190
+ const failures = [];
4191
+ for (const e of entries) {
4192
+ if (!e.archived && e.task.issue === null) {
4193
+ if (ciTrancheSlug && e.trancheSlug !== ciTrancheSlug)
4194
+ continue;
4195
+ if (forgeUnavailableSlugs?.has(e.trancheSlug)) {
4196
+ failures.push({
4197
+ code: "tbd-in-active-tranche",
4198
+ issue: null,
4199
+ tranche: e.trancheSlug,
4200
+ task: e.task.id,
4201
+ reason: `Task ${e.task.id} in active tranche has no Issue ref (#TBD or empty), but forge data for tranche "${e.trancheSlug}" was unavailable — cannot evaluate grandfather status, not silently failed`,
4202
+ grandfathered: true
4203
+ });
4204
+ continue;
4205
+ }
4206
+ failures.push({
4207
+ code: "tbd-in-active-tranche",
4208
+ issue: null,
4209
+ tranche: e.trancheSlug,
4210
+ task: e.task.id,
4211
+ reason: `Task ${e.task.id} in active tranche has no Issue ref (#TBD or empty) — the model requires all active tasks to have Issue numbers`,
4212
+ grandfathered: preEnforcement.has(e.trancheSlug)
4213
+ });
4474
4214
  }
4475
4215
  }
4476
- return [];
4216
+ const activeFails = failures.filter((f) => !f.grandfathered);
4217
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4218
+ return {
4219
+ check: "T3",
4220
+ status,
4221
+ failures,
4222
+ note: status === "info" ? `${failures.length} grandfathered (pre-${COHERENCE_ENFORCED_FROM})` : undefined
4223
+ };
4477
4224
  }
4478
- function checkG6(rows, registeredCheckNames) {
4479
- const findings = [];
4480
- for (const row of rows) {
4481
- if (row.audience !== "product")
4225
+ function checkD1(entries, issueToEntry, taskToEntry) {
4226
+ const failures = [];
4227
+ for (const e of entries) {
4228
+ if (!e.facts)
4482
4229
  continue;
4483
- const candidates = claimedCheckNames(row.implementation);
4484
- if (!candidates.some((name) => registeredCheckNames.has(name))) {
4485
- findings.push({
4486
- row: row.action,
4487
- path: row.implementation,
4488
- reason: `${row.ring} row "${row.action}" is marked \`product\` but its implementation "${row.implementation}" does not resolve to a coreCheckRegistry() entry`
4489
- });
4230
+ if (e.facts.prState !== "open")
4231
+ continue;
4232
+ for (const dep of e.task.dependsOn) {
4233
+ const depEntry = resolveDepEntry(dep, e.trancheSlug, issueToEntry, taskToEntry);
4234
+ if (!depEntry)
4235
+ continue;
4236
+ const sameTask = depEntry.trancheSlug === e.trancheSlug && depEntry.task.id === e.task.id;
4237
+ const sameIssue = depEntry.task.issue !== null && e.task.issue !== null && depEntry.task.issue === e.task.issue;
4238
+ if (sameTask || sameIssue) {
4239
+ failures.push({
4240
+ code: "d1-self-dependency",
4241
+ issue: e.task.issue,
4242
+ tranche: e.trancheSlug,
4243
+ task: e.task.id,
4244
+ reason: `INTERNAL: parsed a self-dependency (depends-on ${dep}) — this is a parser bug in parseRationaleDeps, not a real dependency. Please report it upstream.`
4245
+ });
4246
+ continue;
4247
+ }
4248
+ const depFacts = depEntry.facts;
4249
+ const depClosed = depFacts?.issueState === "closed";
4250
+ if (!depClosed) {
4251
+ failures.push({
4252
+ code: "dispatched-on-unmet-deps",
4253
+ issue: e.task.issue,
4254
+ tranche: e.trancheSlug,
4255
+ task: e.task.id,
4256
+ reason: `Task has open PR but depends-on ${dep} (issue #${depEntry.task.issue ?? "?"}) is not closed`
4257
+ });
4258
+ }
4490
4259
  }
4491
4260
  }
4492
- return { check: "G6", status: findings.length > 0 ? "fail" : "pass", findings };
4261
+ return { check: "D1", status: failures.length > 0 ? "fail" : "pass", failures };
4493
4262
  }
4494
- // ../../packages/aeg-core/src/reader-resolvable-prose.ts
4495
- var PRODUCT_SLUG_SCOPE = [
4496
- "apps/cli/src",
4497
- ".github/workflows",
4498
- ".vinaya",
4499
- "apps/cli/README.md",
4500
- "packages/sources/README.md"
4501
- ];
4502
- function isUnderOrEqual(path, prefix) {
4503
- return path === prefix || path.startsWith(`${prefix}/`);
4504
- }
4505
- function isProductScopeFile(path) {
4506
- return PRODUCT_SLUG_SCOPE.some((prefix) => isUnderOrEqual(path, prefix));
4263
+ function resolveDepEntry(dep, trancheSlug, issueToEntry, taskToEntry) {
4264
+ const issueMatch = dep.match(/^#(\d+)$/);
4265
+ if (issueMatch?.[1])
4266
+ return issueToEntry.get(Number(issueMatch[1]));
4267
+ return taskToEntry.get(`${trancheSlug}/${dep}`) ?? taskToEntry.get(dep);
4507
4268
  }
4508
- var SHIPS_PREFIX = "aeg-root/";
4509
- function shipsArchivePrefix(shipsPrefix) {
4510
- return `${shipsPrefix}tranches/completed/`;
4269
+ function checkR1(issuesBySlug, grandfatheredIssues, registeredNames = [], objectivesSinceIssue) {
4270
+ const failures = [];
4271
+ for (const [slug, issues] of issuesBySlug) {
4272
+ for (const issue of issues) {
4273
+ if (!isTaskIssueLabelSet(issue.labels))
4274
+ continue;
4275
+ const errors = [
4276
+ ...checkIssueRationale(issue.body).errors,
4277
+ ...checkProjectsRegistered(issue.body, issue.labels, registeredNames).errors,
4278
+ ...checkIssueObjectives(issue.body, issue.number, objectivesSinceIssue).errors,
4279
+ ...checkPartsCiteDefinedObjectives(issue.body).errors
4280
+ ];
4281
+ if (errors.length === 0)
4282
+ continue;
4283
+ failures.push({
4284
+ code: "missing-rationale-field",
4285
+ issue: issue.number,
4286
+ tranche: slug,
4287
+ reason: `Issue #${issue.number} fails the rationale gate: ${errors.join(" | ")}`,
4288
+ grandfathered: grandfatheredIssues.has(issue.number)
4289
+ });
4290
+ }
4291
+ }
4292
+ const activeFails = failures.filter((f) => !f.grandfathered);
4293
+ const status = activeFails.length > 0 ? "fail" : failures.length > 0 ? "info" : "pass";
4294
+ return {
4295
+ check: "R1",
4296
+ status,
4297
+ failures,
4298
+ note: status === "info" ? `${failures.length} grandfathered task Issue(s) predate this check's grammar (rationale fields and/or the project registry)` : undefined
4299
+ };
4511
4300
  }
4512
- var DEFAULT_SPEC_PATHS = ["SPEC.md", "CONTEXT.md", "docs/adr"];
4513
- function normalizeSpecPath(entry) {
4514
- let out = entry.replace(/\\/g, "/");
4515
- while (out.startsWith("./"))
4516
- out = out.slice(2);
4517
- out = out.replace(/\/{2,}/g, "/");
4518
- while (out.endsWith("/"))
4519
- out = out.slice(0, -1);
4520
- return out;
4301
+ function checkL1(files, entriesBySlug) {
4302
+ const failures = [];
4303
+ for (const f of files) {
4304
+ if (f.archived)
4305
+ continue;
4306
+ const entries = entriesBySlug.get(f.slug) ?? [];
4307
+ const withFacts = entries.filter((e) => e.facts !== undefined);
4308
+ if (withFacts.length === 0)
4309
+ continue;
4310
+ const allClosed = withFacts.every((e) => e.facts?.issueState === "closed");
4311
+ if (allClosed) {
4312
+ failures.push({
4313
+ code: "archive-recommended",
4314
+ tranche: f.slug,
4315
+ reason: "Active tranche has no open task-Issues — consider archiving to completed/"
4316
+ });
4317
+ }
4318
+ }
4319
+ return {
4320
+ check: "L1",
4321
+ status: "info",
4322
+ failures,
4323
+ note: failures.length > 0 ? `${failures.length} active tranche(s) with no open task-Issues — consider archiving (advisory)` : undefined
4324
+ };
4521
4325
  }
4522
- function isSpecFile2(path, specPaths) {
4523
- if (path.startsWith("apps/") && path.includes("/specs/") && path.endsWith(".md"))
4524
- return true;
4525
- if (!path.endsWith(".md"))
4526
- return false;
4527
- return specPaths.some((entry) => isUnderOrEqual(path, normalizeSpecPath(entry)));
4326
+ function checkL3(files) {
4327
+ const active = files.filter((f) => !f.archived);
4328
+ return {
4329
+ check: "L3",
4330
+ status: "info",
4331
+ failures: [],
4332
+ note: `${active.length} active tranche(s): ${active.map((f) => f.slug).join(", ") || "(none)"}`
4333
+ };
4528
4334
  }
4529
- function isClaudeMdFile(path) {
4530
- return path === "CLAUDE.md" || path.endsWith("/CLAUDE.md");
4335
+ function extractClosesReferences(prBody) {
4336
+ const closesPattern = /(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s{0,8}:?\s{0,8}#(\d+)/gi;
4337
+ const stripped = stripCode(prBody);
4338
+ const searchIn = anchoredRegion(stripped, "CLOSES") ?? stripped;
4339
+ const referenced = new Set;
4340
+ for (const hit of searchIn.matchAll(closesPattern)) {
4341
+ referenced.add(Number(hit[1]));
4342
+ }
4343
+ return referenced;
4531
4344
  }
4532
- function classifyProseFile(path, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX, specPaths = DEFAULT_SPEC_PATHS) {
4533
- if (path.startsWith(shipsPrefix)) {
4534
- return path.startsWith(shipsArchivePrefix(shipsPrefix)) ? "internal" : "ships";
4345
+ function checkClosesNTopology(branch, prBody, trancheFiles, taskIssueRefs) {
4346
+ const referenced = extractClosesReferences(prBody);
4347
+ if (taskIssueRefs) {
4348
+ for (const n of referenced) {
4349
+ const ref = taskIssueRefs.get(n);
4350
+ if (!ref)
4351
+ continue;
4352
+ const expectedBranch = `task/${ref.trancheSlug}/${ref.taskId}`;
4353
+ if (branch !== expectedBranch) {
4354
+ return {
4355
+ ok: false,
4356
+ message: `closes-n-reverse: branch "${branch}" closes #${n} (task ${ref.taskId} of tranche "${ref.trancheSlug}") but is not named "${expectedBranch}" — rename the branch and re-push, or if this work is intentionally outside AEG's dispatch flow, remove the Closes reference.`
4357
+ };
4358
+ }
4359
+ }
4535
4360
  }
4536
- if (path.startsWith(readerFacingPrefix) && path.endsWith(readerFacingSuffix)) {
4537
- return "reader-facing";
4361
+ const ref = parseTaskBranchIdentity(branch);
4362
+ if (!ref)
4363
+ return { ok: true };
4364
+ if (ref.kind === "issue") {
4365
+ const expectedIssue = ref.issueNumber;
4366
+ if (!referenced.has(expectedIssue)) {
4367
+ return {
4368
+ ok: false,
4369
+ expectedIssue,
4370
+ message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for branch "${branch}"). Add it to the PR body Summary section.`
4371
+ };
4372
+ }
4373
+ return { ok: true, expectedIssue };
4538
4374
  }
4539
- if (isClaudeMdFile(path))
4540
- return "internal";
4541
- if (isSpecFile2(path, specPaths))
4542
- return "spec";
4543
- if (isProductScopeFile(path))
4544
- return "product";
4545
- return null;
4546
- }
4547
- var SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
4548
- function stripNonProse(path, content) {
4549
- if (path.endsWith(".md")) {
4550
- return content.replace(/```.*?```/gs, (m) => m.replace(/[^\n]/g, "")).replace(/`[^`\n]*`/g, (m) => m.replace(/[^\n]/g, ""));
4375
+ const trancheSlug = ref.tranche;
4376
+ const taskId = ref.taskId;
4377
+ const trancheFile = trancheFiles.find((f) => f.slug === trancheSlug);
4378
+ if (!trancheFile) {
4379
+ return {
4380
+ ok: false,
4381
+ message: `closes-n: branch "${branch}" references tranche "${trancheSlug}" but no topology file found at aeg-root/tranches/${trancheSlug}.md. Ensure the tranche file exists before opening the PR.`
4382
+ };
4551
4383
  }
4552
- if (path.endsWith(".tsx") || path.endsWith(".ts")) {
4553
- return content.replace(/\/\*.*?\*\//gs, (m) => m.replace(/[^\n]/g, "")).replace(/(^|[^:])\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, ""));
4384
+ const task = trancheFile.tranche.tasks.find((t) => t.id === taskId);
4385
+ if (!task) {
4386
+ return {
4387
+ ok: false,
4388
+ message: `closes-n: branch "${branch}" references task "${taskId}" not found in ${trancheSlug} topology. Verify the task ID matches the tranche file.`
4389
+ };
4554
4390
  }
4555
- return content;
4391
+ if (task.issue === null) {
4392
+ return {
4393
+ ok: false,
4394
+ message: `closes-n: task "${taskId}" in "${trancheSlug}" has no Issue number (#TBD). The Planner must cut the Issue before this PR can be validated.`
4395
+ };
4396
+ }
4397
+ const expectedIssue = task.issue;
4398
+ if (!referenced.has(expectedIssue)) {
4399
+ return {
4400
+ ok: false,
4401
+ expectedIssue,
4402
+ message: `closes-n: PR body does not contain \`Closes #${expectedIssue}\` (required for task "${taskId}" in tranche "${trancheSlug}"). Add it to the PR body Summary section.`
4403
+ };
4404
+ }
4405
+ return { ok: true, expectedIssue };
4556
4406
  }
4557
- function stripNonProseForProduct(path, content) {
4558
- return path.endsWith(".md") ? stripNonProse(path, content) : content;
4407
+ // ../../packages/aeg-core/src/archive-task.ts
4408
+ function closesRefs(text) {
4409
+ return [...new Set([...text.matchAll(/Closes #(\d+)/gi)].map((m) => Number(m[1])))];
4559
4410
  }
4560
- function lineAt(content, index) {
4561
- let line = 1;
4562
- for (let i = 0;i < index; i++) {
4563
- if (content.charCodeAt(i) === 10)
4564
- line++;
4411
+ function extractIssue(body) {
4412
+ const stripped = stripCode(body);
4413
+ const bodyNums = closesRefs(stripped);
4414
+ const anchored = anchoredRegion(stripped, "CLOSES");
4415
+ if (anchored !== null) {
4416
+ const anchorNums = closesRefs(anchored);
4417
+ if (anchorNums.length === 0)
4418
+ return { issue: null, extraIssues: bodyNums, outsideHeader: false };
4419
+ const issue = anchorNums[0];
4420
+ return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: false };
4565
4421
  }
4566
- return line;
4422
+ const headerNums = closesRefs(headerRegion(stripped));
4423
+ if (bodyNums.length === 0)
4424
+ return { issue: null, extraIssues: [], outsideHeader: false };
4425
+ const issue = headerNums.length > 0 ? headerNums[0] : bodyNums[0];
4426
+ return { issue, extraIssues: bodyNums.filter((n) => n !== issue), outsideHeader: headerNums.length === 0 };
4567
4427
  }
4568
- var FORGE_NUMBER_PATTERN = /#[0-9]{2,4}/g;
4569
- var TRANCHE_SLUG_VN_PATTERN = /[a-z][a-z-]+-v[0-9]/g;
4570
- var TASK_NUMBER_PATTERN = /(^|[^a-z0-9-])(tasks?[ \t]+#?[0-9]+)/gi;
4571
- function legacySlugPattern(legacySlugs) {
4572
- if (legacySlugs.length === 0)
4573
- return null;
4574
- const alternation = legacySlugs.map((s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
4575
- return new RegExp(`(^|[^a-zA-Z0-9\\n-])(${alternation})([^a-zA-Z0-9\\n-]|$)`, "g");
4428
+ // ../../packages/aeg-core/src/review-input-manifest.ts
4429
+ import { createHash as createHash4 } from "node:crypto";
4430
+ function briefHash(brief) {
4431
+ return createHash4("sha256").update(`${brief}
4432
+ `).digest("hex");
4576
4433
  }
4577
- function checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4578
- const findings = [];
4579
- const legacyPattern = legacySlugPattern(legacySlugs);
4580
- const grandfathered = new Set(specGrandfather);
4581
- const patterns = [
4582
- { pattern: FORGE_NUMBER_PATTERN, what: "a forge number" },
4583
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug" },
4584
- ...legacyPattern ? [{ pattern: legacyPattern, what: "an internal tranche slug", group: 2 }] : []
4585
- ];
4586
- const productPatterns = [
4587
- { pattern: TRANCHE_SLUG_VN_PATTERN, what: "an internal tranche slug in product code" }
4588
- ];
4589
- const specPatterns = [
4590
- ...patterns,
4591
- { pattern: TASK_NUMBER_PATTERN, what: "a task number", group: 2 }
4592
- ];
4593
- for (const file of files) {
4594
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix, specPaths);
4595
- if (!cls || cls === "internal")
4596
- continue;
4597
- if (cls !== "product" && cls !== "spec" && !SWEPT_CLASSES.has(cls))
4598
- continue;
4599
- if (cls === "spec" && grandfathered.has(file.path))
4600
- continue;
4601
- const blocking = cls === "product" || cls === "spec";
4602
- const scrubbed = cls === "product" ? stripNonProseForProduct(file.path, file.content) : stripNonProse(file.path, file.content);
4603
- const patternsToRun = cls === "product" ? productPatterns : cls === "spec" ? specPatterns : patterns;
4604
- for (const { pattern, what, group } of patternsToRun) {
4605
- pattern.lastIndex = 0;
4606
- let match = pattern.exec(scrubbed);
4607
- while (match !== null) {
4608
- const cited = group !== undefined ? match[group] ?? match[0] : match[0];
4609
- const citedIndex = match.index + match[0].indexOf(cited);
4610
- findings.push({
4611
- file: file.path,
4612
- line: lineAt(scrubbed, citedIndex),
4613
- message: `references ${what} ("${cited}") a reader outside this repo's tracker cannot resolve`,
4614
- blocking
4615
- });
4616
- match = pattern.exec(scrubbed);
4617
- }
4618
- }
4619
- }
4620
- return findings;
4434
+ function policyDigest(policy) {
4435
+ return createHash4("sha256").update(JSON.stringify({
4436
+ codeReviewThreshold: policy.codeReviewThreshold,
4437
+ securityThreshold: policy.securityThreshold
4438
+ })).digest("hex");
4621
4439
  }
4622
- function escapeTerm(term) {
4623
- return term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4440
+ function isBoundToHead(echoed, headSha) {
4441
+ if (!echoed.headSha)
4442
+ return false;
4443
+ return headSha.toLowerCase().startsWith(echoed.headSha.toLowerCase());
4624
4444
  }
4625
- function containsWholeWord(text, term) {
4626
- const escaped = escapeTerm(term);
4627
- const re = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)`, "i");
4628
- return re.test(text);
4445
+ function isBoundByPatchIdentity(echoed, headSha, patchIdOf) {
4446
+ if (patchIdOf === undefined || !echoed.headSha)
4447
+ return false;
4448
+ const judged = patchIdOf(echoed.headSha);
4449
+ const current = patchIdOf(headSha);
4450
+ if (judged === null || current === null)
4451
+ return false;
4452
+ return judged === current;
4629
4453
  }
4630
- function findWholeWordLine(content, term) {
4631
- const lines = content.split(`
4632
- `);
4633
- let lineNo = 0;
4634
- for (const line of lines) {
4635
- lineNo++;
4636
- if (containsWholeWord(line, term))
4637
- return lineNo;
4638
- }
4639
- return null;
4454
+ function isBoundToBase(echoed, currentBase) {
4455
+ if (currentBase === null)
4456
+ return true;
4457
+ if (!echoed.baseSha)
4458
+ return false;
4459
+ return currentBase.toLowerCase().startsWith(echoed.baseSha.toLowerCase());
4640
4460
  }
4641
- function definesOrLinksGlossary(content, term) {
4642
- const escaped = escapeTerm(term);
4643
- const definesInline = new RegExp(`(^|[^a-zA-Z])${escaped}([^a-zA-Z]|$)[^\\n]{0,3}—`, "i").test(content);
4644
- if (definesInline)
4461
+ function isBoundToObjectives(echoed, currentVersion) {
4462
+ if (currentVersion === null)
4645
4463
  return true;
4646
- return /docs\/glossary|glossary\.md/i.test(content);
4464
+ return echoed.objectivesVersion === currentVersion;
4465
+ }
4466
+ function isBoundToRulings(echoed, currentOrdinal) {
4467
+ if (echoed.rulingOrdinal === null)
4468
+ return currentOrdinal === 0;
4469
+ return echoed.rulingOrdinal === currentOrdinal;
4470
+ }
4471
+ function isBoundToBriefHash(echoed, currentHash) {
4472
+ if (currentHash === null)
4473
+ return true;
4474
+ return echoed.briefHash === currentHash;
4475
+ }
4476
+ function isBoundToPolicy(echoed, currentDigest) {
4477
+ return echoed.policyDigest === currentDigest;
4478
+ }
4479
+ function compareManifest(echoed, current, patchIdOf) {
4480
+ const exactHead = isBoundToHead(echoed, current.headSha);
4481
+ const patchHead = exactHead ? false : isBoundByPatchIdentity(echoed, current.headSha, patchIdOf);
4482
+ const head = exactHead || patchHead;
4483
+ const echoedShaLen = echoed.baseSha?.length ?? 0;
4484
+ const currentShaLen = current.baseSha?.length ?? 0;
4485
+ const bothFullShas = echoedShaLen >= 40 && currentShaLen >= 40;
4486
+ const base = patchHead || exactHead && bothFullShas ? true : isBoundToBase(echoed, current.baseSha);
4487
+ const briefHashBound = isBoundToBriefHash(echoed, current.briefHash);
4488
+ const objectivesVersion = isBoundToObjectives(echoed, current.objectivesVersion);
4489
+ const rulingOrdinal = isBoundToRulings(echoed, current.rulingOrdinal);
4490
+ const policyDigestBound = isBoundToPolicy(echoed, current.policyDigest);
4491
+ return {
4492
+ bound: head && base && briefHashBound && objectivesVersion && rulingOrdinal && policyDigestBound,
4493
+ head,
4494
+ base,
4495
+ briefHash: briefHashBound,
4496
+ objectivesVersion,
4497
+ rulingOrdinal,
4498
+ policyDigest: policyDigestBound
4499
+ };
4500
+ }
4501
+
4502
+ // ../../packages/aeg-core/src/review-gate.ts
4503
+ function renderGateDeferred(deferred) {
4504
+ if (deferred.length === 0)
4505
+ return "";
4506
+ const items = deferred.map((d) => {
4507
+ const where = d.finding.location && d.finding.location.length > 0 ? d.finding.location : "(no location)";
4508
+ return `${d.finding.severity} ${where} (${DEFERRAL_REASON_TEXT[d.reason]})`;
4509
+ }).join("; ");
4510
+ return ` ${deferred.length} finding(s) deferred, not blocking this round: ${items}.`;
4511
+ }
4512
+ function checkReviewGate(input) {
4513
+ const principalAllowlist = input.principalAllowlist ?? PRINCIPAL_ALLOWLIST;
4514
+ const waived = isWaiverLabelActorVerified({
4515
+ label: WAIVER_LABEL_REVIEW,
4516
+ labels: input.labels,
4517
+ labelActor: input.waiverLabelActor,
4518
+ principalAllowlist
4519
+ });
4520
+ if (waived) {
4521
+ return {
4522
+ verdict: "pass",
4523
+ reason: `\`${WAIVER_LABEL_REVIEW}\` label is actor-verified — review requirement waived for this PR.`,
4524
+ waived: true
4525
+ };
4526
+ }
4527
+ const verified = input.comments.filter((c) => isPrincipal(c.author, principalAllowlist));
4528
+ const ignoredCount = input.comments.filter((c) => !isPrincipal(c.author, principalAllowlist) && c.body.includes("VERDICT")).length;
4529
+ const verifiedBodies = verified.map((c) => c.body);
4530
+ const codeReview = extractCodeReviewVerdict(verifiedBodies);
4531
+ const security = extractSecurityReviewVerdict(verifiedBodies);
4532
+ const policy = input.policy ?? DEFAULT_REVIEW_POLICY;
4533
+ let codeReviewPolicyEvaluation;
4534
+ let securityPolicyEvaluation;
4535
+ try {
4536
+ codeReviewPolicyEvaluation = evaluateCodeReview(consequentialFindings(codeReview.findingSeverities), policy, input.deferralContext);
4537
+ securityPolicyEvaluation = evaluateSecurityReview(consequentialFindings(security.findingSeverities), policy, input.deferralContext);
4538
+ } catch (err) {
4539
+ return {
4540
+ verdict: "fail",
4541
+ reason: `a verdict comment carries a finding severity this repository's policy does not recognize: ${err instanceof Error ? err.message : String(err)}`,
4542
+ waived: false
4543
+ };
4544
+ }
4545
+ const codeReviewTextClean = codeReview.value === "APPROVE";
4546
+ const securityTextClean = security.value === "PASS";
4547
+ const codeReviewPolicyClean = codeReviewPolicyEvaluation.outcome === "clean";
4548
+ const securityPolicyClean = securityPolicyEvaluation.outcome === "clean";
4549
+ const codeReviewClean = codeReviewTextClean && codeReviewPolicyClean;
4550
+ const securityClean = securityTextClean && securityPolicyClean;
4551
+ const currentManifest = {
4552
+ headSha: input.headSha,
4553
+ baseSha: input.baseSha ?? null,
4554
+ briefHash: input.briefHash ?? null,
4555
+ objectivesVersion: input.objectivesVersion,
4556
+ rulingOrdinal: input.rulingOrdinal,
4557
+ policyDigest: policyDigest(policy)
4558
+ };
4559
+ const codeReviewEchoed = {
4560
+ headSha: codeReview.headSha,
4561
+ baseSha: codeReview.baseSha,
4562
+ briefHash: codeReview.briefHash,
4563
+ objectivesVersion: codeReview.objectivesVersion,
4564
+ rulingOrdinal: codeReview.rulingOrdinal,
4565
+ policyDigest: codeReview.policyDigest
4566
+ };
4567
+ const securityEchoed = {
4568
+ headSha: security.headSha,
4569
+ baseSha: security.baseSha,
4570
+ briefHash: security.briefHash,
4571
+ objectivesVersion: security.objectivesVersion,
4572
+ rulingOrdinal: security.rulingOrdinal,
4573
+ policyDigest: security.policyDigest
4574
+ };
4575
+ const codeReviewBinding = compareManifest(codeReviewEchoed, currentManifest, input.patchIdOf);
4576
+ const securityBinding = compareManifest(securityEchoed, currentManifest, input.patchIdOf);
4577
+ const codeReviewBound = codeReviewBinding.head;
4578
+ const securityBound = securityBinding.head;
4579
+ const codeReviewObjectivesBound = codeReviewBinding.objectivesVersion;
4580
+ const securityObjectivesBound = securityBinding.objectivesVersion;
4581
+ const codeReviewRulingsBound = codeReviewBinding.rulingOrdinal;
4582
+ const securityRulingsBound = securityBinding.rulingOrdinal;
4583
+ const deferredNote = renderGateDeferred([
4584
+ ...codeReviewPolicyEvaluation.deferredFindings,
4585
+ ...securityPolicyEvaluation.deferredFindings
4586
+ ]);
4587
+ if (codeReviewClean && codeReviewBinding.bound && securityClean && securityBinding.bound) {
4588
+ return {
4589
+ verdict: "pass",
4590
+ reason: `code-reviewer verdict is a clean APPROVE and security-review verdict is a clean PASS, both covering head ${input.headSha}.${deferredNote}`,
4591
+ waived: false
4592
+ };
4593
+ }
4594
+ const problems = [];
4595
+ if (!codeReviewTextClean) {
4596
+ problems.push(`code-reviewer verdict is not a clean APPROVE (found: ${codeReview.value})`);
4597
+ } else if (!codeReviewPolicyClean) {
4598
+ problems.push(`code-reviewer verdict says APPROVE but carries a finding (${codeReviewPolicyEvaluation.blockingFindings.map((f) => f.severity).join(", ")}) at or above this repository's code-review policy threshold (${policy.codeReviewThreshold}) — a reviewer's own APPROVE never overrides policy`);
4599
+ } else if (!codeReviewBound) {
4600
+ problems.push(`the newest code-review verdict covers ${codeReview.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4601
+ } else if (!codeReviewBinding.base) {
4602
+ problems.push(`the newest code-review verdict was cast against base ${codeReview.baseSha ?? "no recorded base"}, the PR's base is now ${currentManifest.baseSha ?? "unresolved"} (a base-only change under an unchanged candidate — same patch text on a new base is not automatically equivalent)`);
4603
+ } else if (!codeReviewObjectivesBound) {
4604
+ problems.push(`the newest code-review verdict was cast against objectives version ${codeReview.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4605
+ } else if (!codeReviewRulingsBound) {
4606
+ problems.push(`the newest code-review verdict was cast against ruling ordinal ${codeReview.rulingOrdinal ?? "none"}, a newer ruling (ruling ${input.rulingOrdinal}) is now posted on this PR`);
4607
+ } else if (!codeReviewBinding.briefHash) {
4608
+ 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"}`);
4609
+ } else if (!codeReviewBinding.policyDigest) {
4610
+ 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}`);
4611
+ }
4612
+ if (!securityTextClean) {
4613
+ problems.push(`security-review verdict is not a clean PASS (found: ${security.value})`);
4614
+ } else if (!securityPolicyClean) {
4615
+ problems.push(`security-review verdict says PASS but carries a finding (${securityPolicyEvaluation.blockingFindings.map((f) => f.severity).join(", ")}) at or above this repository's security policy threshold (${policy.securityThreshold}) — a reviewer's own PASS never overrides policy`);
4616
+ } else if (!securityBound) {
4617
+ problems.push(`the newest security-review verdict covers ${security.headSha ?? "no recorded commit"}, head is ${input.headSha}`);
4618
+ } else if (!securityBinding.base) {
4619
+ problems.push(`the newest security-review verdict was cast against base ${security.baseSha ?? "no recorded base"}, the PR's base is now ${currentManifest.baseSha ?? "unresolved"} (a base-only change under an unchanged candidate — same patch text on a new base is not automatically equivalent)`);
4620
+ } else if (!securityObjectivesBound) {
4621
+ problems.push(`the newest security-review verdict was cast against objectives version ${security.objectivesVersion ?? "none"}, the Issue's list is now ${input.objectivesVersion}`);
4622
+ } else if (!securityRulingsBound) {
4623
+ problems.push(`the newest security-review verdict was cast against ruling ordinal ${security.rulingOrdinal ?? "none"}, a newer ruling (ruling ${input.rulingOrdinal}) is now posted on this PR`);
4624
+ } else if (!securityBinding.briefHash) {
4625
+ 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"}`);
4626
+ } else if (!securityBinding.policyDigest) {
4627
+ 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}`);
4628
+ }
4629
+ const ignoredNote = ignoredCount > 0 ? ` ${ignoredCount} verdict-shaped comment(s) from authors outside the principal allowlist were ignored.` : "";
4630
+ return {
4631
+ verdict: "fail",
4632
+ reason: `${problems.join("; ")}. A principal can apply an actor-verified \`${WAIVER_LABEL_REVIEW}\` label to skip this requirement, or post the missing/clean verdict comment(s).${ignoredNote}${deferredNote}`,
4633
+ waived: false
4634
+ };
4635
+ }
4636
+ var CHANGESET_RELEASE_BRANCH = "changeset-release/main";
4637
+ var DEFAULT_RELEASE_ACTOR = "github-actions[bot]";
4638
+ function isChangesetsReleasePr(branch, author, expectedAuthor) {
4639
+ return branch === CHANGESET_RELEASE_BRANCH && author === expectedAuthor;
4647
4640
  }
4648
- function checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix = SHIPS_PREFIX) {
4649
- const findings = [];
4650
- for (const file of files) {
4651
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
4652
- if (!cls || !SWEPT_CLASSES.has(cls))
4641
+ // ../../packages/aeg-core/src/ruling-ordinal.ts
4642
+ var RULING_MARKER_ORDINAL = /^<!-- aeg:principal:ruling:\d+-(\d+) -->$/;
4643
+ function newestPrincipalRulingOrdinal(comments, allowlist) {
4644
+ let best = 0;
4645
+ for (const c of comments) {
4646
+ if (!isPrincipal(c.author, allowlist))
4653
4647
  continue;
4654
- const scrubbed = stripNonProse(file.path, file.content);
4655
- for (const term of glossaryTerms) {
4656
- const line = findWholeWordLine(scrubbed, term);
4657
- if (line === null)
4658
- continue;
4659
- if (definesOrLinksGlossary(scrubbed, term))
4660
- continue;
4661
- findings.push({
4662
- file: file.path,
4663
- line,
4664
- message: `uses coined term "${term}" without defining it inline or linking the glossary`,
4665
- blocking: false
4666
- });
4667
- }
4648
+ const firstLine = (c.body.split(`
4649
+ `)[0] ?? "").trim();
4650
+ const m = RULING_MARKER_ORDINAL.exec(firstLine);
4651
+ if (!m)
4652
+ continue;
4653
+ const k = Number.parseInt(m[1], 10);
4654
+ if (k > best)
4655
+ best = k;
4668
4656
  }
4669
- return findings;
4657
+ return best;
4670
4658
  }
4671
- var SOURCE_COMMENT_TRANCHE_SLUG_PATTERN = /[a-z0-9]+(?:-[a-z0-9]+)*-v[0-9]+/g;
4672
- var SOURCE_COMMENT_FORGE_NUMBER_PATTERN = /#[0-9]{2,}/g;
4673
- function extractComments(path, content) {
4674
- if (!path.endsWith(".ts") && !path.endsWith(".tsx"))
4675
- return content.replace(/[^\n]/g, "");
4676
- let state = "code";
4677
- let out = "";
4678
- const n = content.length;
4679
- let i = 0;
4680
- const blank = (ch) => ch === `
4681
- ` ? `
4682
- ` : " ";
4683
- while (i < n) {
4684
- const c = content[i];
4685
- const next = i + 1 < n ? content[i + 1] : "";
4686
- if (state === "code") {
4687
- if (c === "/" && next === "/") {
4688
- state = "line-comment";
4689
- out += c;
4690
- i++;
4691
- continue;
4692
- }
4693
- if (c === "/" && next === "*") {
4694
- state = "block-comment";
4695
- out += c;
4696
- i++;
4697
- continue;
4698
- }
4699
- if (c === "'") {
4700
- state = "single-quote";
4701
- out += blank(c);
4702
- i++;
4703
- continue;
4704
- }
4705
- if (c === '"') {
4706
- state = "double-quote";
4707
- out += blank(c);
4708
- i++;
4709
- continue;
4710
- }
4711
- if (c === "`") {
4712
- state = "template";
4713
- out += blank(c);
4714
- i++;
4715
- continue;
4716
- }
4717
- out += blank(c);
4718
- i++;
4719
- continue;
4720
- }
4721
- if (state === "line-comment") {
4722
- if (c === `
4723
- `) {
4724
- state = "code";
4725
- out += `
4726
- `;
4659
+ // ../../packages/aeg-core/src/markdown-table.ts
4660
+ function splitRow(line) {
4661
+ const trimmed = line.trim().replace(/^\|/, "").replace(/\|$/, "");
4662
+ return trimmed.split("|").map((cell) => cell.trim());
4663
+ }
4664
+ var TABLE_ROW_PATTERN = /^\s*\|.*\|\s*$/;
4665
+ var SEPARATOR_ROW_PATTERN = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
4666
+ function findTable(lines, fromLine, stopAtHeading = true) {
4667
+ let i = fromLine - 1;
4668
+ while (i < lines.length) {
4669
+ const line = lines[i] ?? "";
4670
+ if (stopAtHeading && i > fromLine - 1 && /^##\s/.test(line))
4671
+ return null;
4672
+ if (TABLE_ROW_PATTERN.test(line)) {
4673
+ const headerLine = line;
4674
+ const sepLine = lines[i + 1] ?? "";
4675
+ if (!SEPARATOR_ROW_PATTERN.test(sepLine)) {
4727
4676
  i++;
4728
4677
  continue;
4729
4678
  }
4730
- out += c;
4731
- i++;
4732
- continue;
4733
- }
4734
- if (state === "block-comment") {
4735
- if (c === "*" && next === "/") {
4736
- out += c;
4737
- out += next;
4738
- state = "code";
4739
- i += 2;
4740
- continue;
4741
- }
4742
- out += c === `
4743
- ` ? `
4744
- ` : c;
4745
- i++;
4746
- continue;
4747
- }
4748
- const closer = state === "single-quote" ? "'" : state === "double-quote" ? '"' : "`";
4749
- if (c === "\\") {
4750
- out += blank(c);
4751
- i++;
4752
- if (i < n) {
4753
- out += blank(content[i]);
4754
- i++;
4679
+ const headers = splitRow(headerLine);
4680
+ const rows = [];
4681
+ let j = i + 2;
4682
+ while (j < lines.length && TABLE_ROW_PATTERN.test(lines[j] ?? "")) {
4683
+ rows.push({ cells: splitRow(lines[j] ?? ""), line: j + 1 });
4684
+ j++;
4755
4685
  }
4756
- continue;
4757
- }
4758
- if (c === closer) {
4759
- state = "code";
4760
- out += blank(c);
4761
- i++;
4762
- continue;
4686
+ return { headers, rows };
4763
4687
  }
4764
- out += blank(c);
4765
4688
  i++;
4766
4689
  }
4767
- return out;
4690
+ return null;
4768
4691
  }
4769
- function checkSourceComments(files, allowlist = []) {
4770
- const findings = [];
4771
- const allowed = new Set(allowlist);
4772
- const patterns = [
4773
- { pattern: SOURCE_COMMENT_TRANCHE_SLUG_PATTERN, what: "a tranche-slug citation" },
4774
- { pattern: SOURCE_COMMENT_FORGE_NUMBER_PATTERN, what: "a forge-number citation" }
4775
- ];
4776
- for (const file of files) {
4777
- if (!file.path.endsWith(".ts"))
4778
- continue;
4779
- if (allowed.has(file.path))
4780
- continue;
4781
- const comments = extractComments(file.path, file.content);
4782
- for (const { pattern, what } of patterns) {
4783
- pattern.lastIndex = 0;
4784
- let match = pattern.exec(comments);
4785
- while (match !== null) {
4786
- findings.push({
4787
- file: file.path,
4788
- line: lineAt(comments, match.index),
4789
- message: `comment cites ${what} ("${match[0]}") a reader outside this repo's tracker cannot resolve`,
4790
- blocking: false
4791
- });
4792
- match = pattern.exec(comments);
4793
- }
4794
- }
4692
+ function findHeadingLine(lines, pattern) {
4693
+ for (let i = 0;i < lines.length; i++) {
4694
+ if (pattern.test(lines[i] ?? ""))
4695
+ return i + 1;
4795
4696
  }
4796
- return findings;
4797
- }
4798
- function checkReaderResolvableProse(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, legacySlugs = [], shipsPrefix = SHIPS_PREFIX, specGrandfather = [], specPaths = DEFAULT_SPEC_PATHS) {
4799
- return [
4800
- ...checkUnresolvableReferences(files, readerFacingPrefix, readerFacingSuffix, legacySlugs, shipsPrefix, specGrandfather, specPaths),
4801
- ...checkUndefinedVocabulary(files, glossaryTerms, readerFacingPrefix, readerFacingSuffix, shipsPrefix)
4802
- ];
4697
+ return null;
4803
4698
  }
4804
- function parseGlossaryTerms(glossaryContent) {
4805
- const terms = [];
4806
- const re = /^\*\*(.+?)\*\* —/gm;
4807
- let match = re.exec(glossaryContent);
4808
- while (match !== null) {
4809
- if (match[1] !== undefined)
4810
- terms.push(match[1]);
4811
- match = re.exec(glossaryContent);
4699
+ // ../../packages/aeg-core/src/diagram-model.ts
4700
+ import matter from "gray-matter";
4701
+
4702
+ // ../../packages/aeg-core/src/registry-parse.ts
4703
+ var RING_HEADINGS = [
4704
+ { ring: "ring0", pattern: /^##\s+Ring 0\b/ },
4705
+ { ring: "ring1", pattern: /^##\s+Ring 1\b/ },
4706
+ { ring: "ring2", pattern: /^##\s+Ring 2\b/ }
4707
+ ];
4708
+ function stripBackticks2(cell) {
4709
+ const trimmed = cell.trim();
4710
+ if (trimmed.length >= 2 && trimmed.startsWith("`") && trimmed.endsWith("`")) {
4711
+ return trimmed.slice(1, -1);
4812
4712
  }
4813
- return terms;
4713
+ return trimmed;
4814
4714
  }
4815
-
4816
- // ../../packages/aeg-core/src/quoted-command.ts
4817
- var QUOTED_COMMAND_SHIPS_PREFIX = "aeg-root/";
4818
- var QUOTED_COMMAND_SWEPT_CLASSES = new Set(["ships", "reader-facing"]);
4819
- var START_PATTERN = /<!--\s*AEG:QUOTES-FILE:START:(\S+?)\s*-->/g;
4820
- var END_PATTERN = /<!--\s*AEG:QUOTES-FILE:END\s*-->/;
4821
- function isValidCitedFilePath(path) {
4822
- if (path.length === 0)
4823
- return false;
4824
- if (path.startsWith("/") || path.startsWith("\\"))
4825
- return false;
4826
- if (/^[A-Za-z]:[\\/]/.test(path))
4827
- return false;
4828
- return !path.split(/[\\/]+/).includes("..");
4715
+ function stripBold(cell) {
4716
+ return cell.trim().replace(/\*\*/g, "");
4717
+ }
4718
+ function parseEnforcementRegistry(content) {
4719
+ const lines = content.split(`
4720
+ `);
4721
+ const result = [];
4722
+ for (const { ring, pattern } of RING_HEADINGS) {
4723
+ const headingLine = findHeadingLine(lines, pattern);
4724
+ if (headingLine === null)
4725
+ continue;
4726
+ const table = findTable(lines, headingLine + 1);
4727
+ if (!table)
4728
+ continue;
4729
+ const descriptionIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "description");
4730
+ const implementationIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "implementation");
4731
+ const audienceIndex = table.headers.findIndex((h) => h.trim().toLowerCase() === "audience");
4732
+ for (const row of table.rows) {
4733
+ const cells = row.cells;
4734
+ if (cells.length < 3)
4735
+ continue;
4736
+ const action = stripBold(cells[0] ?? "");
4737
+ const summary = stripBackticks2(cells[1] ?? "");
4738
+ const category = stripBackticks2(cells[2] ?? "");
4739
+ const implementation = stripBackticks2((implementationIndex === -1 ? cells[cells.length - 1] : cells[implementationIndex]) ?? "");
4740
+ const description = descriptionIndex === -1 ? undefined : stripBackticks2(cells[descriptionIndex] ?? "") || undefined;
4741
+ const specIndex = (audienceIndex === -1 ? cells.length - 1 : audienceIndex) - 1;
4742
+ const spec = specIndex >= 3 ? stripBackticks2(cells[specIndex] ?? "") || undefined : undefined;
4743
+ const audience = audienceIndex === -1 ? "repo-own" : stripBackticks2(cells[audienceIndex] ?? "") === "product" ? "product" : "repo-own";
4744
+ result.push({ ring, action, summary, category, description, spec, implementation, audience, line: row.line });
4745
+ }
4746
+ }
4747
+ return result;
4829
4748
  }
4830
- function quotedCommandLineAt(content, index) {
4749
+ // ../../packages/aeg-core/src/registry-checks.ts
4750
+ var HOOK_DIR_PREFIXES = [".claude/hooks/", ".vinaya/hooks/", ".husky/", ".git/hooks/"];
4751
+ var BARE_HOOK_NAME = /^check-[A-Za-z0-9_.-]*\.sh$/;
4752
+ function basename(path) {
4753
+ return path.slice(path.lastIndexOf("/") + 1);
4754
+ }
4755
+ function lineOf(content, index) {
4831
4756
  let line = 1;
4832
- for (let i = 0;i < index; i++) {
4757
+ for (let i = 0;i < index; i++)
4833
4758
  if (content.charCodeAt(i) === 10)
4834
4759
  line++;
4835
- }
4836
4760
  return line;
4837
4761
  }
4838
- function extractQuotedText(raw) {
4839
- const trimmed = raw.trim();
4840
- const fenced = /^(?:`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n?(?:`{3,}|~{3,})$/.exec(trimmed);
4841
- if (fenced)
4842
- return (fenced[1] ?? "").trim();
4843
- const inline = /^`([^`]+)`$/.exec(trimmed);
4844
- if (inline)
4845
- return (inline[1] ?? "").trim();
4846
- return trimmed;
4762
+ function findUnshippedHookRefs(docs, shipped) {
4763
+ const shippedNames = new Set([...shipped].map(basename));
4764
+ const findings = [];
4765
+ const flag = (doc, token, index) => {
4766
+ findings.push({
4767
+ path: doc.path,
4768
+ reason: `${doc.path}:${lineOf(doc.content, index)} names hook "${token}", which is neither tracked in git nor emitted by \`vinaya init\``
4769
+ });
4770
+ };
4771
+ for (const doc of docs) {
4772
+ for (const { cited, index } of extractCitedPaths(doc.content)) {
4773
+ if (cited.endsWith("/") || !HOOK_DIR_PREFIXES.some((p) => cited.startsWith(p)))
4774
+ continue;
4775
+ if (!shipped.has(cited))
4776
+ flag(doc, cited, index);
4777
+ }
4778
+ const spanPattern = /`([^`\n]+)`/g;
4779
+ let match = spanPattern.exec(doc.content);
4780
+ while (match !== null) {
4781
+ const token = match[1] ?? "";
4782
+ if (BARE_HOOK_NAME.test(token) && !shippedNames.has(token))
4783
+ flag(doc, token, match.index);
4784
+ match = spanPattern.exec(doc.content);
4785
+ }
4786
+ }
4787
+ return findings;
4847
4788
  }
4848
- function findQuotesInFile(path, content) {
4849
- const masked = maskCode(content);
4850
- const quotes = [];
4851
- START_PATTERN.lastIndex = 0;
4852
- let start = START_PATTERN.exec(masked);
4853
- while (start !== null) {
4854
- const citedFile = start[1];
4855
- const innerStart = start.index + start[0].length;
4856
- const end = END_PATTERN.exec(masked.slice(innerStart));
4857
- if (end === null) {
4858
- START_PATTERN.lastIndex = innerStart;
4859
- start = START_PATTERN.exec(masked);
4789
+ function checkG1(rows, existsFn, hookRefs) {
4790
+ const findings = [];
4791
+ for (const row of rows) {
4792
+ if (row.implementation === "")
4860
4793
  continue;
4794
+ if (!existsFn(row.implementation)) {
4795
+ findings.push({
4796
+ row: row.action,
4797
+ path: row.implementation,
4798
+ reason: `${row.ring} row "${row.action}" names implementation "${row.implementation}", which does not exist on disk`
4799
+ });
4861
4800
  }
4862
- const innerEnd = innerStart + end.index;
4863
- if (isValidCitedFilePath(citedFile)) {
4864
- const quotedText = extractQuotedText(content.slice(innerStart, innerEnd));
4865
- if (quotedText.length > 0) {
4866
- quotes.push({ file: path, line: quotedCommandLineAt(content, innerStart), quotedText, citedFile });
4867
- }
4868
- }
4869
- START_PATTERN.lastIndex = innerEnd + end[0].length;
4870
- start = START_PATTERN.exec(masked);
4871
4801
  }
4872
- return quotes;
4802
+ if (hookRefs)
4803
+ findings.push(...findUnshippedHookRefs(hookRefs.docs, hookRefs.shipped));
4804
+ return { check: "G1", status: findings.length > 0 ? "fail" : "pass", findings };
4873
4805
  }
4874
- function findCitedQuotes(files, readerFacingPrefix, readerFacingSuffix, shipsPrefix = QUOTED_COMMAND_SHIPS_PREFIX) {
4875
- const quotes = [];
4876
- for (const file of files) {
4877
- const cls = classifyProseFile(file.path, readerFacingPrefix, readerFacingSuffix, shipsPrefix);
4878
- if (!cls || !QUOTED_COMMAND_SWEPT_CLASSES.has(cls))
4806
+ var SCAFFOLD_PLACEHOLDER = "[undocumented — fill in why]";
4807
+ var NON_GATE_BIN_NAMES = NON_GATE_BINS;
4808
+ var TWIN_CANDIDATE_EXCEPTIONS = {
4809
+ "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)',
4810
+ "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)`,
4811
+ "apps/cli/src/checks/bin/check-closes-n.ts": 'Ring 1 "Closes linkage" (implementation: verify-coherence.ts)'
4812
+ };
4813
+ var NON_GATE_HOOK_SCRIPTS = [".claude/hooks/track-transcript.sh"];
4814
+ function checkG2(rows, candidateFiles) {
4815
+ const implementations = new Set(rows.map((r) => r.implementation).filter((p) => p !== ""));
4816
+ const claimedNames = new Set(rows.flatMap((r) => claimedCheckNames(r.implementation)));
4817
+ const findings = [];
4818
+ for (const path of candidateFiles) {
4819
+ if (implementations.has(path))
4879
4820
  continue;
4880
- quotes.push(...findQuotesInFile(file.path, file.content));
4821
+ if (path.startsWith(AEG_CORE_BIN_PATH_PREFIX) && NON_GATE_BIN_NAMES.includes(basenameNoExt(path)))
4822
+ continue;
4823
+ if (NON_GATE_HOOK_SCRIPTS.includes(path))
4824
+ continue;
4825
+ if (path in TWIN_CANDIDATE_EXCEPTIONS)
4826
+ continue;
4827
+ const candidateNames = claimedCheckNames(path);
4828
+ if (candidateNames.length > 0 && candidateNames.some((n) => claimedNames.has(n)))
4829
+ continue;
4830
+ findings.push({
4831
+ path,
4832
+ reason: `"${path}" is not named as the implementation of any row in enforcement.md's ring tables`
4833
+ });
4881
4834
  }
4882
- return quotes;
4835
+ for (const row of rows) {
4836
+ const carriesPlaceholder = [row.summary, row.description, row.spec].some((cell) => cell === SCAFFOLD_PLACEHOLDER);
4837
+ if (carriesPlaceholder) {
4838
+ findings.push({
4839
+ row: row.action,
4840
+ path: row.implementation,
4841
+ reason: `${row.ring} row "${row.action}" still carries the scaffold placeholder marker — the why is owed`
4842
+ });
4843
+ }
4844
+ }
4845
+ return { check: "G2", status: findings.length > 0 ? "fail" : "pass", findings };
4883
4846
  }
4884
- function evaluateCitedQuotes(citedQuotes, citedFileContents) {
4847
+ function checkG3(ring0Rows, crossingFiles) {
4848
+ const ring0Implementations = new Set(ring0Rows.map((r) => r.implementation));
4885
4849
  const findings = [];
4886
- for (const quote of citedQuotes) {
4887
- const content = citedFileContents.get(quote.citedFile);
4888
- if (content === undefined) {
4850
+ for (const path of crossingFiles) {
4851
+ if (!ring0Implementations.has(path)) {
4889
4852
  findings.push({
4890
- file: quote.file,
4891
- line: quote.line,
4892
- citedFile: quote.citedFile,
4893
- quotedText: quote.quotedText,
4894
- message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but that file could not be read`
4853
+ path,
4854
+ reason: `"${path}" makes a GitHub-crossing call but is not named by any Ring-0 row's implementation — a seventh, unlisted way into GitHub`
4895
4855
  });
4896
- continue;
4897
4856
  }
4898
- if (!content.includes(quote.quotedText)) {
4857
+ }
4858
+ return { check: "G3", status: findings.length > 0 ? "fail" : "pass", findings };
4859
+ }
4860
+ function checkG4(content, resolveFn) {
4861
+ const cited = new Set;
4862
+ for (const hit of content.matchAll(/#(\d{3,})\b/g)) {
4863
+ cited.add(Number(hit[1]));
4864
+ }
4865
+ const findings = [];
4866
+ for (const n of cited) {
4867
+ if (!resolveFn(n)) {
4899
4868
  findings.push({
4900
- file: quote.file,
4901
- line: quote.line,
4902
- citedFile: quote.citedFile,
4903
- quotedText: quote.quotedText,
4904
- message: `${quote.file}:${quote.line} quotes "${quote.quotedText}" as citing \`${quote.citedFile}\`, but \`${quote.citedFile}\` no longer contains that text verbatim`
4869
+ reason: `#${n} is cited in enforcement.md but does not resolve to a real Issue or PR in the forge`
4905
4870
  });
4906
4871
  }
4907
4872
  }
4908
- return findings;
4873
+ return { check: "G4", status: findings.length > 0 ? "fail" : "pass", findings };
4874
+ }
4875
+ function checkG5(roles, contracts) {
4876
+ const roleIds = new Set(roles.map((r) => r.role_id));
4877
+ const findings = [];
4878
+ for (const contract of contracts) {
4879
+ if (!roleIds.has(contract.producer)) {
4880
+ findings.push({
4881
+ path: contract.file,
4882
+ reason: `contract "${contract.file}" names producer "${contract.producer}", which is not a real role_id`
4883
+ });
4884
+ }
4885
+ if (!roleIds.has(contract.consumer)) {
4886
+ findings.push({
4887
+ path: contract.file,
4888
+ reason: `contract "${contract.file}" names consumer "${contract.consumer}", which is not a real role_id`
4889
+ });
4890
+ }
4891
+ }
4892
+ for (const role of roles) {
4893
+ if (role.performs.length === 0) {
4894
+ findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty performs array` });
4895
+ }
4896
+ if (role.refuses_when.trim() === "") {
4897
+ findings.push({ path: role.file, reason: `role "${role.role_id}" has an empty refuses_when` });
4898
+ }
4899
+ }
4900
+ return { check: "G5", status: findings.length > 0 ? "fail" : "pass", findings };
4901
+ }
4902
+ var SHIPPED_BIN_PATH_PREFIX = "apps/cli/src/checks/bin/check-";
4903
+ var AEG_CORE_BIN_PATH_PREFIX = "packages/aeg-core/bin/";
4904
+ function basenameNoExt(path) {
4905
+ const base = path.slice(path.lastIndexOf("/") + 1);
4906
+ return base.replace(/\.ts$/, "");
4907
+ }
4908
+ function claimedCheckNames(implementation) {
4909
+ if (implementation.startsWith(SHIPPED_BIN_PATH_PREFIX) && implementation.endsWith(".ts")) {
4910
+ return [implementation.slice(SHIPPED_BIN_PATH_PREFIX.length, -".ts".length)];
4911
+ }
4912
+ if (implementation.startsWith(AEG_CORE_BIN_PATH_PREFIX)) {
4913
+ const audience = GATE_AUDIENCE[basenameNoExt(implementation)];
4914
+ if (audience && isShipped(audience)) {
4915
+ return Array.isArray(audience.shippedAs) ? audience.shippedAs : [audience.shippedAs];
4916
+ }
4917
+ }
4918
+ return [];
4919
+ }
4920
+ function checkG6(rows, registeredCheckNames) {
4921
+ const findings = [];
4922
+ for (const row of rows) {
4923
+ if (row.audience !== "product")
4924
+ continue;
4925
+ const candidates = claimedCheckNames(row.implementation);
4926
+ if (!candidates.some((name) => registeredCheckNames.has(name))) {
4927
+ findings.push({
4928
+ row: row.action,
4929
+ path: row.implementation,
4930
+ reason: `${row.ring} row "${row.action}" is marked \`product\` but its implementation "${row.implementation}" does not resolve to a coreCheckRegistry() entry`
4931
+ });
4932
+ }
4933
+ }
4934
+ return { check: "G6", status: findings.length > 0 ? "fail" : "pass", findings };
4909
4935
  }
4910
4936
  // ../../packages/aeg-core/src/dead-branch-push-guard.ts
4911
4937
  function checkDeadBranchPush(input) {
@@ -5328,7 +5354,6 @@ var TaskPrPauseSchema = z.object({
5328
5354
  var TaskPrReviewRecordSchema = z.object({
5329
5355
  verdicts: z.array(TaskPrVerdictSchema),
5330
5356
  roundMarkers: z.array(z.number().int().nonnegative()),
5331
- summaryTable: z.string().nullable(),
5332
5357
  pause: TaskPrPauseSchema.nullable()
5333
5358
  });
5334
5359
  var TaskPrReadInputSchema = z.object({
@@ -5375,16 +5400,6 @@ var TaskCancelResultSchema = z.object({
5375
5400
  authenticatedFrom: z.string().min(1),
5376
5401
  fencedEffectKeys: z.array(z.string())
5377
5402
  });
5378
- var TASK_TOOL_NAMES = [
5379
- "task_start",
5380
- "task_status",
5381
- "task_escalation_read",
5382
- "task_pr_read",
5383
- "task_resume",
5384
- "task_cancel"
5385
- ];
5386
- var OPERATOR_STATUS_FOLLOW = "task_status_follow";
5387
- var OPERATOR_TOOL_GRANT = [...TASK_TOOL_NAMES, OPERATOR_STATUS_FOLLOW];
5388
5403
  // ../../packages/aeg-core/src/first-push-dispatch-gate.ts
5389
5404
  function parseTaskBranch(branch) {
5390
5405
  const m = /^task\/([^/]+)\/([^/]+)$/.exec(branch);
@@ -5615,15 +5630,69 @@ var NO_GATE_CUTOVERS = {
5615
5630
  briefRulesSincePr: null,
5616
5631
  agentBoxesRefusedSincePr: null
5617
5632
  };
5618
- // ../../packages/aeg-core/src/dev-review-loop/types.ts
5619
- var SEVERITY_COLUMNS = ["blocker", "major", "minor", "critical", "high", "medium", "low"];
5620
- // ../../packages/aeg-core/src/dev-review-loop/journal-reconstruction.ts
5621
- var SUMMARY_TABLE_HEADER = `| round | ${SEVERITY_COLUMNS.join(" | ")} | confidence | outcome |`;
5622
- // ../../packages/aeg-core/src/log/envelope.ts
5623
- import { createHash as createHash5 } from "node:crypto";
5624
-
5625
5633
  // ../../packages/aeg-core/src/log/schema.ts
5634
+ import { z as z3 } from "zod";
5635
+
5636
+ // ../../packages/aeg-core/src/log/custom.ts
5626
5637
  import { z as z2 } from "zod";
5638
+ var CUSTOM_EVENT_NAME_PATTERN = /^[a-z][a-z0-9_]*\.[a-z][a-z0-9_.]*$/;
5639
+ var CUSTOM_EVENT_NAME_MAX_LENGTH = 64;
5640
+ var CUSTOM_EVENT_RESERVED_NAMESPACE = "vinaya";
5641
+ var CUSTOM_EVENT_MAX_FIELDS = 20;
5642
+ var CUSTOM_FIELD_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;
5643
+ var CUSTOM_FIELD_NAME_MAX_LENGTH = 64;
5644
+ var CUSTOM_TEXT_MAX_LENGTH = 500;
5645
+ var CUSTOM_WORD_PATTERN = /^[a-z0-9][a-z0-9_-]*$/;
5646
+ var CUSTOM_WORD_MAX_LENGTH = 64;
5647
+ var CUSTOM_FIELD_MAX_WORDS = 50;
5648
+ var CustomFieldTypeSchema = z2.union([z2.enum(["text", "number", "boolean"]), z2.array(z2.string())]);
5649
+ var CustomEventDeclarationsSchema = z2.record(z2.string(), z2.object({
5650
+ fields: z2.record(z2.string(), CustomFieldTypeSchema)
5651
+ }).strict()).superRefine((events, ctx) => {
5652
+ for (const [name, declaration] of Object.entries(events)) {
5653
+ const refuse = (message, path = []) => {
5654
+ ctx.addIssue({
5655
+ code: z2.ZodIssueCode.custom,
5656
+ path: [name, ...path],
5657
+ message: `logs.events "${name}": ${message}`
5658
+ });
5659
+ };
5660
+ if (name.length > CUSTOM_EVENT_NAME_MAX_LENGTH) {
5661
+ refuse(`the name must be at most ${CUSTOM_EVENT_NAME_MAX_LENGTH} characters`);
5662
+ }
5663
+ if (!CUSTOM_EVENT_NAME_PATTERN.test(name)) {
5664
+ refuse("the name must be `<namespace>.<event>` — lowercase letters, digits and `_`, a dot between them");
5665
+ } else if (name.split(".")[0] === CUSTOM_EVENT_RESERVED_NAMESPACE) {
5666
+ refuse(`the \`${CUSTOM_EVENT_RESERVED_NAMESPACE}.\` namespace is reserved for Vinaya's own events`);
5667
+ }
5668
+ const fieldEntries = Object.entries(declaration.fields);
5669
+ if (fieldEntries.length > CUSTOM_EVENT_MAX_FIELDS) {
5670
+ refuse(`at most ${CUSTOM_EVENT_MAX_FIELDS} fields may be declared (found ${fieldEntries.length})`, ["fields"]);
5671
+ }
5672
+ for (const [field, type] of fieldEntries) {
5673
+ if (field.length > CUSTOM_FIELD_NAME_MAX_LENGTH || !CUSTOM_FIELD_NAME_PATTERN.test(field)) {
5674
+ refuse(`field "${field}": a field name is lowercase letters, digits and \`_\`, starting with a letter, at most ${CUSTOM_FIELD_NAME_MAX_LENGTH} characters`, ["fields", field]);
5675
+ }
5676
+ if (typeof type === "string")
5677
+ continue;
5678
+ if (type.length === 0) {
5679
+ refuse(`field "${field}": a list of words must name at least one word`, ["fields", field]);
5680
+ }
5681
+ if (type.length > CUSTOM_FIELD_MAX_WORDS) {
5682
+ refuse(`field "${field}": a list of words may name at most ${CUSTOM_FIELD_MAX_WORDS}`, ["fields", field]);
5683
+ }
5684
+ const bad = type.filter((w) => w.length > CUSTOM_WORD_MAX_LENGTH || !CUSTOM_WORD_PATTERN.test(w));
5685
+ if (bad.length > 0) {
5686
+ refuse(`field "${field}": a listed word is lowercase letters, digits, \`_\` and \`-\`, at most ${CUSTOM_WORD_MAX_LENGTH} characters`, ["fields", field]);
5687
+ }
5688
+ if (new Set(type).size !== type.length) {
5689
+ refuse(`field "${field}": a list of words names a word twice`, ["fields", field]);
5690
+ }
5691
+ }
5692
+ }
5693
+ });
5694
+
5695
+ // ../../packages/aeg-core/src/log/schema.ts
5627
5696
  var CONFIDENCE_REASON_MAX_LENGTH = 280;
5628
5697
  var ROLE_VALUES = [
5629
5698
  "planner",
@@ -5634,244 +5703,297 @@ var ROLE_VALUES = [
5634
5703
  "archivist",
5635
5704
  "architect"
5636
5705
  ];
5637
- var RoleSchema = z2.enum(ROLE_VALUES);
5706
+ var RoleSchema = z3.enum(ROLE_VALUES);
5638
5707
  var HOST_VALUES = ["hook", "ci", "cli", "loop"];
5639
- var HostSchema = z2.enum(HOST_VALUES);
5708
+ var HostSchema = z3.enum(HOST_VALUES);
5640
5709
  var RUN_ID_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/;
5641
5710
  var headerMetaCore = {
5642
- ts: z2.string(),
5643
- run_id: z2.string().regex(RUN_ID_PATTERN),
5644
- seq: z2.number().int().nonnegative(),
5645
- repo: z2.string().nullable(),
5646
- vinaya: z2.string(),
5647
- doctrine: z2.string(),
5711
+ ts: z3.string(),
5712
+ run_id: z3.string().regex(RUN_ID_PATTERN),
5713
+ seq: z3.number().int().nonnegative(),
5714
+ repo: z3.string().nullable(),
5715
+ vinaya: z3.string(),
5716
+ doctrine: z3.string(),
5648
5717
  host: HostSchema,
5649
- machine: z2.string()
5718
+ machine: z3.string()
5650
5719
  };
5651
- var HeaderMetaV1Schema = z2.object({
5652
- schema: z2.literal(1),
5720
+ var HeaderMetaV1Schema = z3.object({
5721
+ schema: z3.literal(1),
5653
5722
  ...headerMetaCore
5654
5723
  }).strict();
5655
- var LineageSchema = z2.object({
5656
- run: z2.string().nullable(),
5657
- attempt: z2.number().int().nullable(),
5658
- parent: z2.string().nullable()
5724
+ var LineageSchema = z3.object({
5725
+ run: z3.string().nullable(),
5726
+ attempt: z3.number().int().nullable(),
5727
+ parent: z3.string().nullable()
5659
5728
  }).strict();
5660
- var InputVersionsSchema = z2.object({
5661
- objectives_version: z2.string().nullable(),
5662
- brief_hash: z2.string().nullable(),
5663
- ruling_ordinal: z2.number().int().nullable(),
5664
- policy_digest: z2.string().nullable()
5729
+ var InputVersionsSchema = z3.object({
5730
+ objectives_version: z3.string().nullable(),
5731
+ brief_hash: z3.string().nullable(),
5732
+ ruling_ordinal: z3.number().int().nullable(),
5733
+ policy_digest: z3.string().nullable()
5665
5734
  }).strict();
5666
- var ProvenanceSchema = z2.enum(["parent_attributed", "env_correlated", "self_reported", "unavailable"]);
5667
- var HeaderMetaV2Schema = z2.object({
5668
- schema: z2.literal(2),
5735
+ var ProvenanceSchema = z3.enum(["parent_attributed", "env_correlated", "self_reported", "unavailable"]);
5736
+ var HeaderMetaV2Schema = z3.object({
5737
+ schema: z3.literal(2),
5669
5738
  ...headerMetaCore,
5670
- event_id: z2.string().min(1),
5671
- process_id: z2.string().min(1),
5672
- actor_id: z2.string().nullable(),
5739
+ event_id: z3.string().min(1),
5740
+ process_id: z3.string().min(1),
5741
+ actor_id: z3.string().nullable(),
5673
5742
  lineage: LineageSchema,
5674
5743
  input_versions: InputVersionsSchema,
5675
5744
  provenance: ProvenanceSchema
5676
5745
  }).strict();
5677
- var HeaderMetaSchema = z2.discriminatedUnion("schema", [HeaderMetaV1Schema, HeaderMetaV2Schema]);
5678
- var SubjectSchema = z2.object({
5679
- issue: z2.number().int().nullable(),
5680
- pr: z2.number().int().optional(),
5681
- sha: z2.string().optional(),
5682
- role: z2.union([RoleSchema, z2.literal("unattributed")]),
5683
- round: z2.number().int().optional(),
5684
- objectives_version: z2.string().optional()
5746
+ var WorkSchema = z3.object({
5747
+ ref: z3.string().nullable(),
5748
+ repo: z3.string().nullable(),
5749
+ change: z3.string().nullable(),
5750
+ revision: z3.string().nullable()
5685
5751
  }).strict();
5686
- var HeaderSchema = z2.object({
5752
+ var FlowSchema = z3.object({
5753
+ id: z3.string().nullable(),
5754
+ version: z3.string().nullable()
5755
+ }).strict();
5756
+ var HeaderMetaV3Schema = z3.object({
5757
+ schema: z3.literal(3),
5758
+ ...headerMetaCore,
5759
+ event_id: z3.string().min(1),
5760
+ process_id: z3.string().min(1),
5761
+ actor_id: z3.string().nullable(),
5762
+ lineage: LineageSchema,
5763
+ input_versions: InputVersionsSchema,
5764
+ provenance: ProvenanceSchema,
5765
+ work: WorkSchema,
5766
+ flow: FlowSchema,
5767
+ runtime: z3.string().nullable(),
5768
+ source: z3.string().nullable()
5769
+ }).strict();
5770
+ var HeaderMetaSchema = z3.discriminatedUnion("schema", [HeaderMetaV1Schema, HeaderMetaV2Schema, HeaderMetaV3Schema]);
5771
+ var SubjectSchema = z3.object({
5772
+ issue: z3.number().int().nullable(),
5773
+ pr: z3.number().int().optional(),
5774
+ sha: z3.string().optional(),
5775
+ role: z3.union([RoleSchema, z3.literal("unattributed")]),
5776
+ round: z3.number().int().optional(),
5777
+ objectives_version: z3.string().optional()
5778
+ }).strict();
5779
+ var HeaderSchema = z3.object({
5687
5780
  meta: HeaderMetaSchema,
5688
5781
  subject: SubjectSchema
5689
5782
  }).strict();
5690
5783
  var envelopeTail = {
5691
- duration_ms: z2.number().nonnegative().optional(),
5692
- payload: z2.object({}).strict()
5784
+ duration_ms: z3.number().nonnegative().optional(),
5785
+ payload: z3.object({}).strict()
5693
5786
  };
5694
- var ReviewFindingSchema = z2.object({
5695
- id: z2.string(),
5696
- severity: z2.string(),
5697
- state: z2.string().optional(),
5698
- severity_scale: z2.string().optional(),
5699
- policy_treatment: z2.enum(["blocking", "non_blocking", "unavailable"]).optional(),
5700
- confidence: z2.number().min(0).max(1).optional(),
5701
- confidence_scale: z2.string().optional(),
5702
- confidence_source: z2.string().optional()
5787
+ var ReviewFindingSchema = z3.object({
5788
+ id: z3.string(),
5789
+ severity: z3.string(),
5790
+ state: z3.string().optional(),
5791
+ severity_scale: z3.string().optional(),
5792
+ policy_treatment: z3.enum(["blocking", "non_blocking", "unavailable"]).optional(),
5793
+ confidence: z3.number().min(0).max(1).optional(),
5794
+ confidence_scale: z3.string().optional(),
5795
+ confidence_source: z3.string().optional()
5703
5796
  }).strict();
5704
- var DispatchOutcomeSchema = z2.discriminatedUnion("type", [
5705
- z2.object({ type: z2.literal("pr_opened"), pr: z2.number().int(), head: z2.string() }).strict(),
5706
- z2.object({
5707
- type: z2.literal("round_pushed"),
5708
- pr: z2.number().int(),
5709
- head: z2.string(),
5710
- comment_id: z2.number().int()
5797
+ var DispatchOutcomeSchema = z3.discriminatedUnion("type", [
5798
+ z3.object({ type: z3.literal("pr_opened"), pr: z3.number().int(), head: z3.string() }).strict(),
5799
+ z3.object({
5800
+ type: z3.literal("round_pushed"),
5801
+ pr: z3.number().int(),
5802
+ head: z3.string(),
5803
+ comment_id: z3.number().int()
5711
5804
  }).strict(),
5712
- z2.object({
5713
- type: z2.literal("verdict"),
5714
- verdict: z2.enum(["APPROVE", "REQUEST CHANGES", "PASS", "FAIL"]),
5715
- head: z2.string(),
5716
- comment_id: z2.number().int(),
5717
- objectives: z2.array(z2.object({ id: z2.string(), met: z2.boolean() }).strict()),
5718
- findings: z2.array(ReviewFindingSchema)
5805
+ z3.object({
5806
+ type: z3.literal("verdict"),
5807
+ verdict: z3.enum(["APPROVE", "REQUEST CHANGES", "PASS", "FAIL"]),
5808
+ head: z3.string(),
5809
+ comment_id: z3.number().int(),
5810
+ objectives: z3.array(z3.object({ id: z3.string(), met: z3.boolean() }).strict()),
5811
+ findings: z3.array(ReviewFindingSchema)
5719
5812
  }).strict(),
5720
- z2.object({
5721
- type: z2.literal("escalation"),
5722
- class: z2.enum(["authority", "strategy", "product"]),
5723
- comment_id: z2.number().int()
5813
+ z3.object({
5814
+ type: z3.literal("escalation"),
5815
+ class: z3.enum(["authority", "strategy", "product"]),
5816
+ comment_id: z3.number().int()
5724
5817
  }).strict(),
5725
- z2.object({ type: z2.literal("brief"), comment_id: z2.number().int(), hash: z2.string() }).strict(),
5726
- z2.object({ type: z2.literal("plan"), issues: z2.array(z2.number().int()) }).strict(),
5727
- z2.object({ type: z2.literal("archive"), provenance_comment_id: z2.number().int() }).strict(),
5728
- z2.object({ type: z2.literal("completed") }).strict()
5818
+ z3.object({ type: z3.literal("brief"), comment_id: z3.number().int(), hash: z3.string() }).strict(),
5819
+ z3.object({ type: z3.literal("plan"), issues: z3.array(z3.number().int()) }).strict(),
5820
+ z3.object({ type: z3.literal("archive"), provenance_comment_id: z3.number().int() }).strict(),
5821
+ z3.object({ type: z3.literal("completed") }).strict()
5729
5822
  ]);
5730
5823
  var dispatchShared = {
5731
5824
  meta: HeaderMetaSchema,
5732
5825
  subject: SubjectSchema,
5733
- kind: z2.literal("dispatch"),
5826
+ kind: z3.literal("dispatch"),
5734
5827
  ...envelopeTail,
5735
5828
  target_role: RoleSchema,
5736
- model: z2.string(),
5737
- round: z2.number().int().optional(),
5738
- effect_id: z2.string()
5829
+ model: z3.string(),
5830
+ round: z3.number().int().optional(),
5831
+ effect_id: z3.string()
5739
5832
  };
5740
- var dispatchUsageField = z2.object({ input: z2.number().nonnegative(), output: z2.number().nonnegative() }).strict().nullable();
5741
- var DispatchEventSchema = z2.discriminatedUnion("event", [
5742
- z2.object({ ...dispatchShared, event: z2.literal("dispatched"), prompt_hash: z2.string() }).strict(),
5743
- z2.object({
5833
+ var dispatchUsageField = z3.object({ input: z3.number().nonnegative(), output: z3.number().nonnegative() }).strict().nullable();
5834
+ var DispatchEventSchema = z3.discriminatedUnion("event", [
5835
+ z3.object({ ...dispatchShared, event: z3.literal("dispatched"), prompt_hash: z3.string() }).strict(),
5836
+ z3.object({
5744
5837
  ...dispatchShared,
5745
- event: z2.literal("outcome_received"),
5838
+ event: z3.literal("outcome_received"),
5746
5839
  outcome: DispatchOutcomeSchema,
5747
5840
  usage: dispatchUsageField
5748
5841
  }).strict(),
5749
- z2.object({
5842
+ z3.object({
5750
5843
  ...dispatchShared,
5751
- event: z2.literal("dispatch_failed"),
5752
- reason: z2.enum(["timeout", "crash", "refused", "unattributed_write"]),
5844
+ event: z3.literal("dispatch_failed"),
5845
+ reason: z3.enum(["timeout", "crash", "refused", "unattributed_write"]),
5753
5846
  usage: dispatchUsageField
5754
5847
  }).strict()
5755
5848
  ]);
5849
+ var CODE_TOKEN_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
5850
+ var CodeTokenSchema = z3.string().regex(CODE_TOKEN_PATTERN);
5851
+ var ReviewerVerdictSchema = z3.object({
5852
+ role: RoleSchema,
5853
+ outcome: z3.enum(["approve", "changes_requested", "not_reviewed"]),
5854
+ blockers: z3.number().int().nonnegative()
5855
+ }).strict();
5756
5856
  var loopShared = {
5757
5857
  meta: HeaderMetaSchema,
5758
5858
  subject: SubjectSchema,
5759
- kind: z2.literal("dev_review_loop"),
5859
+ kind: z3.literal("dev_review_loop"),
5760
5860
  ...envelopeTail,
5761
- loop_id: z2.string()
5861
+ loop_id: z3.string()
5762
5862
  };
5763
- var DevReviewLoopEventSchema = z2.discriminatedUnion("event", [
5764
- z2.object({
5863
+ var DevReviewLoopEventSchema = z3.discriminatedUnion("event", [
5864
+ z3.object({
5765
5865
  ...loopShared,
5766
- event: z2.literal("loop_started"),
5767
- task: z2.number().int(),
5768
- policy: z2.object({
5769
- max_rounds: z2.number().int().nonnegative(),
5770
- reviewers: z2.array(RoleSchema),
5771
- models: z2.record(RoleSchema, z2.string())
5866
+ event: z3.literal("loop_started"),
5867
+ task: z3.number().int(),
5868
+ policy: z3.object({
5869
+ max_rounds: z3.number().int().nonnegative(),
5870
+ reviewers: z3.array(RoleSchema),
5871
+ models: z3.record(RoleSchema, z3.string())
5772
5872
  }).strict()
5773
5873
  }).strict(),
5774
- z2.object({ ...loopShared, event: z2.literal("round_started"), round: z2.number().int(), base_head: z2.string() }).strict(),
5775
- z2.object({
5874
+ z3.object({ ...loopShared, event: z3.literal("round_started"), round: z3.number().int(), base_head: z3.string() }).strict(),
5875
+ z3.object({
5776
5876
  ...loopShared,
5777
- event: z2.literal("gate_result_read"),
5778
- round: z2.number().int(),
5779
- head: z2.string(),
5780
- green: z2.boolean(),
5781
- confidence_value: z2.number().int().min(0).max(100).optional(),
5782
- confidence_reason: z2.string().max(CONFIDENCE_REASON_MAX_LENGTH).optional(),
5783
- confidence_unavailable: z2.boolean().optional(),
5784
- extra_turn_spent: z2.boolean().optional()
5877
+ event: z3.literal("gate_result_read"),
5878
+ round: z3.number().int(),
5879
+ head: z3.string(),
5880
+ green: z3.boolean(),
5881
+ confidence_value: z3.number().int().min(0).max(100).optional(),
5882
+ confidence_reason: z3.string().max(CONFIDENCE_REASON_MAX_LENGTH).optional(),
5883
+ confidence_unavailable: z3.boolean().optional(),
5884
+ extra_turn_spent: z3.boolean().optional()
5785
5885
  }).strict(),
5786
- z2.object({
5886
+ z3.object({
5787
5887
  ...loopShared,
5788
- event: z2.literal("verdicts_read"),
5789
- round: z2.number().int(),
5790
- head: z2.string(),
5791
- all_approve: z2.boolean(),
5792
- blockers: z2.number().int().nonnegative(),
5793
- findings: z2.array(ReviewFindingSchema).optional()
5888
+ event: z3.literal("verdicts_read"),
5889
+ round: z3.number().int(),
5890
+ head: z3.string(),
5891
+ all_approve: z3.boolean(),
5892
+ blockers: z3.number().int().nonnegative(),
5893
+ findings: z3.array(ReviewFindingSchema).optional(),
5894
+ reviewers: z3.array(ReviewerVerdictSchema).optional()
5794
5895
  }).strict(),
5795
- z2.object({
5896
+ z3.object({
5796
5897
  ...loopShared,
5797
- event: z2.literal("findings_compared"),
5798
- round: z2.number().int(),
5799
- open: z2.array(z2.string()),
5800
- resolved: z2.array(z2.string()),
5801
- new: z2.array(z2.string()),
5802
- recurring: z2.array(z2.string())
5898
+ event: z3.literal("findings_compared"),
5899
+ round: z3.number().int(),
5900
+ open: z3.array(z3.string()),
5901
+ resolved: z3.array(z3.string()),
5902
+ new: z3.array(z3.string()),
5903
+ recurring: z3.array(z3.string())
5803
5904
  }).strict(),
5804
- z2.object({
5905
+ z3.object({
5805
5906
  ...loopShared,
5806
- event: z2.literal("stop_condition_met"),
5807
- round: z2.number().int(),
5808
- condition: z2.enum([
5907
+ event: z3.literal("stop_condition_met"),
5908
+ round: z3.number().int(),
5909
+ condition: z3.enum([
5809
5910
  "green",
5810
5911
  "max_rounds",
5811
5912
  "no_progress",
5812
5913
  "escalated",
5813
5914
  "principal_stop",
5814
5915
  "confidence",
5815
- "reappearance"
5916
+ "reappearance",
5917
+ "repeat_finding",
5918
+ "repeat_failure",
5919
+ "time_budget"
5816
5920
  ])
5817
5921
  }).strict(),
5818
- z2.object({
5922
+ z3.object({
5923
+ ...loopShared,
5924
+ event: z3.literal("paused"),
5925
+ round: z3.number().int(),
5926
+ reason: z3.enum(["escalation", "principal_item", "refreeze_needed"]),
5927
+ reason_code: CodeTokenSchema.optional()
5928
+ }).strict(),
5929
+ z3.object({
5930
+ ...loopShared,
5931
+ event: z3.literal("resumed"),
5932
+ round: z3.number().int(),
5933
+ by: z3.enum(["principal", "driver"])
5934
+ }).strict(),
5935
+ z3.object({
5819
5936
  ...loopShared,
5820
- event: z2.literal("paused"),
5821
- round: z2.number().int(),
5822
- reason: z2.enum(["escalation", "principal_item", "refreeze_needed"])
5937
+ event: z3.literal("cancelled"),
5938
+ round: z3.number().int(),
5939
+ by: z3.literal("principal")
5823
5940
  }).strict(),
5824
- z2.object({
5941
+ z3.object({
5825
5942
  ...loopShared,
5826
- event: z2.literal("resumed"),
5827
- round: z2.number().int(),
5828
- by: z2.enum(["principal", "driver"])
5943
+ event: z3.literal("unpushed_work_resume"),
5944
+ round: z3.number().int(),
5945
+ branch: z3.string(),
5946
+ detail: z3.string()
5829
5947
  }).strict(),
5830
- z2.object({
5948
+ z3.object({
5831
5949
  ...loopShared,
5832
- event: z2.literal("cancelled"),
5833
- round: z2.number().int(),
5834
- by: z2.literal("principal")
5950
+ event: z3.literal("round_ended"),
5951
+ round: z3.number().int(),
5952
+ base_head: z3.string(),
5953
+ head: z3.string(),
5954
+ files_changed: z3.number().int().nonnegative(),
5955
+ insertions: z3.number().int().nonnegative(),
5956
+ deletions: z3.number().int().nonnegative(),
5957
+ wall_ms: z3.number().nonnegative(),
5958
+ outcome: z3.enum(["green", "changes_requested", "escalated"])
5835
5959
  }).strict(),
5836
- z2.object({
5960
+ z3.object({
5837
5961
  ...loopShared,
5838
- event: z2.literal("unpushed_work_resume"),
5839
- round: z2.number().int(),
5840
- branch: z2.string(),
5841
- detail: z2.string()
5962
+ event: z3.literal("journal_finalized"),
5963
+ rounds: z3.number().int().nonnegative(),
5964
+ total_wall_ms: z3.number().nonnegative(),
5965
+ time_to_green_ms: z3.number().nonnegative().nullable(),
5966
+ files_changed_total: z3.number().int().nonnegative(),
5967
+ final_head: z3.string(),
5968
+ result: z3.enum(["merged_ready", "stopped"])
5842
5969
  }).strict(),
5843
- z2.object({
5970
+ z3.object({
5844
5971
  ...loopShared,
5845
- event: z2.literal("round_ended"),
5846
- round: z2.number().int(),
5847
- base_head: z2.string(),
5848
- head: z2.string(),
5849
- files_changed: z2.number().int().nonnegative(),
5850
- insertions: z2.number().int().nonnegative(),
5851
- deletions: z2.number().int().nonnegative(),
5852
- wall_ms: z2.number().nonnegative(),
5853
- outcome: z2.enum(["green", "changes_requested", "escalated"])
5972
+ event: z3.literal("infrastructure_retry"),
5973
+ round: z3.number().int(),
5974
+ failure_kind: z3.enum(["pause_comment_post", "developer_connection"]),
5975
+ attempts: z3.number().int().positive(),
5976
+ outcome: z3.enum(["recovered", "exhausted"])
5854
5977
  }).strict(),
5855
- z2.object({
5978
+ z3.object({
5856
5979
  ...loopShared,
5857
- event: z2.literal("journal_finalized"),
5858
- rounds: z2.number().int().nonnegative(),
5859
- total_wall_ms: z2.number().nonnegative(),
5860
- time_to_green_ms: z2.number().nonnegative().nullable(),
5861
- files_changed_total: z2.number().int().nonnegative(),
5862
- final_head: z2.string(),
5863
- result: z2.enum(["merged_ready", "stopped"])
5980
+ event: z3.literal("driver_heartbeat"),
5981
+ task: z3.number().int(),
5982
+ pr: z3.number().int().positive().optional(),
5983
+ round: z3.number().int(),
5984
+ phase: z3.string()
5864
5985
  }).strict(),
5865
- z2.object({
5986
+ z3.object({
5866
5987
  ...loopShared,
5867
- event: z2.literal("infrastructure_retry"),
5868
- round: z2.number().int(),
5869
- failure_kind: z2.enum(["pause_comment_post", "developer_connection"]),
5870
- attempts: z2.number().int().positive(),
5871
- outcome: z2.enum(["recovered", "exhausted"])
5988
+ event: z3.literal("driver_exited"),
5989
+ task: z3.number().int(),
5990
+ reason: z3.enum(["finished", "paused", "reexec", "error", "signal"]),
5991
+ last_decision: z3.string(),
5992
+ exit_code: z3.number().int().optional(),
5993
+ error_class: CodeTokenSchema.optional()
5872
5994
  }).strict()
5873
5995
  ]);
5874
- var ForgeOpSchema = z2.enum([
5996
+ var ForgeOpSchema = z3.enum([
5875
5997
  "pr.create",
5876
5998
  "pr.comment",
5877
5999
  "pr.body.replace",
@@ -5885,24 +6007,24 @@ var ForgeOpSchema = z2.enum([
5885
6007
  "label.add",
5886
6008
  "label.remove"
5887
6009
  ]);
5888
- var ForgeWriteTargetSchema = z2.object({
5889
- issue: z2.number().int().optional(),
5890
- pr: z2.number().int().optional()
6010
+ var ForgeWriteTargetSchema = z3.object({
6011
+ issue: z3.number().int().optional(),
6012
+ pr: z3.number().int().optional()
5891
6013
  }).strict();
5892
6014
  var forgeWriteShared = {
5893
6015
  meta: HeaderMetaSchema,
5894
6016
  subject: SubjectSchema,
5895
- kind: z2.literal("forge_write"),
6017
+ kind: z3.literal("forge_write"),
5896
6018
  ...envelopeTail,
5897
6019
  op: ForgeOpSchema,
5898
6020
  target: ForgeWriteTargetSchema
5899
6021
  };
5900
- var ForgeWriteEventSchema = z2.discriminatedUnion("event", [
5901
- z2.object({ ...forgeWriteShared, event: z2.literal("validated") }).strict(),
5902
- z2.object({ ...forgeWriteShared, event: z2.literal("refused"), reason: z2.string() }).strict(),
5903
- z2.object({ ...forgeWriteShared, event: z2.literal("written"), comment_ids: z2.array(z2.string()) }).strict()
6022
+ var ForgeWriteEventSchema = z3.discriminatedUnion("event", [
6023
+ z3.object({ ...forgeWriteShared, event: z3.literal("validated") }).strict(),
6024
+ z3.object({ ...forgeWriteShared, event: z3.literal("refused"), reason: z3.string() }).strict(),
6025
+ z3.object({ ...forgeWriteShared, event: z3.literal("written"), comment_ids: z3.array(z3.string()) }).strict()
5904
6026
  ]);
5905
- var GateOutcomeSchema = z2.enum([
6027
+ var GateOutcomeSchema = z3.enum([
5906
6028
  "pass",
5907
6029
  "fail",
5908
6030
  "wait",
@@ -5915,61 +6037,74 @@ var GateOutcomeSchema = z2.enum([
5915
6037
  var gateShared = {
5916
6038
  meta: HeaderMetaSchema,
5917
6039
  subject: SubjectSchema,
5918
- kind: z2.literal("gate"),
6040
+ kind: z3.literal("gate"),
5919
6041
  ...envelopeTail,
5920
- check: z2.string(),
5921
- check_version: z2.string().nullable(),
5922
- policy_version: z2.string().nullable(),
5923
- input_fingerprint: z2.string().nullable()
6042
+ check: z3.string(),
6043
+ check_version: z3.string().nullable(),
6044
+ policy_version: z3.string().nullable(),
6045
+ input_fingerprint: z3.string().nullable()
5924
6046
  };
5925
- var GateEventSchema = z2.discriminatedUnion("event", [
5926
- z2.object({
6047
+ var GateEventSchema = z3.discriminatedUnion("event", [
6048
+ z3.object({
5927
6049
  ...gateShared,
5928
- event: z2.literal("checked"),
6050
+ event: z3.literal("checked"),
5929
6051
  outcome: GateOutcomeSchema,
5930
- reason: z2.string().optional()
6052
+ reason: z3.string().optional()
6053
+ }).strict(),
6054
+ z3.object({
6055
+ meta: HeaderMetaSchema,
6056
+ subject: SubjectSchema,
6057
+ kind: z3.literal("gate"),
6058
+ ...envelopeTail,
6059
+ event: z3.literal("summary"),
6060
+ ran: z3.number().int().nonnegative(),
6061
+ passed: z3.number().int().nonnegative(),
6062
+ failed: z3.number().int().nonnegative(),
6063
+ skipped: z3.number().int().nonnegative(),
6064
+ failed_checks: z3.array(z3.string())
5931
6065
  }).strict()
5932
6066
  ]);
5933
- var OperationResultSchema = z2.enum(["ok", "error", "refused", "timeout", "cancelled", "unavailable"]);
6067
+ var OperationResultSchema = z3.enum(["ok", "error", "refused", "timeout", "cancelled", "unavailable"]);
5934
6068
  var operationShared = {
5935
6069
  meta: HeaderMetaSchema,
5936
6070
  subject: SubjectSchema,
5937
- kind: z2.literal("operation"),
6071
+ kind: z3.literal("operation"),
5938
6072
  ...envelopeTail,
5939
- operation: z2.string(),
5940
- target: z2.string().nullable()
6073
+ operation: z3.string(),
6074
+ target: z3.string().nullable()
5941
6075
  };
5942
- var OperationEventSchema = z2.discriminatedUnion("event", [
5943
- z2.object({
6076
+ var OperationEventSchema = z3.discriminatedUnion("event", [
6077
+ z3.object({
5944
6078
  ...operationShared,
5945
- event: z2.literal("completed"),
6079
+ event: z3.literal("completed"),
5946
6080
  result: OperationResultSchema,
5947
- error_class: z2.string().nullable()
6081
+ error_class: z3.string().nullable(),
6082
+ field_names: z3.array(z3.string().max(CUSTOM_FIELD_NAME_MAX_LENGTH)).max(CUSTOM_EVENT_MAX_FIELDS).optional()
5948
6083
  }).strict()
5949
6084
  ]);
5950
- var UsageUnitsSchema = z2.object({
5951
- input: z2.number().nonnegative().nullable(),
5952
- output: z2.number().nonnegative().nullable(),
5953
- cache: z2.number().nonnegative().nullable()
6085
+ var UsageUnitsSchema = z3.object({
6086
+ input: z3.number().nonnegative().nullable(),
6087
+ output: z3.number().nonnegative().nullable(),
6088
+ cache: z3.number().nonnegative().nullable()
5954
6089
  }).strict();
5955
6090
  var usageShared = {
5956
6091
  meta: HeaderMetaSchema,
5957
6092
  subject: SubjectSchema,
5958
- kind: z2.literal("usage"),
6093
+ kind: z3.literal("usage"),
5959
6094
  ...envelopeTail,
5960
- model: z2.string().nullable(),
5961
- source: z2.string(),
5962
- semantics: z2.enum(["cumulative", "delta"])
6095
+ model: z3.string().nullable(),
6096
+ source: z3.string(),
6097
+ semantics: z3.enum(["cumulative", "delta"])
5963
6098
  };
5964
- var UsageEventSchema = z2.discriminatedUnion("event", [
5965
- z2.object({
6099
+ var UsageEventSchema = z3.discriminatedUnion("event", [
6100
+ z3.object({
5966
6101
  ...usageShared,
5967
- event: z2.literal("observed"),
6102
+ event: z3.literal("observed"),
5968
6103
  units: UsageUnitsSchema,
5969
- unknown_reason: z2.string().nullable()
6104
+ unknown_reason: z3.string().nullable()
5970
6105
  }).strict()
5971
6106
  ]);
5972
- var RoleAttemptOutcomeSchema = z2.enum([
6107
+ var RoleAttemptOutcomeSchema = z3.enum([
5973
6108
  "completed",
5974
6109
  "incomplete",
5975
6110
  "infrastructure_failed",
@@ -5980,17 +6115,17 @@ var RoleAttemptOutcomeSchema = z2.enum([
5980
6115
  var roleAttemptShared = {
5981
6116
  meta: HeaderMetaSchema,
5982
6117
  subject: SubjectSchema,
5983
- kind: z2.literal("role_attempt"),
6118
+ kind: z3.literal("role_attempt"),
5984
6119
  ...envelopeTail,
5985
- actor: z2.string().nullable(),
5986
- attempt: z2.number().int().nullable(),
5987
- effect_id: z2.string(),
5988
- model: z2.string().nullable()
6120
+ actor: z3.string().nullable(),
6121
+ attempt: z3.number().int().nullable(),
6122
+ effect_id: z3.string(),
6123
+ model: z3.string().nullable()
5989
6124
  };
5990
- var RoleAttemptEventSchema = z2.discriminatedUnion("event", [
5991
- z2.object({
6125
+ var RoleAttemptEventSchema = z3.discriminatedUnion("event", [
6126
+ z3.object({
5992
6127
  ...roleAttemptShared,
5993
- event: z2.literal("attempted"),
6128
+ event: z3.literal("attempted"),
5994
6129
  outcome: RoleAttemptOutcomeSchema,
5995
6130
  usage: dispatchUsageField
5996
6131
  }).strict()
@@ -5998,42 +6133,59 @@ var RoleAttemptEventSchema = z2.discriminatedUnion("event", [
5998
6133
  var handoffShared = {
5999
6134
  meta: HeaderMetaSchema,
6000
6135
  subject: SubjectSchema,
6001
- kind: z2.literal("handoff"),
6136
+ kind: z3.literal("handoff"),
6002
6137
  ...envelopeTail,
6003
- class: z2.enum(["authority", "strategy", "product"]),
6004
- reason: z2.string()
6138
+ class: z3.enum(["authority", "strategy", "product"]),
6139
+ reason: z3.string()
6005
6140
  };
6006
- var HandoffEventSchema = z2.discriminatedUnion("event", [
6007
- z2.object({
6141
+ var HandoffEventSchema = z3.discriminatedUnion("event", [
6142
+ z3.object({
6008
6143
  ...handoffShared,
6009
- event: z2.literal("raised"),
6010
- requested_decision: z2.string().nullable()
6144
+ event: z3.literal("raised"),
6145
+ requested_decision: z3.string().nullable()
6011
6146
  }).strict(),
6012
- z2.object({
6147
+ z3.object({
6013
6148
  ...handoffShared,
6014
- event: z2.literal("resolved"),
6015
- resolution: z2.string().nullable(),
6016
- resolved_by: z2.string().nullable()
6149
+ event: z3.literal("resolved"),
6150
+ resolution: z3.string().nullable(),
6151
+ resolved_by: z3.string().nullable()
6017
6152
  }).strict()
6018
6153
  ]);
6019
- var EffectTargetSchema = z2.object({
6020
- kind: z2.string(),
6021
- ref: z2.string()
6154
+ var EffectTargetSchema = z3.object({
6155
+ kind: z3.string(),
6156
+ ref: z3.string()
6022
6157
  }).strict();
6023
6158
  var effectShared = {
6024
6159
  meta: HeaderMetaSchema,
6025
6160
  subject: SubjectSchema,
6026
- kind: z2.literal("effect"),
6161
+ kind: z3.literal("effect"),
6027
6162
  ...envelopeTail,
6028
- effect_id: z2.string(),
6163
+ effect_id: z3.string(),
6029
6164
  target: EffectTargetSchema
6030
6165
  };
6031
- var EffectEventSchema = z2.discriminatedUnion("event", [
6032
- z2.object({ ...effectShared, event: z2.literal("attempted") }).strict(),
6033
- z2.object({ ...effectShared, event: z2.literal("observed"), outcome: z2.enum(["success", "failure", "uncertain"]) }).strict(),
6034
- z2.object({ ...effectShared, event: z2.literal("verified"), outcome: z2.enum(["success", "failure", "uncertain"]) }).strict()
6166
+ var EffectEventSchema = z3.discriminatedUnion("event", [
6167
+ z3.object({ ...effectShared, event: z3.literal("attempted") }).strict(),
6168
+ z3.object({ ...effectShared, event: z3.literal("observed"), outcome: z3.enum(["success", "failure", "uncertain"]) }).strict(),
6169
+ z3.object({ ...effectShared, event: z3.literal("verified"), outcome: z3.enum(["success", "failure", "uncertain"]) }).strict()
6170
+ ]);
6171
+ var CustomFieldValueSchema = z3.union([z3.string().max(CUSTOM_TEXT_MAX_LENGTH), z3.number().finite(), z3.boolean()]);
6172
+ var customShared = {
6173
+ meta: HeaderMetaV3Schema,
6174
+ subject: SubjectSchema,
6175
+ kind: z3.literal("custom"),
6176
+ ...envelopeTail
6177
+ };
6178
+ var CustomEventSchema = z3.discriminatedUnion("event", [
6179
+ z3.object({
6180
+ ...customShared,
6181
+ event: z3.literal("recorded"),
6182
+ name: z3.string().max(CUSTOM_EVENT_NAME_MAX_LENGTH).regex(CUSTOM_EVENT_NAME_PATTERN),
6183
+ fields: z3.record(z3.string().max(CUSTOM_FIELD_NAME_MAX_LENGTH).regex(CUSTOM_FIELD_NAME_PATTERN), CustomFieldValueSchema).refine((f) => Object.keys(f).length <= CUSTOM_EVENT_MAX_FIELDS, {
6184
+ message: `custom: at most ${CUSTOM_EVENT_MAX_FIELDS} fields`
6185
+ })
6186
+ }).strict()
6035
6187
  ]);
6036
- var LogEventSchema = z2.union([
6188
+ var LogEventSchema = z3.union([
6037
6189
  DispatchEventSchema,
6038
6190
  DevReviewLoopEventSchema,
6039
6191
  ForgeWriteEventSchema,
@@ -6042,10 +6194,11 @@ var LogEventSchema = z2.union([
6042
6194
  UsageEventSchema,
6043
6195
  RoleAttemptEventSchema,
6044
6196
  HandoffEventSchema,
6045
- EffectEventSchema
6197
+ EffectEventSchema,
6198
+ CustomEventSchema
6046
6199
  ]);
6047
-
6048
6200
  // ../../packages/aeg-core/src/log/envelope.ts
6201
+ import { createHash as createHash5 } from "node:crypto";
6049
6202
  function isRole(value) {
6050
6203
  return value !== undefined && ROLE_VALUES.includes(value);
6051
6204
  }
@@ -6082,18 +6235,27 @@ function roundFromEnv(round) {
6082
6235
  const n = Number(round);
6083
6236
  return Number.isInteger(n) ? n : undefined;
6084
6237
  }
6238
+ function prFromEnv(pr) {
6239
+ if (pr === undefined || pr === "")
6240
+ return;
6241
+ const n = Number(pr);
6242
+ return Number.isInteger(n) && n > 0 ? n : undefined;
6243
+ }
6085
6244
  function buildHeader(input) {
6086
6245
  const role = isRole(input.env.role) ? input.env.role : "unattributed";
6087
6246
  const round = roundFromEnv(input.env.round);
6247
+ const pr = prFromEnv(input.env.pr);
6088
6248
  const subject = {
6089
6249
  issue: issueFromTask(input.env.task) ?? input.branchIssue ?? null,
6090
6250
  role,
6091
6251
  ...round !== undefined ? { round } : {},
6252
+ ...pr !== undefined ? { pr } : {},
6092
6253
  ...input.subject ?? {}
6093
6254
  };
6255
+ const issue = subject.issue;
6094
6256
  return {
6095
6257
  meta: {
6096
- schema: 2,
6258
+ schema: 3,
6097
6259
  ts: input.now.toISOString(),
6098
6260
  run_id: input.runId,
6099
6261
  seq: input.seq,
@@ -6116,7 +6278,19 @@ function buildHeader(input) {
6116
6278
  ruling_ordinal: input.inputVersions?.rulingOrdinal ?? null,
6117
6279
  policy_digest: input.inputVersions?.policyDigest ?? null
6118
6280
  },
6119
- provenance: provenanceFor(input)
6281
+ provenance: provenanceFor(input),
6282
+ work: {
6283
+ ref: lineageFieldFromEnv(input.env.workRef) ?? (issue === null ? null : String(issue)),
6284
+ repo: input.repo,
6285
+ change: null,
6286
+ revision: null
6287
+ },
6288
+ flow: {
6289
+ id: lineageFieldFromEnv(input.env.flow) ?? "vinaya",
6290
+ version: lineageFieldFromEnv(input.env.flowVersion)
6291
+ },
6292
+ runtime: lineageFieldFromEnv(input.env.runtime),
6293
+ source: lineageFieldFromEnv(input.env.source)
6120
6294
  },
6121
6295
  subject
6122
6296
  };
@@ -6159,7 +6333,7 @@ function redact(value, home) {
6159
6333
  return value;
6160
6334
  }
6161
6335
  // ../../packages/aeg-core/src/log/store.ts
6162
- var KNOWN_SCHEMA_VERSIONS = [1, 2];
6336
+ var KNOWN_SCHEMA_VERSIONS = [1, 2, 3];
6163
6337
  function metaOf(obj) {
6164
6338
  if (obj === null || typeof obj !== "object")
6165
6339
  return null;
@@ -6225,7 +6399,7 @@ function classifyStoredLine(raw, home) {
6225
6399
  return { status: "invalid", identity: null, raw, reason: "valid event with no derivable identity" };
6226
6400
  }
6227
6401
  const redacted = redact(event, home);
6228
- const provenance = version === 2 ? event.meta.provenance ?? null : null;
6402
+ const provenance = version >= 2 ? event.meta.provenance ?? null : null;
6229
6403
  return {
6230
6404
  status: "ok",
6231
6405
  identity,
@@ -6238,134 +6412,143 @@ function classifyStoredLine(raw, home) {
6238
6412
  };
6239
6413
  }
6240
6414
  // ../../packages/aeg-core/src/control-store/records.ts
6241
- import { z as z3 } from "zod";
6242
- var isoTimestamp = z3.string().min(1);
6243
- var taskId = z3.number().int().positive();
6244
- var epochNumber = z3.number().int().nonnegative();
6245
- var RunRecordSchema = z3.object({
6246
- version: z3.literal(1),
6247
- kind: z3.literal("run"),
6415
+ import { z as z4 } from "zod";
6416
+ var isoTimestamp = z4.string().min(1);
6417
+ var taskId = z4.number().int().positive();
6418
+ var epochNumber = z4.number().int().nonnegative();
6419
+ var RunRecordSchema = z4.object({
6420
+ version: z4.literal(1),
6421
+ kind: z4.literal("run"),
6248
6422
  task: taskId,
6249
- runId: z3.string().min(1),
6250
- pid: z3.number().int().positive(),
6251
- host: z3.string().min(1),
6423
+ runId: z4.string().min(1),
6424
+ pid: z4.number().int().positive(),
6425
+ host: z4.string().min(1),
6252
6426
  startedAt: isoTimestamp,
6253
- childStartedAt: z3.string().min(1).nullable().optional(),
6254
- childCommand: z3.string().min(1).nullable().optional()
6427
+ childStartedAt: z4.string().min(1).nullable().optional(),
6428
+ childCommand: z4.string().min(1).nullable().optional()
6255
6429
  }).strict();
6256
- var InputRecordSchema = z3.object({
6257
- version: z3.literal(1),
6258
- kind: z3.literal("input"),
6430
+ var InputRecordSchema = z4.object({
6431
+ version: z4.literal(1),
6432
+ kind: z4.literal("input"),
6259
6433
  task: taskId,
6260
- runId: z3.string().min(1),
6261
- source: z3.union([z3.literal("fresh"), z3.literal("resume")]),
6262
- pr: z3.number().int().positive().nullable(),
6263
- round: z3.number().int().nonnegative(),
6434
+ runId: z4.string().min(1),
6435
+ source: z4.union([z4.literal("fresh"), z4.literal("resume")]),
6436
+ pr: z4.number().int().positive().nullable(),
6437
+ round: z4.number().int().nonnegative(),
6264
6438
  recordedAt: isoTimestamp
6265
6439
  }).strict();
6266
- var OwnershipRecordSchema = z3.object({
6267
- version: z3.literal(1),
6268
- kind: z3.literal("ownership"),
6440
+ var OwnershipRecordSchema = z4.object({
6441
+ version: z4.literal(1),
6442
+ kind: z4.literal("ownership"),
6269
6443
  task: taskId,
6270
6444
  epoch: epochNumber,
6271
- ownerId: z3.string().min(1),
6272
- pid: z3.number().int().positive(),
6273
- host: z3.string().min(1),
6445
+ ownerId: z4.string().min(1),
6446
+ pid: z4.number().int().positive(),
6447
+ host: z4.string().min(1),
6274
6448
  acquiredAt: isoTimestamp
6275
6449
  }).strict();
6276
- var TransitionRecordSchema = z3.object({
6277
- version: z3.literal(1),
6278
- kind: z3.literal("transition"),
6450
+ var TransitionRecordSchema = z4.object({
6451
+ version: z4.literal(1),
6452
+ kind: z4.literal("transition"),
6279
6453
  task: taskId,
6280
6454
  epoch: epochNumber,
6281
- seq: z3.number().int().nonnegative(),
6282
- from: z3.string().min(1),
6283
- to: z3.string().min(1),
6284
- detail: z3.string().optional(),
6455
+ seq: z4.number().int().nonnegative(),
6456
+ from: z4.string().min(1),
6457
+ to: z4.string().min(1),
6458
+ detail: z4.string().optional(),
6285
6459
  at: isoTimestamp
6286
6460
  }).strict();
6287
- var ManifestRecordSchema = z3.object({
6288
- version: z3.literal(1),
6289
- kind: z3.literal("manifest"),
6461
+ var ManifestRecordSchema = z4.object({
6462
+ version: z4.literal(1),
6463
+ kind: z4.literal("manifest"),
6290
6464
  task: taskId,
6291
6465
  round: epochNumber,
6292
- repository: z3.string().min(1),
6293
- pr: z3.number().int().positive(),
6294
- branch: z3.string().min(1),
6295
- baseSha: z3.string().min(1).nullable(),
6296
- headSha: z3.string().min(1),
6297
- briefHash: z3.string().min(1).nullable(),
6298
- objectivesVersion: z3.string().min(1).nullable(),
6466
+ repository: z4.string().min(1),
6467
+ pr: z4.number().int().positive(),
6468
+ branch: z4.string().min(1),
6469
+ baseSha: z4.string().min(1).nullable(),
6470
+ headSha: z4.string().min(1),
6471
+ briefHash: z4.string().min(1).nullable(),
6472
+ objectivesVersion: z4.string().min(1).nullable(),
6299
6473
  rulingOrdinal: epochNumber,
6300
- policyDigest: z3.string().min(1),
6474
+ policyDigest: z4.string().min(1),
6301
6475
  recordedAt: isoTimestamp
6302
6476
  }).strict();
6303
- var roundHeadIdentity = z3.object({ round: z3.number().int().positive(), head: z3.string().min(1) }).strict();
6304
- var LoopBudgetsSchema = z3.object({
6305
- mechanicalRetries: z3.number().int().nonnegative(),
6306
- reviewRounds: z3.number().int().nonnegative(),
6307
- infrastructureRetries: z3.number().int().nonnegative()
6477
+ var roundHeadIdentity = z4.object({ round: z4.number().int().positive(), head: z4.string().min(1) }).strict();
6478
+ var LoopBudgetsSchema = z4.object({
6479
+ mechanicalRetries: z4.number().int().nonnegative(),
6480
+ reviewRounds: z4.number().int().nonnegative(),
6481
+ infrastructureRetries: z4.number().int().nonnegative()
6308
6482
  }).strict();
6309
- var LoopStateRecordSchema = z3.object({
6310
- version: z3.literal(1),
6311
- kind: z3.literal("loop_state"),
6483
+ var LoopStateRecordSchema = z4.object({
6484
+ version: z4.literal(1),
6485
+ kind: z4.literal("loop_state"),
6312
6486
  task: taskId,
6313
- round: z3.number().int().positive(),
6314
- phase: z3.string().min(1),
6315
- pauseReason: z3.string().min(1).nullable(),
6487
+ round: z4.number().int().positive(),
6488
+ phase: z4.string().min(1),
6489
+ pauseReason: z4.string().min(1).nullable(),
6316
6490
  budgets: LoopBudgetsSchema,
6317
6491
  heldResult: roundHeadIdentity.nullable(),
6318
6492
  deliveredFindings: roundHeadIdentity.nullable(),
6493
+ repeatMemory: z4.object({
6494
+ blockingFindings: z4.array(z4.string()),
6495
+ lastFailure: z4.object({ signature: z4.string(), message: z4.string() }).nullable()
6496
+ }).strict().optional(),
6497
+ publicationExpectedBase: z4.string().regex(/^[0-9a-f]{40}$/).nullable().optional(),
6498
+ taskStartedAt: isoTimestamp.optional(),
6499
+ phaseMs: z4.record(z4.string(), z4.number().nonnegative()).optional(),
6319
6500
  recordedAt: isoTimestamp
6320
6501
  }).strict();
6321
- var EffectRecordSchema = z3.object({
6322
- version: z3.literal(1),
6323
- kind: z3.literal("effect"),
6502
+ var EffectRecordSchema = z4.object({
6503
+ version: z4.literal(1),
6504
+ kind: z4.literal("effect"),
6324
6505
  task: taskId,
6325
- key: z3.string().min(1),
6326
- operation: z3.string().min(1),
6327
- target: z3.string().min(1),
6328
- inputVersion: z3.number().int().nonnegative(),
6329
- payloadDigest: z3.string().min(1),
6330
- status: z3.union([z3.literal("started"), z3.literal("verified"), z3.literal("uncertain")]),
6331
- url: z3.string().optional(),
6506
+ key: z4.string().min(1),
6507
+ operation: z4.string().min(1),
6508
+ target: z4.string().min(1),
6509
+ inputVersion: z4.number().int().nonnegative(),
6510
+ payloadDigest: z4.string().min(1),
6511
+ status: z4.union([z4.literal("started"), z4.literal("verified"), z4.literal("uncertain")]),
6512
+ url: z4.string().optional(),
6332
6513
  recordedAt: isoTimestamp
6333
6514
  }).strict();
6334
- var EscalationRecordSchema = z3.object({
6335
- version: z3.literal(1),
6336
- kind: z3.literal("escalation"),
6515
+ var EscalationRecordSchema = z4.object({
6516
+ version: z4.literal(1),
6517
+ kind: z4.literal("escalation"),
6337
6518
  task: taskId,
6338
- escalationId: z3.string().min(1),
6519
+ escalationId: z4.string().min(1),
6339
6520
  round: epochNumber,
6340
- head: z3.string().min(1),
6341
- branch: z3.string().min(1),
6342
- pr: z3.number().int().positive().nullable(),
6343
- runId: z3.string().min(1),
6344
- pid: z3.number().int().positive(),
6345
- host: z3.string().min(1),
6346
- agent: z3.string().min(1).optional(),
6347
- reason: z3.string().min(1),
6348
- detail: z3.string().optional(),
6349
- evidence: z3.string().optional(),
6350
- attemptedRecovery: z3.string().min(1),
6351
- requestedDecision: z3.string().min(1),
6352
- recipient: z3.string().min(1),
6353
- briefHash: z3.string().min(1).nullable(),
6354
- objectivesVersion: z3.string().min(1).nullable(),
6521
+ head: z4.string().min(1),
6522
+ branch: z4.string().min(1),
6523
+ pr: z4.number().int().positive().nullable(),
6524
+ runId: z4.string().min(1),
6525
+ pid: z4.number().int().positive(),
6526
+ host: z4.string().min(1),
6527
+ agent: z4.string().min(1).optional(),
6528
+ reason: z4.string().min(1),
6529
+ detail: z4.string().optional(),
6530
+ evidence: z4.string().optional(),
6531
+ attemptedRecovery: z4.string().min(1),
6532
+ requestedDecision: z4.string().min(1),
6533
+ recipient: z4.string().min(1),
6534
+ briefHash: z4.string().min(1).nullable(),
6535
+ objectivesVersion: z4.string().min(1).nullable(),
6355
6536
  rulingOrdinal: epochNumber,
6356
- policyDigest: z3.string().min(1),
6537
+ policyDigest: z4.string().min(1),
6357
6538
  recordedAt: isoTimestamp
6358
6539
  }).strict();
6359
- var ResolutionRecordSchema = z3.object({
6360
- version: z3.literal(1),
6361
- kind: z3.literal("resolution"),
6540
+ var ResolutionRecordSchema = z4.object({
6541
+ version: z4.literal(1),
6542
+ kind: z4.literal("resolution"),
6362
6543
  task: taskId,
6363
- escalationId: z3.string().min(1),
6364
- decision: z3.union([z3.literal("resume"), z3.literal("cancel")]),
6365
- authenticatedBy: z3.string().min(1),
6366
- authenticatedFrom: z3.string().min(1),
6544
+ escalationId: z4.string().min(1),
6545
+ decision: z4.union([z4.literal("resume"), z4.literal("cancel")]),
6546
+ authenticatedBy: z4.string().min(1),
6547
+ authenticatedFrom: z4.string().min(1),
6367
6548
  consumedAt: isoTimestamp
6368
6549
  }).strict();
6550
+ // ../../packages/aeg-core/src/control-store/local.ts
6551
+ var CONTROL_AREA_DIRNAME = "control";
6369
6552
  // src/checks/contract.ts
6370
6553
  var CHECK_SCHEMA_VERSION = 1;
6371
6554
  function emitCheckError(error) {
@@ -6382,29 +6565,29 @@ import { promisify as promisify4 } from "node:util";
6382
6565
  import { existsSync, mkdirSync, readFileSync as readFileSync2, realpathSync, writeFileSync } from "node:fs";
6383
6566
  import { homedir } from "node:os";
6384
6567
  import { dirname, isAbsolute, join, resolve } from "node:path";
6385
- import { z as z4 } from "zod";
6568
+ import { z as z5 } from "zod";
6386
6569
 
6387
6570
  // src/lib/agent-vendors.ts
6388
6571
  var AGENT_VENDORS = ["skills", "claude", "gemini"];
6389
6572
 
6390
6573
  // src/lib/config.ts
6391
- var EnvEntrySchema = z4.union([
6392
- z4.literal(true),
6393
- z4.object({ optional: z4.literal(true) }),
6394
- z4.object({ anyOf: z4.array(z4.string()).min(2) }),
6395
- z4.string()
6574
+ var EnvEntrySchema = z5.union([
6575
+ z5.literal(true),
6576
+ z5.object({ optional: z5.literal(true) }),
6577
+ z5.object({ anyOf: z5.array(z5.string()).min(2) }),
6578
+ z5.string()
6396
6579
  ]);
6397
- var CheckEntrySchema = z4.object({
6398
- run: z4.string(),
6399
- scope: z4.enum(["diff", "full"]),
6400
- include: z4.array(z4.string()).optional(),
6401
- args: z4.array(z4.string()).optional(),
6402
- timeoutMs: z4.number().optional(),
6403
- env: z4.record(z4.string(), EnvEntrySchema).optional(),
6404
- requiresOpenPr: z4.boolean().optional(),
6405
- ownWorkflow: z4.boolean().optional(),
6406
- principalOwed: z4.literal(true).optional(),
6407
- validates: z4.enum(["body", "issue"]).optional()
6580
+ var CheckEntrySchema = z5.object({
6581
+ run: z5.string(),
6582
+ scope: z5.enum(["diff", "full"]),
6583
+ include: z5.array(z5.string()).optional(),
6584
+ args: z5.array(z5.string()).optional(),
6585
+ timeoutMs: z5.number().optional(),
6586
+ env: z5.record(z5.string(), EnvEntrySchema).optional(),
6587
+ requiresOpenPr: z5.boolean().optional(),
6588
+ ownWorkflow: z5.boolean().optional(),
6589
+ principalOwed: z5.literal(true).optional(),
6590
+ validates: z5.enum(["body", "issue"]).optional()
6408
6591
  }).superRefine((entry, ctx) => {
6409
6592
  if (!entry.env)
6410
6593
  return;
@@ -6414,22 +6597,22 @@ var CheckEntrySchema = z4.object({
6414
6597
  const members = value.anyOf;
6415
6598
  if (new Set(members).size !== members.length) {
6416
6599
  ctx.addIssue({
6417
- code: z4.ZodIssueCode.custom,
6600
+ code: z5.ZodIssueCode.custom,
6418
6601
  message: `env.${key}.anyOf has duplicate members`,
6419
6602
  path: ["env", key, "anyOf"]
6420
6603
  });
6421
6604
  }
6422
6605
  if (!members.includes(key)) {
6423
6606
  ctx.addIssue({
6424
- code: z4.ZodIssueCode.custom,
6607
+ code: z5.ZodIssueCode.custom,
6425
6608
  message: `env.${key}.anyOf must include "${key}" itself as a member`,
6426
6609
  path: ["env", key, "anyOf"]
6427
6610
  });
6428
6611
  }
6429
6612
  }
6430
6613
  });
6431
- var RoleEntrySchema = z4.object({
6432
- contract: z4.string().refine((p) => p.includes("/"), {
6614
+ var RoleEntrySchema = z5.object({
6615
+ contract: z5.string().refine((p) => p.includes("/"), {
6433
6616
  message: 'must be a path (contain at least one "/"), not a bare filename'
6434
6617
  })
6435
6618
  });
@@ -6453,17 +6636,17 @@ var BRIEF_BUILTINS = [
6453
6636
  "briefSections",
6454
6637
  "milestoneShape"
6455
6638
  ];
6456
- var BriefSectionSchema = z4.union([
6457
- z4.object({ builtin: z4.enum(BRIEF_BUILTINS) }),
6458
- z4.object({ heading: z4.string().min(1), name: z4.string().optional() }),
6459
- z4.object({ field: z4.string().min(1), name: z4.string().optional() }),
6460
- z4.object({ phrase: z4.string().min(1), name: z4.string().optional() })
6639
+ var BriefSectionSchema = z5.union([
6640
+ z5.object({ builtin: z5.enum(BRIEF_BUILTINS) }),
6641
+ z5.object({ heading: z5.string().min(1), name: z5.string().optional() }),
6642
+ z5.object({ field: z5.string().min(1), name: z5.string().optional() }),
6643
+ z5.object({ phrase: z5.string().min(1), name: z5.string().optional() })
6461
6644
  ]);
6462
- var BriefSchemaSchema = z4.object({
6463
- pr: z4.object({ sections: z4.array(BriefSectionSchema) }).optional(),
6464
- issue: z4.object({ sections: z4.array(BriefSectionSchema) }).optional(),
6465
- milestone: z4.object({ sections: z4.array(BriefSectionSchema) }).optional(),
6466
- ack: z4.array(z4.enum(BRIEF_BUILTINS)).optional()
6645
+ var BriefSchemaSchema = z5.object({
6646
+ pr: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6647
+ issue: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6648
+ milestone: z5.object({ sections: z5.array(BriefSectionSchema) }).optional(),
6649
+ ack: z5.array(z5.enum(BRIEF_BUILTINS)).optional()
6467
6650
  });
6468
6651
  function isSafeRepoRelPath(p) {
6469
6652
  if (p.length === 0)
@@ -6472,7 +6655,7 @@ function isSafeRepoRelPath(p) {
6472
6655
  return false;
6473
6656
  return p.split(/[\\/]/).every((seg) => seg !== ".." && seg !== "");
6474
6657
  }
6475
- var SafeRepoRelPath = z4.string().refine(isSafeRepoRelPath, {
6658
+ var SafeRepoRelPath = z5.string().refine(isSafeRepoRelPath, {
6476
6659
  message: "must be a repo-root-relative path with no `..` segment or absolute root"
6477
6660
  });
6478
6661
  var CANONICAL_HOOK_BLOCK_PREFIXES = [".git/", ".husky/", ".vinaya/hooks/", ".claude/hooks/"];
@@ -6482,22 +6665,22 @@ function isCanonicalHookBlockPath(p) {
6482
6665
  var ManagedHookBlockPath = SafeRepoRelPath.refine(isCanonicalHookBlockPath, {
6483
6666
  message: `must start with one of ${CANONICAL_HOOK_BLOCK_PREFIXES.join(", ")} (byte-exact, case-sensitive)`
6484
6667
  });
6485
- var ManagedBlockRecordSchema = z4.object({
6668
+ var ManagedBlockRecordSchema = z5.object({
6486
6669
  path: ManagedHookBlockPath,
6487
- marker: z4.string(),
6488
- comment: z4.enum(["hash", "html"])
6670
+ marker: z5.string(),
6671
+ comment: z5.enum(["hash", "html"])
6489
6672
  });
6490
- var ManagedManifestSchema = z4.object({
6491
- version: z4.number().int().positive(),
6492
- files: z4.array(SafeRepoRelPath),
6493
- blocks: z4.array(ManagedBlockRecordSchema),
6494
- labels: z4.array(z4.string()),
6495
- agents: z4.array(z4.enum(AGENT_VENDORS)).optional()
6673
+ var ManagedManifestSchema = z5.object({
6674
+ version: z5.number().int().positive(),
6675
+ files: z5.array(SafeRepoRelPath),
6676
+ blocks: z5.array(ManagedBlockRecordSchema),
6677
+ labels: z5.array(z5.string()),
6678
+ agents: z5.array(z5.enum(AGENT_VENDORS)).optional()
6496
6679
  });
6497
- var ProjectEntrySchema = z4.object({
6498
- name: z4.string().min(1),
6499
- description: z4.string().min(1).optional(),
6500
- path: z4.string().min(1).optional()
6680
+ var ProjectEntrySchema = z5.object({
6681
+ name: z5.string().min(1),
6682
+ description: z5.string().min(1).optional(),
6683
+ path: z5.string().min(1).optional()
6501
6684
  });
6502
6685
  function parseTokensCollectDeclaration(value) {
6503
6686
  const m = value.trim().match(/^(\S+)\s+(\S+)$/);
@@ -6508,87 +6691,97 @@ function parseTokensCollectDeclaration(value) {
6508
6691
  return null;
6509
6692
  return { interpreter, script };
6510
6693
  }
6511
- var VinayaConfigSchema = z4.object({
6512
- rings: z4.object({
6513
- ring1_forgeWriteInterception: z4.boolean(),
6514
- ring2_asyncAudits: z4.boolean()
6694
+ var VinayaConfigSchema = z5.object({
6695
+ rings: z5.object({
6696
+ ring1_forgeWriteInterception: z5.boolean(),
6697
+ ring2_asyncAudits: z5.boolean()
6515
6698
  }).optional(),
6516
- checks: z4.record(z4.string(), CheckEntrySchema).optional(),
6517
- roles: z4.record(z4.string(), RoleEntrySchema).optional(),
6699
+ checks: z5.record(z5.string(), CheckEntrySchema).optional(),
6700
+ roles: z5.record(z5.string(), RoleEntrySchema).optional(),
6518
6701
  briefSchema: BriefSchemaSchema.optional(),
6519
6702
  managed: ManagedManifestSchema.optional(),
6520
- principals: z4.array(z4.string()).min(1).optional(),
6521
- releaseActor: z4.string().min(1).optional(),
6522
- ci: z4.object({ setup: z4.string().min(1) }).optional(),
6523
- tokens: z4.object({
6524
- collect: z4.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
6703
+ principals: z5.array(z5.string()).min(1).optional(),
6704
+ releaseActor: z5.string().min(1).optional(),
6705
+ ci: z5.object({ setup: z5.string().min(1) }).optional(),
6706
+ tokens: z5.object({
6707
+ collect: z5.string().min(1).refine((v) => parseTokensCollectDeclaration(v) !== null, {
6525
6708
  message: 'tokens.collect must be exactly "<interpreter> <repo-relative-script-path>" — two whitespace-separated tokens, no flags, no shell syntax, no quoting'
6526
6709
  })
6527
6710
  }).optional(),
6528
- blastRadius: z4.object({ extraDomains: z4.array(z4.string()).optional() }).optional(),
6529
- proseGates: z4.object({
6530
- doctrineRoot: z4.string().min(1).optional(),
6531
- readerFacingPrefix: z4.string().min(1).optional(),
6532
- readerFacingSuffix: z4.string().min(1).optional(),
6533
- legacySlugDir: z4.string().min(1).optional(),
6534
- sourceComments: z4.object({
6535
- globs: z4.array(z4.string().min(1)).optional(),
6536
- allowlist: z4.array(z4.string().min(1)).optional(),
6537
- severity: z4.enum(["warning", "error"]).optional()
6711
+ blastRadius: z5.object({ extraDomains: z5.array(z5.string()).optional() }).optional(),
6712
+ proseGates: z5.object({
6713
+ doctrineRoot: z5.string().min(1).optional(),
6714
+ readerFacingPrefix: z5.string().min(1).optional(),
6715
+ readerFacingSuffix: z5.string().min(1).optional(),
6716
+ legacySlugDir: z5.string().min(1).optional(),
6717
+ sourceComments: z5.object({
6718
+ globs: z5.array(z5.string().min(1)).optional(),
6719
+ allowlist: z5.array(z5.string().min(1)).optional(),
6720
+ severity: z5.enum(["warning", "error"]).optional()
6538
6721
  }).optional(),
6539
- specGrandfather: z4.array(z4.string().min(1)).optional(),
6540
- specPaths: z4.array(z4.string().min(1).refine((entry) => !entry.startsWith("/") && !/^[A-Za-z]:/.test(entry), {
6722
+ specGrandfather: z5.union([z5.array(z5.string().min(1)), z5.record(z5.string().min(1), z5.number().int().min(0))]).optional(),
6723
+ specPaths: z5.array(z5.string().min(1).refine((entry) => !entry.startsWith("/") && !/^[A-Za-z]:/.test(entry), {
6541
6724
  message: "must be a repository-relative path, not an absolute one"
6542
6725
  }).refine((entry) => !entry.split(/[\\/]/).includes(".."), {
6543
6726
  message: "must stay inside the repository — no `..` segment"
6544
6727
  })).optional()
6545
6728
  }).optional(),
6546
- projects: z4.array(ProjectEntrySchema).optional(),
6547
- dispatch: z4.object({
6548
- timeoutMs: z4.number().int().positive().optional(),
6549
- killGraceMs: z4.number().int().positive().optional(),
6550
- agent: z4.enum(["claude", "codex", "gemini"]).optional(),
6551
- requireWorkerIsolation: z4.boolean().optional()
6729
+ projects: z5.array(ProjectEntrySchema).optional(),
6730
+ dispatch: z5.object({
6731
+ timeoutMs: z5.number().int().positive().optional(),
6732
+ killGraceMs: z5.number().int().positive().optional(),
6733
+ agent: z5.enum(["claude", "codex", "gemini"]).optional()
6734
+ }).optional(),
6735
+ reviewPolicy: z5.object({
6736
+ codeReviewThreshold: z5.string().min(1).optional(),
6737
+ securityThreshold: z5.string().min(1).optional(),
6738
+ maxRounds: z5.number().optional(),
6739
+ maxTaskMinutes: z5.number().optional()
6552
6740
  }).optional(),
6553
- reviewPolicy: z4.object({
6554
- codeReviewThreshold: z4.string().min(1).optional(),
6555
- securityThreshold: z4.string().min(1).optional(),
6556
- maxRounds: z4.number().optional()
6741
+ securityScan: z5.object({
6742
+ command: z5.array(z5.string().min(1)).min(1)
6557
6743
  }).optional(),
6558
- gateCutovers: z4.object({
6559
- objectivesSinceIssue: z4.number().int().nonnegative().optional(),
6560
- briefSectionsSinceIssue: z4.number().int().nonnegative().optional(),
6561
- documentationSinceIssue: z4.number().int().nonnegative().optional(),
6562
- briefRulesSincePr: z4.number().int().nonnegative().optional(),
6563
- agentBoxesRefusedSincePr: z4.number().int().nonnegative().optional()
6744
+ gateCutovers: z5.object({
6745
+ objectivesSinceIssue: z5.number().int().nonnegative().optional(),
6746
+ briefSectionsSinceIssue: z5.number().int().nonnegative().optional(),
6747
+ documentationSinceIssue: z5.number().int().nonnegative().optional(),
6748
+ briefRulesSincePr: z5.number().int().nonnegative().optional(),
6749
+ agentBoxesRefusedSincePr: z5.number().int().nonnegative().optional()
6564
6750
  }).optional(),
6565
- prePush: z4.object({
6566
- alwaysRun: z4.array(z4.string()).optional()
6751
+ planning: z5.object({
6752
+ collisionThreshold: z5.number().int().nonnegative().optional()
6567
6753
  }).optional(),
6568
- report: z4.object({
6569
- commandTimeoutMs: z4.number().int().positive().optional()
6754
+ prePush: z5.object({
6755
+ alwaysRun: z5.array(z5.string()).optional()
6756
+ }).optional(),
6757
+ report: z5.object({
6758
+ commandTimeoutMs: z5.number().int().positive().optional()
6570
6759
  }).superRefine((report, ctx) => {
6571
6760
  const commandTimeoutMs = report.commandTimeoutMs;
6572
6761
  if (commandTimeoutMs !== undefined && commandTimeoutMs > MAX_REPORT_COMMAND_TIMEOUT_MS) {
6573
6762
  ctx.addIssue({
6574
- code: z4.ZodIssueCode.custom,
6763
+ code: z5.ZodIssueCode.custom,
6575
6764
  path: ["commandTimeoutMs"],
6576
6765
  message: "must be at most 3600000 (1 hour)"
6577
6766
  });
6578
6767
  }
6579
6768
  }).optional(),
6580
- logPublish: z4.unknown().refine((v) => v === undefined, {
6769
+ logPublish: z5.unknown().refine((v) => v === undefined, {
6581
6770
  message: "logPublish is removed — telemetry is never posted to a tracker or a code host; configure `logs` instead (a folder or a server destination)"
6582
6771
  }),
6583
- runtimeDir: z4.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
6584
- logs: z4.object({
6585
- folder: z4.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
6586
- url: z4.string().url().optional(),
6587
- headers: z4.record(z4.string()).optional()
6772
+ runtimeDir: z5.string().min(1).refine((v) => isAbsolute(v), { message: "runtimeDir: must be an absolute path" }).optional(),
6773
+ logs: z5.object({
6774
+ folder: z5.string().min(1).refine((v) => isAbsolute(v), { message: "logs.folder: must be an absolute path" }).optional(),
6775
+ url: z5.string().url().optional(),
6776
+ headers: z5.record(z5.string()).optional(),
6777
+ readHeaders: z5.record(z5.string()).optional(),
6778
+ events: CustomEventDeclarationsSchema.optional()
6588
6779
  }).refine((v) => [v.folder, v.url].filter((x) => x !== undefined).length <= 1, {
6589
6780
  message: "logs: set at most one of folder/url"
6590
6781
  }).refine((v) => v.headers === undefined || v.url !== undefined, {
6591
6782
  message: "logs: headers requires url"
6783
+ }).refine((v) => v.readHeaders === undefined || v.url !== undefined, {
6784
+ message: "logs: readHeaders requires url"
6592
6785
  }).optional()
6593
6786
  });
6594
6787
  var GLOBAL_VINAYA_HOME = join(homedir(), ".vinaya");
@@ -6693,10 +6886,15 @@ function resolveReviewPolicy(config) {
6693
6886
  if (!Number.isInteger(maxRounds) || maxRounds < 1) {
6694
6887
  throw new Error(`vinaya.config.json: reviewPolicy.maxRounds "${maxRounds}" is not a positive integer — fix the config, this never falls back to a default.`);
6695
6888
  }
6889
+ const maxTaskMinutes = raw.maxTaskMinutes ?? DEFAULT_REVIEW_POLICY.maxTaskMinutes;
6890
+ if (!Number.isInteger(maxTaskMinutes) || maxTaskMinutes < 0) {
6891
+ 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.`);
6892
+ }
6696
6893
  return {
6697
6894
  codeReviewThreshold,
6698
6895
  securityThreshold,
6699
- maxRounds
6896
+ maxRounds,
6897
+ maxTaskMinutes
6700
6898
  };
6701
6899
  }
6702
6900
  function resolveGateCutovers(config) {