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