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