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