@attalabs/vinaya 0.31.0 → 0.33.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 (212) hide show
  1. package/README.md +2 -3
  2. package/aeg-root/contracts/principal-operator.md +18 -5
  3. package/aeg-root/roles/developer/reference.md +3 -3
  4. package/aeg-root/roles/operator.md +69 -16
  5. package/aeg-root/roles/planner/reference.md +1 -1
  6. package/aeg-root/roles/tranche-archivist.md +1 -0
  7. package/aeg-root/skills/aeg-context-packets/SKILL.md +1 -1
  8. package/aeg-root/skills/aeg-context-packets/examples/operator-start.md +1 -1
  9. package/aeg-root/templates/pr-report-template.md +7 -2
  10. package/dist/checks/bin/check-body-bare-digits.js +340 -101
  11. package/dist/checks/bin/check-branch-topology.js +184 -105
  12. package/dist/checks/bin/check-brief-shape.js +333 -94
  13. package/dist/checks/bin/check-changeset-coverage.js +1028 -248
  14. package/dist/checks/bin/check-ci-shard-coverage.js +82 -0
  15. package/dist/checks/bin/check-closes-n.js +184 -105
  16. package/dist/checks/bin/check-coherence.js +345 -145
  17. package/dist/checks/bin/check-dead-branch-push.js +179 -59
  18. package/dist/checks/bin/check-dispatch-readiness.js +350 -150
  19. package/dist/checks/bin/check-doc-coverage-push.js +1011 -231
  20. package/dist/checks/bin/check-doc-coverage.js +1015 -235
  21. package/dist/checks/bin/check-doctrine-no-procedures.js +333 -94
  22. package/dist/checks/bin/check-doctrine-portability.js +1013 -233
  23. package/dist/checks/bin/check-evidence-fresh.js +1010 -222
  24. package/dist/checks/bin/check-exec-bits.js +1009 -229
  25. package/dist/checks/bin/check-first-push-dispatch.js +343 -145
  26. package/dist/checks/bin/check-issue-assignment.js +186 -107
  27. package/dist/checks/bin/check-issue-milestone-attach.js +176 -56
  28. package/dist/checks/bin/check-issue-objectives-numbering.js +176 -56
  29. package/dist/checks/bin/check-issue-parts-coverage.js +176 -56
  30. package/dist/checks/bin/check-issue-surface-globs.js +363 -143
  31. package/dist/checks/bin/check-issue-title-grammar.js +176 -56
  32. package/dist/checks/bin/check-issue-tranche-label.js +176 -56
  33. package/dist/checks/bin/check-main-branch-refusal.js +176 -56
  34. package/dist/checks/bin/check-no-disk-state.js +176 -56
  35. package/dist/checks/bin/check-pr-premise-reassert.js +333 -92
  36. package/dist/checks/bin/check-pr-report-density.js +176 -56
  37. package/dist/checks/bin/check-principal-test-plan-wait.js +176 -54
  38. package/dist/checks/bin/check-quoted-command.js +999 -217
  39. package/dist/checks/bin/check-reader-resolvable-prose.js +1011 -229
  40. package/dist/checks/bin/check-registry-gates.js +186 -56
  41. package/dist/checks/bin/check-retired-vocabulary.js +997 -215
  42. package/dist/checks/bin/check-review-gate.js +403 -203
  43. package/dist/checks/bin/check-single-plan-pr.js +176 -56
  44. package/dist/checks/bin/check-surface-scope.js +184 -105
  45. package/dist/checks/bin/check-test-plan.js +176 -54
  46. package/dist/checks/bin/check-token-collection-wired.js +182 -57
  47. package/dist/checks/bin/check-token-report.js +178 -58
  48. package/dist/checks/bin/check-workspace-escape.js +1011 -229
  49. package/dist/index.js +5971 -3489
  50. package/dist/lib/pre-push-cache-test-run.js +4431 -0
  51. package/dist/lib/pre-push-select-tests.js +799 -110
  52. package/package.json +3 -2
  53. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/actions.ts +10 -12
  54. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/anchored-region.ts +5 -5
  55. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/archive-task.ts +42 -17
  56. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/baseline-capture.ts +1 -2
  57. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/branch-topology-gate.ts +3 -3
  58. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-render.ts +554 -95
  59. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-validation.ts +264 -44
  60. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/claude-code-transcript.ts +9 -9
  61. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/coherence-checks.ts +211 -30
  62. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/consumer-enumeration.ts +2 -2
  63. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/index.ts +75 -0
  64. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/local.ts +961 -0
  65. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/migration.ts +212 -0
  66. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/outcomes.ts +135 -0
  67. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/records.ts +394 -0
  68. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dead-branch-push-audit.ts +1 -2
  69. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dead-branch-push-guard.ts +1 -1
  70. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/derive-section7.ts +2 -2
  71. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/assess-round.ts +514 -0
  72. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/fakes.ts +110 -0
  73. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/index.ts +27 -0
  74. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/journal-reconstruction.ts +123 -0
  75. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/render-summary.ts +27 -0
  76. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/types.ts +240 -0
  77. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/diagram-model.ts +1 -1
  78. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/direct-main-push.ts +1 -2
  79. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dispatch-gate.ts +65 -22
  80. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doc-claim.ts +238 -0
  81. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doc-owners.ts +14 -1
  82. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/docs-coherence.ts +1 -1
  83. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/legacy-anchors.ts +1 -1
  84. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/node-route.ts +1 -1
  85. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/surfaced-manifest.ts +1 -1
  86. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doctrine-no-procedures.ts +1 -1
  87. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doctrine-portability.ts +5 -5
  88. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/ensure-label.ts +1 -1
  89. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/first-push-dispatch-gate.ts +1 -1
  90. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/gate-audience.ts +14 -3
  91. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/index.ts +379 -11
  92. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-assignment.ts +3 -4
  93. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-validation.ts +1450 -33
  94. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/leftover-detection.ts +1 -2
  95. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/local-anchor-coverage.ts +2 -2
  96. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/envelope.ts +119 -0
  97. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/index.ts +75 -0
  98. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/redact.ts +87 -0
  99. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema.ts +801 -0
  100. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/store.ts +373 -0
  101. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/main-branch-refusal.ts +2 -2
  102. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/metering-io-guard.ts +1 -1
  103. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/milestone-validation.ts +2 -3
  104. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/no-disk-state.ts +2 -2
  105. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/objectives.ts +288 -0
  106. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/parse-token-report.ts +3 -3
  107. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/parse-tranche.ts +1 -1
  108. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/pr-report-density.ts +30 -16
  109. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/pr-tier.ts +17 -1
  110. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/premise-check.ts +1 -1
  111. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/quoted-command.ts +1 -1
  112. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/reader-resolvable-prose.ts +267 -19
  113. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/registry-checks.ts +91 -24
  114. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/registry-scaffold.ts +6 -6
  115. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/report-tokens.ts +4 -4
  116. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-gate.ts +239 -110
  117. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-input-manifest.ts +384 -0
  118. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-policy.ts +184 -0
  119. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-status.ts +65 -18
  120. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/ruling-ordinal.ts +76 -0
  121. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/single-plan-pr.ts +4 -4
  122. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/state-machine-model.ts +40 -27
  123. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/symbol-collisions.ts +2 -2
  124. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/task-branch-identity.ts +38 -0
  125. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/task-tools.ts +488 -0
  126. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/test-plan-gate.ts +7 -9
  127. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/test-plan-section.ts +5 -5
  128. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/types.ts +4 -4
  129. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/verdict-extraction.ts +314 -56
  130. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/waiver-label.ts +2 -3
  131. package/studio-standalone/_node_modules/@attalabs/aeg-core/src/workspace-escape.ts +3 -3
  132. package/studio-standalone/apps/vinaya-studio/web/.next/BUILD_ID +1 -1
  133. package/studio-standalone/apps/vinaya-studio/web/.next/build-manifest.json +3 -3
  134. package/studio-standalone/apps/vinaya-studio/web/.next/prerender-manifest.json +3 -3
  135. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.html +1 -1
  136. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.rsc +1 -1
  137. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  138. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  139. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  140. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  141. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  142. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page/server-reference-manifest.json +2 -2
  143. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page.js.nft.json +1 -1
  144. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  145. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route.js +1 -1
  146. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route.js.nft.json +1 -1
  147. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page/server-reference-manifest.json +2 -2
  148. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page.js.nft.json +1 -1
  149. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page_client-reference-manifest.js +1 -1
  150. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page/server-reference-manifest.json +2 -2
  151. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js +1 -1
  152. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js.nft.json +1 -1
  153. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page_client-reference-manifest.js +1 -1
  154. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page/server-reference-manifest.json +2 -2
  155. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js +1 -1
  156. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js.nft.json +1 -1
  157. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page_client-reference-manifest.js +1 -1
  158. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page/server-reference-manifest.json +2 -2
  159. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js +1 -1
  160. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js.nft.json +1 -1
  161. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page_client-reference-manifest.js +1 -1
  162. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page/server-reference-manifest.json +3 -3
  163. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js +2 -2
  164. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js.nft.json +1 -1
  165. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page_client-reference-manifest.js +1 -1
  166. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page/server-reference-manifest.json +2 -2
  167. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js +1 -1
  168. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js.nft.json +1 -1
  169. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page_client-reference-manifest.js +1 -1
  170. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page/server-reference-manifest.json +2 -2
  171. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js +1 -1
  172. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js.nft.json +1 -1
  173. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page_client-reference-manifest.js +1 -1
  174. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page/server-reference-manifest.json +2 -2
  175. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js +1 -1
  176. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js.nft.json +1 -1
  177. package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page_client-reference-manifest.js +1 -1
  178. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/{[externals]__1agj1ww._.js → [externals]__0cki-x_._.js} +2 -2
  179. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/[root-of-the-server]__02a-3g8._.js +6 -6
  180. 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
  181. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__074w9nf._.js +3 -0
  182. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0ls23oh._.js +1 -1
  183. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__0r7e54g._.js → [root-of-the-server]__18paley._.js} +1 -1
  184. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1gjqmhq._.js +1 -1
  185. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1wc4-ip._.js +1 -1
  186. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__1r47dr7._.js → _08onyya._.js} +3 -3
  187. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_096f46i._.js +1 -1
  188. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0af2one._.js +1 -1
  189. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0e5tkdd._.js +1 -1
  190. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0kf2g72._.js +1 -1
  191. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0y1jv16._.js +1 -1
  192. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0zf4d27._.js +1 -1
  193. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1-wo68i._.js +1 -1
  194. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_15gdg48._.js +5 -5
  195. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1achbh9._.js +1 -1
  196. 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
  197. package/studio-standalone/apps/vinaya-studio/web/.next/server/middleware-build-manifest.js +3 -3
  198. package/studio-standalone/apps/vinaya-studio/web/.next/server/pages/500.html +1 -1
  199. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.js +1 -1
  200. package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.json +4 -4
  201. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/0bjnj-5fy4e7l.js +1 -0
  202. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{1dc2_-c_gavj1.js → 1ce2dj27_cgbj.js} +4 -4
  203. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{3xg6-flovrcx-.js → 22s44f5k3ecmj.js} +1 -1
  204. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/34hhdtbp20krb.js +1 -0
  205. package/studio-standalone/apps/vinaya-studio/web/package.json +2 -2
  206. package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0hstap0._.js +0 -3
  207. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/2t_rfsztmwu6y.js +0 -1
  208. package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/3ua4rm5f-a9k6.js +0 -1
  209. /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/{aeg-core → vinaya/studio-standalone/_node_modules/@attalabs/aeg-core}/bin/verify-coherence.ts +0 -0
  210. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{e8XbZ2vlVz40KzHmlqhwP → vl7QVqELe1AQ-9kaOd9mR}/_buildManifest.js +0 -0
  211. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{e8XbZ2vlVz40KzHmlqhwP → vl7QVqELe1AQ-9kaOd9mR}/_clientMiddlewareManifest.js +0 -0
  212. /package/studio-standalone/apps/vinaya-studio/web/.next/static/{e8XbZ2vlVz40KzHmlqhwP → vl7QVqELe1AQ-9kaOd9mR}/_ssgManifest.js +0 -0
@@ -16,15 +16,27 @@
16
16
  * applicability from the labels; this module only checks the body.
17
17
  */
18
18
 
19
- import { hasLabel, LABELS, projectFieldFromBody, projectsFromBody, SECTION_HEADER } from '@attalabs/aeg-forge-state'
19
+ import {
20
+ hasLabel,
21
+ LABELS,
22
+ projectFieldFromBody,
23
+ projectsFromBody,
24
+ SECTION_HEADER,
25
+ splitSlugQualifiedEdge
26
+ } from '@attalabs/aeg-forge-state'
20
27
  import { stripCode } from './anchored-region'
28
+ import { checkTestPlan, extractFencedBlocks } from './brief-validation'
29
+ import { DOC_OWNERS_PATH, isUrlPointer, parseDocOwners, pointerToPath } from './doc-owners'
30
+ import { globsOverlap } from './derive-section7'
31
+ import { objectivesOf, objectivesVersion } from './objectives'
32
+ import { locateTestPlanSection } from './test-plan-section'
21
33
 
22
34
  export type IssueSectionResult = { status: 'pass' | 'fail'; errors: string[] }
23
35
 
24
36
  /**
25
37
  * Tolerant field detector: accepts the two live rationale styles —
26
- * `**Field** — …` bold-inline (e.g. Issue #309) and `### Field` headings
27
- * (e.g. Issue #219). Case-insensitive.
38
+ * `**Field** — …` bold-inline (e.g. Issue #NNN) and `### Field` headings
39
+ * (e.g. Issue #MMM). Case-insensitive.
28
40
  */
29
41
  function hasRationaleField(body: string, labelPattern: string): boolean {
30
42
  // `labelPattern` is grouped. Ungrouped, its own top-level `|` (present in
@@ -89,11 +101,723 @@ export function checkIssueRationale(body: string): IssueSectionResult {
89
101
  return { status: errors.length > 0 ? 'fail' : 'pass', errors }
90
102
  }
91
103
 
104
+ /**
105
+ * The Issue number from which `## Objectives` becomes mandatory (a real
106
+ * incident: a merged PR left two brief Parts
107
+ * undelivered and nothing named what the work had to do in a form a machine
108
+ * could compare). Every task
109
+ * Issue at or above this cutover number already carries the section by hand. Same shape as
110
+ * `BRIEF_RULES_SINCE_PR` (`brief-validation.ts`) — a cutover by Issue number,
111
+ * never a retroactive requirement on the pre-gate stock.
112
+ */
113
+ export const OBJECTIVES_SINCE_ISSUE = 404
114
+
115
+ /**
116
+ * **The Objectives gate.** A task Issue numbered at or above
117
+ * `OBJECTIVES_SINCE_ISSUE` must carry a well-formed `## Objectives` section
118
+ * (`objectives.ts`'s `objectivesOf`) — one numbered, observable-outcome
119
+ * sentence per line, contiguous from `O1`. Below the cutover, an Issue passes
120
+ * unconditionally — the stock of older Issues stays green.
121
+ *
122
+ * `issueNumber === null` (not yet known — an Issue being created has no
123
+ * number until the write completes) is NOT exempted: fail-closed, the same
124
+ * posture `partitionBriefErrorsByRollout` (`brief-validation.ts`) takes for
125
+ * an unparseable PR number. Every Issue this repo can newly mint is already
126
+ * far past the cutover, so this never blocks a legitimate create; what it
127
+ * refuses is guessing an unknown number is old enough to skip.
128
+ */
129
+ export function checkIssueObjectives(body: string, issueNumber: number | null): IssueSectionResult {
130
+ if (issueNumber !== null && issueNumber < OBJECTIVES_SINCE_ISSUE) return { status: 'pass', errors: [] }
131
+ const result = objectivesOf(body)
132
+ if (result.ok) return { status: 'pass', errors: [] }
133
+ return { status: 'fail', errors: result.errors.map((e) => `issue-validation objectives: ${e}`) }
134
+ }
135
+
136
+ // ---------------------------------------------------------------------------
137
+ // Judgment sections as data. Four more
138
+ // task-Issue sections, each parsed by its own pure function: `## Surface`,
139
+ // `## Parts`, `## Test plan`, `## Stop conditions`. `brief-render.ts` reads
140
+ // their parsed values to fill a brief's §4/§6/§9/§10 mechanically, so `vinaya
141
+ // brief render` needs no hand edit to become dispatchable. Gated by
142
+ // `BRIEF_SECTIONS_SINCE_ISSUE`, the same cutover-by-Issue-number shape as
143
+ // `OBJECTIVES_SINCE_ISSUE` above — an Issue below the cutover legitimately
144
+ // carries none of the four, and `checkIssueBriefSections` passes it
145
+ // unconditionally; `issueNumber === null` is NOT exempted (fail-closed, same
146
+ // posture `checkIssueObjectives` takes for a not-yet-created Issue).
147
+ // ---------------------------------------------------------------------------
148
+
149
+ /** One section's raw text, from its `## <name>` heading to the next `##` heading or the end — `null` when the heading is absent. Mirrors `objectives.ts`'s private `objectivesSectionText`, parametrized on the heading name. */
150
+ function topLevelSectionText(body: string, headingName: string): string | null {
151
+ const headingRe = new RegExp(`^##[ \\t]*${headingName}[ \\t]*$`, 'im')
152
+ const heading = headingRe.exec(body)
153
+ if (!heading) return null
154
+ const afterHeading = body.slice(heading.index + heading[0].length)
155
+ const next = /^##[ \t]/m.exec(afterHeading)
156
+ return next ? afterHeading.slice(0, next.index) : afterHeading
157
+ }
158
+
159
+ /**
160
+ * True iff `text` contains a backticked span with a `/` inside it — the same
161
+ * bare-path signal `objectives.ts`'s private `hasBacktickedPath` detects for
162
+ * an Objectives line, duplicated here (that helper is not exported, and
163
+ * `objectives.ts` is out of this task's surface) for `## Parts` lines, which
164
+ * carry the identical "never a path" rule. Linear-scan, not a two-wildcard
165
+ * regex, for the same ReDoS reason that function's own doc comment records.
166
+ */
167
+ function partHasBacktickedPath(text: string): boolean {
168
+ let i = 0
169
+ while (i < text.length) {
170
+ const start = text.indexOf('`', i)
171
+ if (start === -1) return false
172
+ const end = text.indexOf('`', start + 1)
173
+ if (end === -1) return false
174
+ if (text.slice(start + 1, end).includes('/')) return true
175
+ i = end + 1
176
+ }
177
+ return false
178
+ }
179
+
180
+ /** How many non-path words a Parts line's outcome needs outside its backticked spans to count as a real sentence — same threshold and rationale as `objectives.ts`'s `MIN_WORDS_OUTSIDE_BACKTICKS`. */
181
+ const PART_MIN_WORDS_OUTSIDE_BACKTICKS = 3
182
+
183
+ function stripPartBackticks(text: string): string {
184
+ return text.replace(/`[^`\n]*`/g, ' ')
185
+ }
186
+
187
+ function partWordCount(text: string): number {
188
+ return text.split(/\s+/).filter((w) => /[a-z]/i.test(w)).length
189
+ }
190
+
191
+ /**
192
+ * A `## Surface` `in:`/`out:` entry — directory-level only, per the grammar's
193
+ * own rule. A trailing `/**`/`/*` glob suffix is stripped before the
194
+ * extension check, so `packages/aeg-core/**` reads as a directory.
195
+ *
196
+ * A dot-prefixed directory (`.claude`, `.github`) must read as a directory,
197
+ * not a file: its last path segment's only `.` sits at index 0, which is a
198
+ * name, not an extension. A real file's dot sits after at least one other
199
+ * character (`foo.ts`, `.env.local`'s trailing `.local`). Only the latter
200
+ * counts as "looks like a file path".
201
+ */
202
+ function looksLikeFilePath(entry: string): boolean {
203
+ const stripped = entry.replace(/\/\*\*?$/, '')
204
+ const lastSegment = stripped.split('/').pop() ?? stripped
205
+ const extMatch = /\.[A-Za-z0-9]{1,6}$/.exec(lastSegment)
206
+ return extMatch !== null && extMatch.index > 0
207
+ }
208
+
209
+ function splitGlobList(raw: string): string[] {
210
+ return raw
211
+ .split(',')
212
+ .map((s) => s.trim())
213
+ .filter((s) => s.length > 0)
214
+ }
215
+
216
+ export type IssueSurface = { in: string[]; out: string[] }
217
+ export type IssuePart = { n: number; objectiveIds: number[]; text: string }
218
+ export type IssueTestPlan = { kind: 'unit-tests-only' } | { kind: 'commands'; lines: string[]; principal: string[] }
219
+
220
+ type ParsedIssueSection<T> = { ok: true; value: T } | { ok: false; errors: string[] }
221
+
222
+ /**
223
+ * `## Surface` — a directory-level `in:` glob list (what this task touches)
224
+ * and `out:` glob list (what it explicitly does not), each comma-separated.
225
+ * Refuses a file path in either list — Surface entries are directory-level,
226
+ * never a specific file (the Planner's own §4 maps globs to files at
227
+ * render time).
228
+ */
229
+ export function parseIssueSurface(body: string): ParsedIssueSection<IssueSurface> {
230
+ const section = topLevelSectionText(body, 'Surface')
231
+ if (section === null) return { ok: false, errors: ['no `## Surface` heading found in the body.'] }
232
+
233
+ const inLine = /^in:\s*(.+)$/im.exec(section)
234
+ const outLine = /^out:\s*(.+)$/im.exec(section)
235
+ const errors: string[] = []
236
+ if (!inLine) errors.push('`## Surface` has no `in:` line.')
237
+ if (!outLine) errors.push('`## Surface` has no `out:` line.')
238
+ if (errors.length > 0) return { ok: false, errors }
239
+
240
+ const inGlobs = splitGlobList((inLine as RegExpExecArray)[1] as string)
241
+ const outGlobs = splitGlobList((outLine as RegExpExecArray)[1] as string)
242
+ for (const g of [...inGlobs, ...outGlobs]) {
243
+ if (looksLikeFilePath(g)) {
244
+ errors.push(
245
+ `\`${g}\` in \`## Surface\` looks like a file path — Surface entries are directory-level globs, never file paths.`
246
+ )
247
+ }
248
+ }
249
+ if (inGlobs.length === 0) errors.push("`## Surface`'s `in:` line resolved to zero globs.")
250
+ if (errors.length > 0) return { ok: false, errors }
251
+
252
+ return { ok: true, value: { in: inGlobs, out: outGlobs } }
253
+ }
254
+
255
+ /**
256
+ * A directory-level glob/path from one field "covers" a directory-level
257
+ * domain/path from another when either contains the other as a path prefix
258
+ * — shared by O4 (does a `## Surface` `in:` glob touch a shared collision
259
+ * domain?) and O6 (does a `## Surface` glob contain a doc pointer?). Both
260
+ * sides are stripped of a trailing `/**`/`/*` and any trailing slash first.
261
+ */
262
+ export function globCoversPath(glob: string, path: string): boolean {
263
+ const g = glob.replace(/\/\*\*?$/, '').replace(/\/+$/, '')
264
+ const p = path.replace(/\/+$/, '')
265
+ return g === p || g.startsWith(`${p}/`) || p.startsWith(`${g}/`)
266
+ }
267
+
268
+ /**
269
+ * **O1 — a declared Surface glob must resolve.** Every `## Surface` `in:`
270
+ * glob must match at least one real tracked file, or a Surface that cannot
271
+ * render a file list is caught at authoring time instead of at dispatch
272
+ * (`brief-assembly.ts`'s own render-time sanity check, which currently
273
+ * catches the identical defect too late). `resolvesToFile` is injected —
274
+ * this module stays pure, no `git`/`fs` — and the caller
275
+ * (`forge-write.ts`) passes the SAME `expandGlob` predicate
276
+ * `brief-assembly.ts` already uses to render, so the gate and the renderer
277
+ * can never disagree about whether a glob resolves.
278
+ *
279
+ * A backtick-wrapped glob (`` `packages/foo/**` ``) is not stripped or
280
+ * specially refused here: the literal backticks are part of the string
281
+ * handed to `resolvesToFile`, which can never match a real tracked path, so
282
+ * this check catches it the same way it catches a typo'd directory — naming
283
+ * the glob exactly as written, backticks included.
284
+ *
285
+ * `out:` entries are not checked — declaring something out of scope that
286
+ * does not yet exist (a directory not yet created) is a legitimate
287
+ * exclusion, not a defect.
288
+ */
289
+ export function checkSurfaceGlobsResolve(body: string, resolvesToFile: (glob: string) => boolean): IssueSectionResult {
290
+ const surface = parseIssueSurface(body)
291
+ if (!surface.ok) return { status: 'pass', errors: [] }
292
+ const errors: string[] = []
293
+ for (const glob of surface.value.in) {
294
+ if (!resolvesToFile(glob)) {
295
+ errors.push(
296
+ `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.`
297
+ )
298
+ }
299
+ }
300
+ return { status: errors.length > 0 ? 'fail' : 'pass', errors }
301
+ }
302
+
303
+ export type SurfaceScopeViolation = { file: string; glob: string }
304
+ export type SurfaceScopeResult = { ok: true } | { ok: false; violations: SurfaceScopeViolation[] }
305
+
306
+ /**
307
+ * **O7 — a task-branch PR's changed files must stay inside its Issue's
308
+ * declared surface.** `outGlobs` is the Issue's own `## Surface` `out:`
309
+ * list (parsed by the caller via `parseIssueSurface`, same reuse discipline
310
+ * as everything else here); `changedFiles` is the PR/branch's own diff.
311
+ * Every changed file crossing a declared `out:` glob is a violation, naming
312
+ * both the file and the glob it crosses — collected in one pass (O12's own
313
+ * discipline), never only the first. Uses the SAME `globCoversPath`
314
+ * predicate O4/O6 already use to decide whether a Surface glob covers a
315
+ * path, so "does this file cross the boundary" can never disagree with how
316
+ * the boundary itself is read elsewhere in this module.
317
+ *
318
+ * Pure: takes the already-resolved file list and glob list, never reads
319
+ * disk or the forge itself — the caller (a check-bin adapter) resolves
320
+ * both.
321
+ */
322
+ export function checkSurfaceScope(changedFiles: string[], outGlobs: string[]): SurfaceScopeResult {
323
+ if (outGlobs.length === 0) return { ok: true }
324
+ const violations: SurfaceScopeViolation[] = []
325
+ for (const file of changedFiles) {
326
+ const glob = outGlobs.find((g) => globCoversPath(g, file))
327
+ if (glob) violations.push({ file, glob })
328
+ }
329
+ return violations.length > 0 ? { ok: false, violations } : { ok: true }
330
+ }
331
+
332
+ /** One `Part <n> (<refs>) — <outcome>` line, anywhere in the `## Parts` section. */
333
+ const ISSUE_PART_LINE_RE = /^Part\s+(\d+)\s*\(([^)]*)\)\s*[-—–]\s*(.*)$/i
334
+
335
+ /**
336
+ * `## Parts` — numbered `Part <n> (O<k>[, O<j>]) — <outcome>` lines, the same
337
+ * citation grammar `brief-validation.ts`'s `PART_CITATION_RE` reads out of a
338
+ * brief's own §6. An outcome names outcomes and symbols, never a file path
339
+ * (refused the same way `objectives.ts` refuses a bare-path objective).
340
+ */
341
+ export function parseIssueParts(body: string): ParsedIssueSection<IssuePart[]> {
342
+ const section = topLevelSectionText(body, 'Parts')
343
+ if (section === null) return { ok: false, errors: ['no `## Parts` heading found in the body.'] }
344
+
345
+ const lines = section
346
+ .split(/\r?\n/)
347
+ .map((l) => l.trim())
348
+ .filter((l) => l.length > 0)
349
+
350
+ const parts: IssuePart[] = []
351
+ const errors: string[] = []
352
+ for (const line of lines) {
353
+ const m = ISSUE_PART_LINE_RE.exec(line)
354
+ if (!m) {
355
+ errors.push(`"${line}" is not a well-formed Parts line — expected \`Part <n> (<refs>) — <outcome>\`.`)
356
+ continue
357
+ }
358
+ const n = Number.parseInt(m[1] as string, 10)
359
+ const refs = m[2] as string
360
+ const text = (m[3] as string).trim()
361
+ if (text.length === 0) {
362
+ errors.push(`Part ${n} has no outcome text after the dash — every Part states one observable outcome.`)
363
+ continue
364
+ }
365
+ if (partHasBacktickedPath(text) && partWordCount(stripPartBackticks(text)) < PART_MIN_WORDS_OUTSIDE_BACKTICKS) {
366
+ errors.push(`Part ${n} is little more than a file path — a Part names an outcome and symbols, never a bare path.`)
367
+ continue
368
+ }
369
+ const objectiveIds = [...refs.matchAll(/O(\d+)/g)].map((r) => Number.parseInt(r[1] as string, 10))
370
+ parts.push({ n, objectiveIds, text })
371
+ }
372
+
373
+ if (parts.length === 0) {
374
+ errors.push('the `## Parts` section has no well-formed `Part <n> (<refs>) — <outcome>` lines.')
375
+ }
376
+ if (errors.length > 0) return { ok: false, errors }
377
+ return { ok: true, value: parts }
378
+ }
379
+
380
+ /**
381
+ * **O2 — a `## Parts` citation must name a real Objective.** `Part <n>
382
+ * (O<k>, …)` cites objective ids the Issue's own `## Objectives` section
383
+ * defines — reusing `objectivesOf` (the one Objectives parser every other
384
+ * consumer reads, `objectives.ts`'s own doc comment) rather than a second
385
+ * hand-rolled id set, so this can never disagree with what the Objectives
386
+ * gate itself accepts.
387
+ *
388
+ * Passes trivially when either section is malformed — `checkIssueParts`'s
389
+ * own shape errors and `checkIssueObjectives`'s own errors already cover
390
+ * that; this function only ever reports a citation of an id that is
391
+ * genuinely absent from an otherwise well-formed Objectives list.
392
+ */
393
+ export function checkPartsCiteDefinedObjectives(body: string): IssueSectionResult {
394
+ const parts = parseIssueParts(body)
395
+ const objectives = objectivesOf(body)
396
+ if (!parts.ok || !objectives.ok) return { status: 'pass', errors: [] }
397
+ const definedIds = new Set(objectives.objectives.map((o) => Number.parseInt(o.id.slice(1), 10)))
398
+ const errors: string[] = []
399
+ for (const part of parts.value) {
400
+ for (const objectiveId of part.objectiveIds) {
401
+ if (!definedIds.has(objectiveId)) {
402
+ errors.push(
403
+ `issue-validation Parts: Part ${part.n} cites O${objectiveId}, which the Issue's own \`## Objectives\` section does not define.`
404
+ )
405
+ }
406
+ }
407
+ }
408
+ return { status: errors.length > 0 ? 'fail' : 'pass', errors }
409
+ }
410
+
411
+ const ISSUE_PRINCIPAL_LINE_RE = /^-\s*\[[ xX]\]\s*\*{2}\[principal\]\*{2}(.*)$/gim
412
+ const UNIT_TESTS_ONLY_SENTINEL_RE = /(?:\*\*)?Test plan(?:\*\*)?\s*:\s*(?:\*\*)?\s*unit-tests-only/i
413
+
414
+ /**
415
+ * `bunx turbo test` never takes a single-file argument at
416
+ * all (it runs a whole package's suite by construction), so any form of it
417
+ * is whole-suite. `bun test` and `vitest run` are whole-suite only when no
418
+ * argument in the line names an actual test file — a bare invocation or a
419
+ * directory argument still runs everything under it.
420
+ */
421
+ const TURBO_TEST_RE = /\bbunx\s+turbo\s+test\b/i
422
+ const BUN_TEST_RE = /\bbun\s+test\b/i
423
+ const VITEST_RUN_RE = /\bvitest\s+run\b/i
424
+ const TEST_FILE_ARG_RE = /[^\s'"]+\.(?:test|spec)\.[jt]sx?\b/i
425
+
426
+ /** Same length, quoted regions blanked — so an index found in the result still points at the real character in the original string. */
427
+ function maskQuoted(s: string): string {
428
+ return s.replace(/'[^']*'/g, (m) => 'x'.repeat(m.length)).replace(/"[^"]*"/g, (m) => 'x'.repeat(m.length))
429
+ }
430
+
431
+ /**
432
+ * A shell comment (an unquoted `#` to end of line) can plant a real test-file
433
+ * path AFTER the runner invocation it never actually reaches — the invoked
434
+ * command is still the bare part before the `#`. Found live (security
435
+ * review): `bun test # apps/cli/tests/foo.test.ts` satisfied
436
+ * `TEST_FILE_ARG_RE` by matching the commented-out path, though the line it
437
+ * names still runs the whole suite.
438
+ */
439
+ function stripLineComment(s: string): string {
440
+ const idx = maskQuoted(s).indexOf('#')
441
+ return idx === -1 ? s : s.slice(0, idx)
442
+ }
443
+
444
+ /**
445
+ * Splits on an unquoted `;`, `&&`, or `||` — a chained line can smuggle a
446
+ * real test-file path into a SECOND statement while the FIRST one, the
447
+ * runner invocation itself, still has no argument. Found live (security
448
+ * review): `bun test; echo apps/cli/tests/foo.test.ts` satisfied
449
+ * `TEST_FILE_ARG_RE` against the whole line, though the `bun test` statement
450
+ * that actually runs still has no file argument.
451
+ */
452
+ function commandStatements(command: string): string[] {
453
+ const masked = maskQuoted(command)
454
+ const statements: string[] = []
455
+ let last = 0
456
+ const re = /;|&&|\|\|/g
457
+ let m: RegExpExecArray | null
458
+ // biome-ignore lint/suspicious/noAssignInExpressions: standard exec-loop idiom
459
+ while ((m = re.exec(masked)) !== null) {
460
+ statements.push(command.slice(last, m.index))
461
+ last = m.index + m[0].length
462
+ }
463
+ statements.push(command.slice(last))
464
+ return statements
465
+ }
466
+
467
+ /**
468
+ * A Test plan line naming a test runner with no test-file argument can run
469
+ * the whole suite once dispatched — the developer role's pre-push hook
470
+ * already runs the affected suite on its own (`roles/developer.md`), so a
471
+ * Planner's Test plan line exists to name the file(s) THIS task's own Part
472
+ * proves, never to re-authorize the whole thing. A line that isn't a
473
+ * recognized test-runner invocation at all (a `vinaya check` command, an
474
+ * arbitrary CLI call) is never whole-suite by this definition. Judged one
475
+ * statement at a time (see `commandStatements`/`stripLineComment`) so a
476
+ * trailing chained command or comment can never smuggle in a test-file
477
+ * argument the runner invocation itself never receives.
478
+ */
479
+ function isWholeSuiteTestPlanLine(line: string): boolean {
480
+ for (const raw of commandStatements(line)) {
481
+ const stmt = stripLineComment(raw)
482
+ if (TURBO_TEST_RE.test(stmt)) return true
483
+ if ((BUN_TEST_RE.test(stmt) || VITEST_RUN_RE.test(stmt)) && !TEST_FILE_ARG_RE.test(stmt)) return true
484
+ }
485
+ return false
486
+ }
487
+
488
+ /**
489
+ * `## Test plan` — reuses `checkTestPlan`/`extractFencedBlocks`
490
+ * (`brief-validation.ts`) rather than a second parser: the `unit-tests-only`
491
+ * sentinel, or a fenced command list plus optional `**[principal]**` items.
492
+ * The two forms are mutually exclusive, same rule `checkTestPlanExclusivity`
493
+ * applies to a PR body's Test Plan.
494
+ */
495
+ export function parseIssueTestPlan(body: string): ParsedIssueSection<IssueTestPlan> {
496
+ const located = locateTestPlanSection(body)
497
+ if (!located.found) return { ok: false, errors: ['no `## Test plan` section found in the body.'] }
498
+
499
+ const presence = checkTestPlan(body)
500
+ if (presence.status === 'fail') return { ok: false, errors: presence.errors }
501
+
502
+ const region = located.section
503
+ const hasSentinel = UNIT_TESTS_ONLY_SENTINEL_RE.test(region)
504
+ const blocks = extractFencedBlocks(region)
505
+
506
+ if (hasSentinel && blocks.length > 0) {
507
+ return {
508
+ ok: false,
509
+ errors: [
510
+ '`## Test plan` carries both the `unit-tests-only` sentinel and a fenced command list — the two are mutually exclusive, same exclusivity rule as the PR body Test Plan.'
511
+ ]
512
+ }
513
+ }
514
+ if (hasSentinel) return { ok: true, value: { kind: 'unit-tests-only' } }
515
+
516
+ const lines = blocks.flatMap((b) =>
517
+ b.content
518
+ .split('\n')
519
+ .map((l) => l.trim())
520
+ .filter((l) => l.length > 0)
521
+ )
522
+
523
+ const wholeSuiteLines = lines.filter(isWholeSuiteTestPlanLine)
524
+ if (wholeSuiteLines.length > 0) {
525
+ return {
526
+ ok: false,
527
+ errors: wholeSuiteLines.map(
528
+ (line) =>
529
+ `\`${line}\` runs a test runner with no test-file argument — a \`## Test plan\` line must name one or more \`*.test.*\`/\`*.spec.*\` files (e.g. \`bun test apps/cli/tests/lib/dev-review-loop.test.ts\`) or a \`vinaya check\` command; a bare \`bun test\`, \`bun test\` on a directory, any \`bunx turbo test\` form, or \`vitest run\` on a package can run the whole suite, which the pre-push hook already covers on its own.`
530
+ )
531
+ }
532
+ }
533
+
534
+ const principal = [...region.matchAll(ISSUE_PRINCIPAL_LINE_RE)].map((m) => (m[1] ?? '').trim()).filter(Boolean)
535
+ if (lines.length === 0 && principal.length === 0) {
536
+ return {
537
+ ok: false,
538
+ errors: [
539
+ '`## Test plan` carries neither the `unit-tests-only` sentinel, a fenced command list, nor a `**[principal]**` item.'
540
+ ]
541
+ }
542
+ }
543
+ return { ok: true, value: { kind: 'commands', lines, principal } }
544
+ }
545
+
546
+ /** `## Stop conditions` — a bullet list, each item the outcome-agnostic condition under which the executing agent must stop and escalate. */
547
+ export function parseIssueStopConditions(body: string): ParsedIssueSection<string[]> {
548
+ const section = topLevelSectionText(body, 'Stop conditions')
549
+ if (section === null) return { ok: false, errors: ['no `## Stop conditions` heading found in the body.'] }
550
+ const items = [...section.matchAll(/^[-*]\s+(.+)$/gm)].map((m) => (m[1] as string).trim()).filter(Boolean)
551
+ if (items.length === 0) {
552
+ return { ok: false, errors: ['the `## Stop conditions` section has no bullet-list items.'] }
553
+ }
554
+ return { ok: true, value: items }
555
+ }
556
+
557
+ export type IssueDocumentationSource = { source: string; mechanism: string; objectiveIds: number[] }
558
+ export type IssueDocumentation = { kind: 'none' } | { kind: 'sources'; sources: IssueDocumentationSource[] }
559
+
560
+ /** The explicit opt-out for a task with no externally-normative source — same sentinel shape as `Test Plan: unit-tests-only`/"No doc updates required". */
561
+ const NO_DOCUMENTATION_SENTINEL_RE = /^none\b/i
562
+
563
+ /**
564
+ * One well-formed `## Documentation` line: a source, then the mechanism it
565
+ * governs, split on an em/en-dash (optional surrounding whitespace — those
566
+ * two characters never appear inside a real URL/path, so they are
567
+ * unambiguous) or an ASCII hyphen with MANDATORY whitespace on both sides.
568
+ * The mandatory-whitespace form is deliberate, not `## Parts`'s own looser
569
+ * `\s*[-—–]\s*` (`ISSUE_PART_LINE_RE`): Parts' literal `Part <n> (<refs>)`
570
+ * prefix already anchors where its separator falls, so a hyphen anywhere
571
+ * else in the line is never ambiguous there. A Documentation line has no
572
+ * such anchor — its source is very often a URL — and a real doc-page path
573
+ * routinely contains an unspaced hyphen (`agent-sdk`, `cost-tracking`);
574
+ * against the old `\s*[-—–]\s*` shape, the lazy source capture stopped at
575
+ * the FIRST such in-URL hyphen, truncating the source and corrupting the
576
+ * mechanism text (round 2 review, BLOCKER, O1/O2 — verified live:
577
+ * `https://code.claude.com/docs/en/agent-sdk/cost-tracking` split at
578
+ * `.../agent`). Requiring `\s+-\s+` for the hyphen form specifically closes
579
+ * that gap: no URL contains a literal space, so an in-path hyphen can never
580
+ * satisfy it, while a real Planner-written ` - ` separator still does. An
581
+ * OPTIONAL trailing `(O<n>[, O<m>])` citation follows — same grammar Parts
582
+ * cites Objectives with, moved to the end here since a source/mechanism pair
583
+ * reads naturally before the citation that grades it (O3). The
584
+ * citation group only ever matches a real `O<digits>` list, so a mechanism
585
+ * whose own prose ends in an ordinary parenthetical (never shaped like
586
+ * `(O2)`) is never mistaken for one — it stays part of the mechanism capture
587
+ * instead.
588
+ */
589
+ const ISSUE_DOCUMENTATION_LINE_RE = /^[-*]\s+(.+?)(?:\s+-\s+|\s*[—–]\s*)(.+?)(?:\s*\((O\d+(?:\s*,\s*O\d+)*)\))?$/i
590
+
591
+ /**
592
+ * `## Documentation` — one bullet per normative source (a doc URL or an
593
+ * in-repo path) against the mechanism it governs: `- <source> — <mechanism>
594
+ * (O<n>)`. A task with no externally-documented mechanism states the
595
+ * explicit `None` sentinel instead of an empty section — silence is never
596
+ * read as "nothing to cite" (the failure this section closes is
597
+ * a source assumed read, never verified). `topLevelSectionText`/the
598
+ * dash-split grammar mirror `parseIssueParts`'s own shape, so this reads as
599
+ * one more judgment section, not a bespoke grammar.
600
+ */
601
+ export function parseIssueDocumentation(body: string): ParsedIssueSection<IssueDocumentation> {
602
+ const section = topLevelSectionText(body, 'Documentation')
603
+ if (section === null) return { ok: false, errors: ['no `## Documentation` heading found in the body.'] }
604
+
605
+ const lines = section
606
+ .split(/\r?\n/)
607
+ .map((l) => l.trim())
608
+ .filter((l) => l.length > 0)
609
+
610
+ if (lines.length > 0 && lines.every((l) => NO_DOCUMENTATION_SENTINEL_RE.test(l))) {
611
+ return { ok: true, value: { kind: 'none' } }
612
+ }
613
+
614
+ const sources: IssueDocumentationSource[] = []
615
+ const errors: string[] = []
616
+ for (const line of lines) {
617
+ const m = ISSUE_DOCUMENTATION_LINE_RE.exec(line)
618
+ if (!m) {
619
+ errors.push(
620
+ `"${line}" is not a well-formed Documentation line — expected \`- <source> — <mechanism it governs>\` (or the \`None\` sentinel).`
621
+ )
622
+ continue
623
+ }
624
+ const source = (m[1] as string).trim()
625
+ const mechanism = (m[2] as string).trim()
626
+ if (source.length === 0 || mechanism.length === 0) {
627
+ errors.push(`"${line}" is missing a source or a mechanism — a Documentation line needs both.`)
628
+ continue
629
+ }
630
+ const objectiveIds = m[3]
631
+ ? [...(m[3] as string).matchAll(/O(\d+)/gi)].map((r) => Number.parseInt(r[1] as string, 10))
632
+ : []
633
+ sources.push({ source, mechanism, objectiveIds })
634
+ }
635
+ if (sources.length === 0 && errors.length === 0) {
636
+ errors.push(
637
+ 'the `## Documentation` section has no well-formed `- <source> — <mechanism>` lines, and no `None` sentinel.'
638
+ )
639
+ }
640
+ if (errors.length > 0) return { ok: false, errors }
641
+ return { ok: true, value: { kind: 'sources', sources } }
642
+ }
643
+
644
+ /**
645
+ * **O3 — the Documentation obligation is graded, not assumed.** When
646
+ * `## Documentation` names at least one real source (`kind: 'sources'`, the
647
+ * `None` sentinel is exempt — nothing to grade), at least one of those
648
+ * sources must cite a real `## Objectives` id via the trailing `(O<n>)`
649
+ * grammar `parseIssueDocumentation` accepts. This is what lets the Reviewer's
650
+ * ordinary `O<n>: MET | NOT MET` grading (already run on every task) cover
651
+ * whether the cited source's mechanism/version was actually incorporated,
652
+ * rather than leaving the obligation to compete on salience alone with
653
+ * nothing checking it. The review-gate stays the
654
+ * backstop that catches a wrong `MET`; this check only proves a graded home
655
+ * for the obligation exists at all.
656
+ *
657
+ * Passes trivially when Documentation or Objectives fails to parse —
658
+ * `checkIssueBriefSections`'s own Documentation branch and
659
+ * `checkIssueObjectives` already report that; this function only ever
660
+ * reports a genuinely uncited, well-formed Documentation section.
661
+ */
662
+ export function checkDocumentationCitesObjective(body: string): IssueSectionResult {
663
+ const documentation = parseIssueDocumentation(body)
664
+ if (!documentation.ok || documentation.value.kind === 'none') return { status: 'pass', errors: [] }
665
+ const objectives = objectivesOf(body)
666
+ if (!objectives.ok) return { status: 'pass', errors: [] }
667
+ const definedIds = new Set(objectives.objectives.map((o) => Number.parseInt(o.id.slice(1), 10)))
668
+ const cited = documentation.value.sources.some((s) => s.objectiveIds.some((id) => definedIds.has(id)))
669
+ if (cited) return { status: 'pass', errors: [] }
670
+ return {
671
+ status: 'fail',
672
+ errors: [
673
+ "issue-validation Documentation: `## Documentation` names a real source but none cites a defined `## Objectives` id — add `(O<n>)` to at least one source line so the Reviewer's ordinary Objectives grading covers whether its mechanism/version was actually incorporated."
674
+ ]
675
+ }
676
+ }
677
+
678
+ /**
679
+ * The Issue number from which the four judgment sections above become
680
+ * mandatory — this Issue's own number, the first Issue this tranche cut.
681
+ * Same cutover-by-Issue-number shape as `OBJECTIVES_SINCE_ISSUE`; a task
682
+ * Issue below this number legitimately carries none of the four.
683
+ */
684
+ export const BRIEF_SECTIONS_SINCE_ISSUE = 426
685
+
686
+ /**
687
+ * The Issue number from which `## Documentation` becomes mandatory alongside
688
+ * the four sections above — deliberately one past this requirement's own
689
+ * Issue (the highest Issue number in existence when it was authored),
690
+ * so no open or historical Issue is invalidated by the new requirement and
691
+ * `issue edit` on one never starts refusing a body it could not have carried
692
+ * the section in. Never grandfathered further back than that: unlike
693
+ * `BRIEF_SECTIONS_SINCE_ISSUE`'s 426, there is no stock of Issues that
694
+ * already carry a literal `## Documentation` heading by hand to preserve.
695
+ */
696
+ export const DOCUMENTATION_SINCE_ISSUE = 626
697
+
698
+ /**
699
+ * **The brief-sections gate.** A task Issue numbered at or above
700
+ * `BRIEF_SECTIONS_SINCE_ISSUE` must carry all four of `## Surface`,
701
+ * `## Parts`, `## Test plan`, `## Stop conditions`, each well-formed per its
702
+ * own parser above. Below the cutover, an Issue passes unconditionally.
703
+ * `issueNumber === null` is NOT exempted — fail-closed, the same posture
704
+ * `checkIssueObjectives` takes for an Issue with no number yet.
705
+ *
706
+ * A fifth section, `## Documentation`, is folded into this same gate rather
707
+ * than a new builtin (O1) — it is graded on its own, later
708
+ * cutover (`DOCUMENTATION_SINCE_ISSUE`), since no pre-existing Issue ever
709
+ * carried it and requiring it retroactively on an `issue edit` would refuse a
710
+ * body no author had reason to write that way.
711
+ */
712
+ export function checkIssueBriefSections(body: string, issueNumber: number | null): IssueSectionResult {
713
+ if (issueNumber !== null && issueNumber < BRIEF_SECTIONS_SINCE_ISSUE) return { status: 'pass', errors: [] }
714
+
715
+ const errors: string[] = []
716
+ const surface = parseIssueSurface(body)
717
+ if (!surface.ok) errors.push(...surface.errors.map((e) => `issue-validation Surface: ${e}`))
718
+ const parts = parseIssueParts(body)
719
+ if (!parts.ok) errors.push(...parts.errors.map((e) => `issue-validation Parts: ${e}`))
720
+ const testPlan = parseIssueTestPlan(body)
721
+ if (!testPlan.ok) errors.push(...testPlan.errors.map((e) => `issue-validation Test plan: ${e}`))
722
+ const stopConditions = parseIssueStopConditions(body)
723
+ if (!stopConditions.ok) errors.push(...stopConditions.errors.map((e) => `issue-validation Stop conditions: ${e}`))
724
+
725
+ if (issueNumber === null || issueNumber >= DOCUMENTATION_SINCE_ISSUE) {
726
+ const documentation = parseIssueDocumentation(body)
727
+ if (!documentation.ok) errors.push(...documentation.errors.map((e) => `issue-validation Documentation: ${e}`))
728
+ else errors.push(...checkDocumentationCitesObjective(body).errors)
729
+ }
730
+
731
+ return { status: errors.length > 0 ? 'fail' : 'pass', errors }
732
+ }
733
+
92
734
  /** true when any label marks this as a task Issue (the rationale contract applies). */
93
735
  export function isTaskIssueLabelSet(labels: string[]): boolean {
94
736
  return hasLabel('tranche', labels)
95
737
  }
96
738
 
739
+ /** The literal `## Objectives` heading — independent of whether the section that follows it actually parses (a malformed one is still evidence of task-shape, and is `checkIssueObjectives`'s own concern, not this detector's). */
740
+ const OBJECTIVES_HEADING_RE = /^##[ \t]*Objectives[ \t]*$/im
741
+
742
+ /**
743
+ * **O1 — is this body task-Issue-shaped at all?** The
744
+ * forge-write label gate (`forge-write.ts`'s `refuseUnlabeledTaskShapedBody`,
745
+ * and `bin/open-issue.ts`'s mirrored inline check) uses this to catch a
746
+ * Planner's mistake `isTaskIssueLabelSet`-gated validation cannot see: a body
747
+ * that carries the Planner's judgment sections but no `vinaya/tranche:*`
748
+ * label reads, to every check gated behind `isTaskIssueLabelSet`, as "not a
749
+ * task Issue" and sails through unvalidated — the exact hole a task Issue
750
+ * never reaching the forge unlabeled falls through.
751
+ *
752
+ * Two signals, either sufficient: a real `## Objectives` heading, or any ONE
753
+ * of the eight Planner's-rationale fields (`hasRationaleField` — the same
754
+ * tolerant bold-inline-or-heading detector `checkIssueRationale` itself
755
+ * checks all eight with). Reusing that detector, rather than a third
756
+ * "does this look like a rationale section" heuristic, is deliberate: a body
757
+ * this function calls task-shaped is, by construction, exactly the set of
758
+ * bodies `checkIssueRationale` would go on to grade — a real Issue can carry
759
+ * its rationale under a heading `checkIssueRationale` never requires to be
760
+ * literally "## Planner's rationale" (`apps/cli/tests/fixtures/forge/issue-valid.md`
761
+ * uses "## Task Issue — Planner rationale"), so gating on that literal
762
+ * heading text alone under-detects.
763
+ */
764
+ export function isTaskIssueBodyShaped(body: string): boolean {
765
+ const text = stripCode(body)
766
+ if (OBJECTIVES_HEADING_RE.test(text)) return true
767
+ return RATIONALE_FIELDS.some((f) => hasRationaleField(text, f.pattern))
768
+ }
769
+
770
+ /**
771
+ * task 17, O2 — one of the six write-only rules given a name apart: a task-
772
+ * shaped Issue body reaching the forge with no `vinaya/tranche:*` label. Pure
773
+ * over `isTaskIssueBodyShaped`/`isTaskIssueLabelSet` — the exact predicate
774
+ * `forge-write.ts`'s `refuseUnlabeledTaskShapedBody` and `bin/open-issue.ts`'s
775
+ * mirrored inline check already enforce; this names it once so a registered
776
+ * `issue`-scope check and the coherence sweep can both call the SAME
777
+ * function instead of re-deriving the same two-line condition.
778
+ *
779
+ * **Retired to an always-pass check.** A task-
780
+ * shaped body reaching the forge with no `vinaya/tranche:*` label is no
781
+ * longer, by itself, evidence of a mistake — it is the exact shape of a
782
+ * legitimate backlog Issue (`task run --issue <n>`'s own dispatch target),
783
+ * which carries the same body grammar as a tranche task with the label
784
+ * simply omitted. The invariant this rule enforced ("a task Issue never
785
+ * reaches the forge unlabeled") no longer holds; kept as a function (never
786
+ * deleted) so every caller above stays wired to one place rather than three
787
+ * independently-updated copies, and so a future rule needing this exact
788
+ * shape has somewhere to register itself apart from a fresh predicate.
789
+ */
790
+ export function checkTrancheLabelPresence(_body: string, _labels: string[]): IssueSectionResult {
791
+ return { status: 'pass', errors: [] }
792
+ }
793
+
794
+ /**
795
+ * task 17, O2 — the Milestone-attach rule's validating half. The auto-attach
796
+ * ACTION (`resolveMilestoneAttachArgs`/`resolveMilestoneTitleForCreate` in
797
+ * `forge-write.ts`) mutates argv best-effort; this is the check that proves
798
+ * the attach actually landed — a task Issue's live Milestone must equal the
799
+ * target its tranche label resolves to, once that target is known at all.
800
+ * Dormant (`pass`) whenever the caller could not resolve one side or the
801
+ * other — a Milestone this process cannot determine has no known target to
802
+ * compare against, the same seam-is-dormant-when-absent posture
803
+ * `forge-write.ts` already uses for `docOwnersContent`/`sharedPackages`.
804
+ */
805
+ export function checkMilestoneAttach(
806
+ labels: string[],
807
+ currentMilestoneTitle: string | null,
808
+ resolvedMilestoneTitle: string | null
809
+ ): IssueSectionResult {
810
+ if (!isTaskIssueLabelSet(labels)) return { status: 'pass', errors: [] }
811
+ if (resolvedMilestoneTitle === null) return { status: 'pass', errors: [] }
812
+ if (currentMilestoneTitle === resolvedMilestoneTitle) return { status: 'pass', errors: [] }
813
+ return {
814
+ status: 'fail',
815
+ errors: [
816
+ `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}".`
817
+ ]
818
+ }
819
+ }
820
+
97
821
  /** Every `vinaya/type:*` label id, in `labels.ts` order — the source of truth this check reads, never a second list. */
98
822
  const TYPE_LABEL_IDS = LABELS.filter((l) => l.category === 'type').map((l) => l.id)
99
823
 
@@ -136,7 +860,7 @@ export function checkIssueType(_body: string, labels: string[]): IssueSectionRes
136
860
  //
137
861
  // `checkIssueRationale` above checks the eight fields are PRESENT and
138
862
  // well-formed. It never checks what they SAY against the surface the task
139
- // touches — and three task Issues in `vinaya-pages-v2` (#621/#622/#626) passed
863
+ // touches — and three real task Issues passed
140
864
  // it while being wrong in three distinct ways: a `packages/ui` edit declared
141
865
  // `Project: vinaya` only (blast radius under-declared, so the review fans out
142
866
  // through one product's lens instead of every consumer's); a `## References`
@@ -147,7 +871,7 @@ export function checkIssueType(_body: string, labels: string[]): IssueSectionRes
147
871
  // deterministic functions on the surface they happened on.
148
872
  //
149
873
  // EVERY ONE OF THEM READS BLOCK-STRIPPED TEXT, via the single exported
150
- // `stripCode` — never a second regex (PR #617's rule). A rationale that quotes
874
+ // `stripCode` — never a second regex. A rationale that quotes
151
875
  // `## References`, `Premise:`, or a `packages/ui` path inside a **fence** is
152
876
  // documenting, not leaking, and must not trip anything; GitHub's own parsers
153
877
  // ignore code the same way.
@@ -157,14 +881,14 @@ export function checkIssueType(_body: string, labels: string[]): IssueSectionRes
157
881
  // - B looks for brief-shaped *headings*, which never live in a span, so it
158
882
  // takes the full default strip.
159
883
  // - A/C/D look for *paths*, and prose writes paths in backticks by
160
- // convention — #621 declares its own surface as "edits `packages/ui`". Run
884
+ // convention — a real task declares its own surface as "edits `packages/ui`". Run
161
885
  // span-blind, A matches nothing on the very Issues it was built from and
162
886
  // ships as a gate that always passes, which is worse than no gate. So they
163
887
  // read `PATH_TEXT`: fences and indented blocks gone, spans intact.
164
888
  //
165
889
  // Accepted cost: brief content that leaks *entirely inside* a fence is
166
890
  // invisible to B. Same trade every code-aware gate here makes; the alternative
167
- // is the fence-blind false-positive machine #617 removed.
891
+ // is the fence-blind false-positive machine a real fix removed.
168
892
  // ---------------------------------------------------------------------------
169
893
 
170
894
  /**
@@ -276,7 +1000,7 @@ function forMessage(value: string): string {
276
1000
 
277
1001
  /**
278
1002
  * The projects a task Issue declares — its body's `**Project:**` field, and
279
- * only that. Project is a **field, not a label** (doctrine): #614 dropped the
1003
+ * only that. Project is a **field, not a label** (doctrine): a real migration dropped the
280
1004
  * `project:*` labels outright, and `@attalabs/aeg-forge-state`'s `list-tasks.ts`
281
1005
  * derives a task's project from the same field, so the two agree by
282
1006
  * construction. `labels` stays in the signature because callers pass it and
@@ -463,7 +1187,7 @@ export function checkProjectsRegistered(
463
1187
  * **A cited document is not a touched domain.** Every rationale points at docs
464
1188
  * for provenance — "the registry row in `.vinaya/projects.md`",
465
1189
  * "per `packages/ui/README.md`" — and counting those as edits fails correct
466
- * plans wholesale (it fired on all three of #621/#622/#626 for a projects.md
1190
+ * plans wholesale (it fired on three real tasks for a projects.md
467
1191
  * citation none of them edits). So an occurrence whose full path token ends in
468
1192
  * a doc extension does not count; a bare domain reference, or any non-doc path
469
1193
  * under it, does. Citing `packages/ui/README.md` *and* editing
@@ -491,7 +1215,7 @@ const BLAST_RADIUS_ACK_RE = /(?:\*\*)?blast-radius-ack(?:\*\*)?\s*[:—–-]/i
491
1215
  * review fan-out ("more projects = more review lenses = proportionally more
492
1216
  * rigor"), so a shared-primitive change carrying one product's label is
493
1217
  * reviewed through one lens and under-governs the regression its own prose
494
- * usually admits in the same breath (#621: "**BUT edits `packages/ui`** … any
1218
+ * usually admits in the same breath (a real task: "**BUT edits `packages/ui`** … any
495
1219
  * topbar change is seen by every product").
496
1220
  *
497
1221
  * Two ways to satisfy it, both deliberate: list the other consumers in the
@@ -520,7 +1244,7 @@ const BLAST_RADIUS_ACK_RE = /(?:\*\*)?blast-radius-ack(?:\*\*)?\s*[:—–-]/i
520
1244
  * project field and only that. The previous body-wide read took the first
521
1245
  * field-shaped token *anywhere* in the body, which is routinely prose in Sizing
522
1246
  * or Boundary rather than the declaration: prose carries file paths, and a path
523
- * fragment parses as an invented project name (#870's own blast-radius line
1247
+ * fragment parses as an invented project name (a real blast-radius line
524
1248
  * yielded a project called `src`). Two parsers for one field is how the gate and
525
1249
  * the derivation come to disagree about what a task even declares — so do not
526
1250
  * add a second regex here, nor a pre-clean step that makes one "usually" agree.
@@ -535,27 +1259,54 @@ const BLAST_RADIUS_ACK_RE = /(?:\*\*)?blast-radius-ack(?:\*\*)?\s*[:—–-]/i
535
1259
  * seam-is-dormant-when-absent shape `doc-owners` uses. The check cannot be
536
1260
  * deterministic without its source of truth, and inventing one inline is worse
537
1261
  * than not running.
1262
+ *
1263
+ * **O4 — above the brief-sections cutover, this decides from `## Surface`
1264
+ * alone.** A task Issue's own `Boundary`/`Project(s) + blast radius` prose
1265
+ * can name a shared package precisely IN ORDER TO EXCLUDE it ("does not
1266
+ * touch `packages/ui`") — a negation the text scan below cannot tell apart
1267
+ * from a real touch-claim, and a heuristic in a blocking gate is wrong in
1268
+ * both directions. `## Surface`'s `in:` glob list is parsed structure with
1269
+ * no negation to misread: at or above `BRIEF_SECTIONS_SINCE_ISSUE`, where
1270
+ * every task Issue carries one, a shared domain is "named" iff a declared
1271
+ * `in:` glob covers it (`globCoversPath`) — never by scanning prose for the
1272
+ * domain's name. Below the cutover, an Issue legitimately carries no
1273
+ * `## Surface` at all, so the original prose scan is unchanged.
1274
+ * `issueNumber` follows the same fail-closed posture as
1275
+ * `checkIssueObjectives`/`checkIssueBriefSections`: `null` (not yet known,
1276
+ * e.g. `issue create`) is NOT treated as "at or above the cutover" — it
1277
+ * falls back to the prose scan, since a not-yet-created Issue's own
1278
+ * `## Surface` cannot yet be trusted to be the mandatory kind.
538
1279
  */
539
1280
  export function checkBlastRadiusScope(
540
1281
  body: string,
541
1282
  _labels: string[],
542
1283
  sharedPackages: string[],
543
- projectPaths: ProjectPath[]
1284
+ projectPaths: ProjectPath[],
1285
+ issueNumber: number | null = null
544
1286
  ): IssueSectionResult {
545
1287
  if (sharedPackages.length === 0) return { status: 'pass', errors: [] }
546
- // Scoped to the two fields that declare the task's OWN surface. Scanning the
547
- // whole body fails correct plans in bulk: a rationale names packages for many
548
- // reasons that are not edits — a dependency it imports unchanged (#591/#599
549
- // name `packages/aeg-core` because Vinaya's CLI imports it), a trap to avoid,
550
- // an Origin note. A full-body scan flagged 46 of 166 historical task Issues,
551
- // nearly all of them correctly-scoped work. Boundary and Project(s) + blast
552
- // radius are where a task states what it touches, so that is where a
553
- // touch-claim is load-bearing enough to block on.
554
- const text = [
555
- rationaleFieldText(PATH_TEXT(body), 'Boundary'),
556
- rationaleFieldText(PATH_TEXT(body), 'Project\\(s\\)|Project(?:s)?\\s*\\+|blast radius')
557
- ].join('\n')
558
- const named = sharedPackages.filter((d) => namesPath(text, d))
1288
+ const decideFromSurface = issueNumber !== null && issueNumber >= BRIEF_SECTIONS_SINCE_ISSUE
1289
+ let named: string[]
1290
+ if (decideFromSurface) {
1291
+ const surface = parseIssueSurface(body)
1292
+ const surfaceIn = surface.ok ? surface.value.in : []
1293
+ named = sharedPackages.filter((d) => surfaceIn.some((glob) => globCoversPath(glob, d)))
1294
+ } else {
1295
+ // Scoped to the two fields that declare the task's OWN surface. Scanning
1296
+ // the whole body fails correct plans in bulk: a rationale names packages
1297
+ // for many reasons that are not edits — a dependency it imports unchanged
1298
+ // (real tasks name `packages/aeg-core` because Vinaya's CLI imports it), a
1299
+ // trap to avoid, an Origin note. A full-body scan flagged 46 of 166
1300
+ // historical task Issues, nearly all of them correctly-scoped work.
1301
+ // Boundary and Project(s) + blast radius are where a task states what it
1302
+ // touches, so that is where a touch-claim is load-bearing enough to
1303
+ // block on.
1304
+ const text = [
1305
+ rationaleFieldText(PATH_TEXT(body), 'Boundary'),
1306
+ rationaleFieldText(PATH_TEXT(body), 'Project\\(s\\)|Project(?:s)?\\s*\\+|blast radius')
1307
+ ].join('\n')
1308
+ named = sharedPackages.filter((d) => namesPath(text, d))
1309
+ }
559
1310
  if (named.length === 0) return { status: 'pass', errors: [] }
560
1311
 
561
1312
  // Registry-validated, not merely declared. The bypass below widens the review
@@ -598,13 +1349,18 @@ const BRIEF_MARKERS: Array<{ name: string; pattern: RegExp }> = [
598
1349
  { name: 'Technical surface map', pattern: /(?:^#{1,6}\s*|\*\*)\s*Technical surface map\b/im },
599
1350
  { name: 'Premise', pattern: /(?:^#{1,6}\s*|\*\*)\s*Premise(?:\*\*)?\s*[:—–]/im },
600
1351
  { name: 'Step 0', pattern: /(?:^#{1,6}\s*|\*\*)\s*Step 0\b/im },
601
- { name: 'Test Plan', pattern: /(?:^#{1,6}\s*|\*\*)\s*Test Plan\b/im }
1352
+ // Heading form removed: `## Test plan` is
1353
+ // now an Issue-native section since `BRIEF_SECTIONS_SINCE_ISSUE`, parsed by
1354
+ // `parseIssueTestPlan` above — a heading is not a marker any more. The bold
1355
+ // inline form (`**Test Plan:** …`) is unaffected and still catches a brief's
1356
+ // own Test Plan field pasted verbatim into an Issue.
1357
+ { name: 'Test Plan', pattern: /\*\*\s*Test Plan\b/im }
602
1358
  ]
603
1359
 
604
1360
  /**
605
1361
  * **B — brief content in the Issue.** Fails when the code-stripped body carries
606
1362
  * a brief-shaped heading. The Issue is the Planner's durable rationale; the
607
- * brief is the Brief Author's just-in-time execution context, authored against
1363
+ * brief is the Planner's just-in-time execution context, dispatched against
608
1364
  * the surface as it exists at dispatch. Copying the second into the first
609
1365
  * creates a stale copy nobody re-reads and nobody updates.
610
1366
  */
@@ -627,11 +1383,11 @@ function rationaleFieldText(text: string, labelPattern: string): string {
627
1383
  // instead of just the label — `Docs to keep coherent|§7` compiled as
628
1384
  // "(**|#) Docs to keep coherent" OR "§7[^\n]*…", so the Docs branch matched
629
1385
  // the bare label and captured nothing, and D silently graded every Issue on
630
- // its Traps field alone (#622 failed on exactly this).
1386
+ // its Traps field alone (a real task failed on exactly this).
631
1387
  // The terminator is `(?![\s\S])` — a real end-of-INPUT assertion — not `$`.
632
1388
  // The `m` flag is required for the `^#{1,4}` heading form, and under `m` a
633
1389
  // `$` matches end-of-LINE, so the lazy body satisfied the lookahead
634
- // immediately and every heading-style field (`### §7`, #219) sliced to its
1390
+ // immediately and every heading-style field (`### §7`) sliced to its
635
1391
  // own label with zero content. D then saw an empty field and failed Issues
636
1392
  // that name their docs perfectly well, one line further down.
637
1393
  const re = new RegExp(
@@ -660,6 +1416,9 @@ function rationaleFieldText(text: string, labelPattern: string): string {
660
1416
  const DOC_PATH_RE =
661
1417
  /(?:(?: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
662
1418
 
1419
+ /** `DOC_PATH_RE`, globally — same grammar, used to enumerate every doc pointer in a field rather than only testing presence of one. */
1420
+ const DOC_PATH_RE_GLOBAL = new RegExp(DOC_PATH_RE.source, 'gi')
1421
+
663
1422
  /**
664
1423
  * The doc-less-surface exemption, shaped after `brief-validation`'s
665
1424
  * `Test Plan: unit-tests-only` sentinel: an explicit, greppable opt-out a human
@@ -694,6 +1453,187 @@ export function checkRationaleNamesDocs(body: string): IssueSectionResult {
694
1453
  }
695
1454
  }
696
1455
 
1456
+ /**
1457
+ * **O6 — a "Docs to keep coherent" pointer must not fall inside this task's
1458
+ * own declared `out:` surface.** A doc a task claims to keep coherent, but
1459
+ * that its own `## Surface` explicitly excludes (an `out:` glob), is a
1460
+ * contradiction: the task disclaims touching that doc's directory in the
1461
+ * same breath it claims to keep the doc itself coherent. This gate catches
1462
+ * that contradiction at authoring time, before it ever reaches a brief.
1463
+ *
1464
+ * **The premise this gate rests on is narrower than it once was: absence
1465
+ * from `in:` is not checked here, because nothing at pull-request time
1466
+ * enforces it either.** A pointer's own file is never itself a `## Surface`
1467
+ * entry — Surface globs are directory-level only (`parseIssueSurface`'s own
1468
+ * rule) — so a doc pointer can sit outside every `in:` glob while still
1469
+ * being a single-file edit `checkSurfaceScope` (the pull-request-time gate
1470
+ * this authoring-time check exists to anticipate) would never catch: that
1471
+ * gate refuses a changed file only against `out:`, and never consults `in:`
1472
+ * at all. Refusing "outside `in:`" here bought no real enforcement — it only
1473
+ * forced a Planner to widen a surface around a single doc pointer to satisfy
1474
+ * a check the pull-request gate was never going to make anyway, which is
1475
+ * what rendered an unusable, over-wide brief. So a pointer the surface
1476
+ * simply does not enclose is now accepted; a pointer the surface explicitly
1477
+ * excludes still is not.
1478
+ *
1479
+ * At or above `BRIEF_SECTIONS_SINCE_ISSUE` only — below it an Issue
1480
+ * legitimately carries no `## Surface` to compare against, same cutover
1481
+ * every other Surface-aware check in this module uses. Passes trivially
1482
+ * when the Surface itself doesn't parse (`checkIssueBriefSections` already
1483
+ * reports that malformation) or the docs field carries the `no-doc-surface`
1484
+ * sentinel (nothing to compare).
1485
+ */
1486
+ export function checkDocsWithinSurface(body: string, issueNumber: number | null): IssueSectionResult {
1487
+ if (issueNumber !== null && issueNumber < BRIEF_SECTIONS_SINCE_ISSUE) return { status: 'pass', errors: [] }
1488
+ const surface = parseIssueSurface(body)
1489
+ if (!surface.ok) return { status: 'pass', errors: [] }
1490
+
1491
+ const text = PATH_TEXT(body)
1492
+ const scope = rationaleFieldText(text, 'Docs to keep coherent|§7')
1493
+ if (NO_DOC_SURFACE_RE.test(scope)) return { status: 'pass', errors: [] }
1494
+
1495
+ const pointers = [...new Set([...scope.matchAll(DOC_PATH_RE_GLOBAL)].map((m) => m[0]))]
1496
+ const errors: string[] = []
1497
+ for (const pointer of pointers) {
1498
+ const excludingGlob = surface.value.out.find((glob) => globCoversPath(glob, pointer))
1499
+ if (excludingGlob) {
1500
+ errors.push(
1501
+ `issue-validation Docs to keep coherent: \`${pointer}\` falls inside \`## Surface\`'s \`out:\` glob \`${excludingGlob}\` — this task's own declared surface explicitly excludes the doc it claims to keep coherent.`
1502
+ )
1503
+ }
1504
+ }
1505
+ return { status: errors.length > 0 ? 'fail' : 'pass', errors }
1506
+ }
1507
+
1508
+ /** A backticked repo-path token — at least two `/`-separated segments, so a bare identifier or filename in backticks (`` `log()` ``, `` `foo.ts` ``) never matches. Never a URL (filtered by the caller). */
1509
+ const RATIONALE_PATH_RE_GLOBAL = /`([\w.@-]+(?:\/[\w.@-]+)+)`/g
1510
+
1511
+ /** How many leading `/`-separated segments two paths/globs share — the "nearest" ranking O4's message uses. A trailing `/**`/`/*` is stripped from the glob side first so `packages/aeg-core/**` compares as `packages/aeg-core`. */
1512
+ function sharedLeadingSegments(path: string, glob: string): number {
1513
+ const pathSegs = path.split('/')
1514
+ const globSegs = glob.replace(/\/\*\*?$/, '').split('/')
1515
+ let n = 0
1516
+ while (n < pathSegs.length && n < globSegs.length && pathSegs[n] === globSegs[n]) n++
1517
+ return n
1518
+ }
1519
+
1520
+ /** The `in:` glob sharing the most leading path segments with `path` — ties broken by first occurrence. `inGlobs` is never empty when called (a well-formed `## Surface` always parses at least one `in:` glob). */
1521
+ function nearestInGlob(path: string, inGlobs: string[]): string {
1522
+ let best = inGlobs[0] as string
1523
+ let bestScore = -1
1524
+ for (const glob of inGlobs) {
1525
+ const score = sharedLeadingSegments(path, glob)
1526
+ if (score > bestScore) {
1527
+ bestScore = score
1528
+ best = glob
1529
+ }
1530
+ }
1531
+ return best
1532
+ }
1533
+
1534
+ /**
1535
+ * **O4 — a Boundary path must fall inside the task's
1536
+ * own declared Surface.** The Boundary field is where a Planner names what a
1537
+ * task touches (and, in the same breath, what it deliberately excludes —
1538
+ * `checkBlastRadiusScope`'s own doc comment records Boundary prose naming a
1539
+ * path precisely IN ORDER TO EXCLUDE it). A path Boundary names as touched
1540
+ * that no `in:` glob covers is a rationale/Surface disagreement the
1541
+ * Developer would otherwise discover only after Step 0; naming the nearest
1542
+ * `in:` entry (`nearestInGlob`) makes the fix — widen that glob, or correct
1543
+ * the path — obvious without a second round trip.
1544
+ *
1545
+ * A path covered by `out:` is not flagged: Boundary naming a path to
1546
+ * disclaim it (the negation case above) is legitimate and already accounted
1547
+ * for by the Surface's own `out:` declaration — refusing it here would
1548
+ * misread a negation as an omission, the exact failure mode
1549
+ * `checkBlastRadiusScope`'s O4 (a different, file-scoped check) moved off
1550
+ * prose-scanning to avoid.
1551
+ *
1552
+ * Scoped to the Boundary field only, not the whole Planner's rationale
1553
+ * section: "Docs to keep coherent"/"Traps to avoid" have their own,
1554
+ * deliberately narrower doc-pointer check (`checkDocsWithinSurface`, above)
1555
+ * that stopped enforcing `in:`-coverage for doc pointers specifically,
1556
+ * because nothing at PR time enforces it either and doing so produced an
1557
+ * unusably over-wide brief (see that function's own doc comment). Reusing
1558
+ * this net over those fields would silently re-introduce the regression that
1559
+ * decision undid; Boundary is where "what this task touches" is actually
1560
+ * declared.
1561
+ *
1562
+ * At or above `BRIEF_SECTIONS_SINCE_ISSUE` only — below it an Issue
1563
+ * legitimately carries no `## Surface` to compare against.
1564
+ */
1565
+ export function checkRationaleSurfaceCoverage(body: string, issueNumber: number | null): IssueSectionResult {
1566
+ if (issueNumber !== null && issueNumber < BRIEF_SECTIONS_SINCE_ISSUE) return { status: 'pass', errors: [] }
1567
+ const surface = parseIssueSurface(body)
1568
+ if (!surface.ok) return { status: 'pass', errors: [] }
1569
+
1570
+ const text = PATH_TEXT(body)
1571
+ const scope = rationaleFieldText(text, 'Boundary')
1572
+ const paths = [...new Set([...scope.matchAll(RATIONALE_PATH_RE_GLOBAL)].map((m) => m[1] as string))].filter(
1573
+ (p) => !/^https?:\/\//i.test(p)
1574
+ )
1575
+
1576
+ const errors: string[] = []
1577
+ for (const path of paths) {
1578
+ if (surface.value.in.some((g) => globCoversPath(g, path))) continue
1579
+ if (surface.value.out.some((g) => globCoversPath(g, path))) continue
1580
+ const nearest = nearestInGlob(path, surface.value.in)
1581
+ errors.push(
1582
+ `issue-validation Boundary: \`${path}\` is named in the Boundary rationale, but no \`## Surface\` \`in:\` glob covers it — nearest is \`${nearest}\`. Widen the Surface's \`in:\` list to cover it, or correct the path if it was mistyped.`
1583
+ )
1584
+ }
1585
+ return { status: errors.length > 0 ? 'fail' : 'pass', errors }
1586
+ }
1587
+
1588
+ /**
1589
+ * **O1/O2 — a task Issue's `## Surface` `out:` list must not exclude a
1590
+ * document `.vinaya/doc-owners` binds to a path the same Issue's `in:` list
1591
+ * covers.** A binding whose code-glob overlaps an `in:` glob (`globsOverlap`,
1592
+ * `derive-section7.ts` — the same matcher `deriveSection7` uses to relate
1593
+ * Surface globs to doc-owners bindings) commits this task to keeping its
1594
+ * pointer coherent; if that pointer also falls inside an `out:` glob
1595
+ * (`globCoversPath`, this module's own Surface-vs-path matcher —
1596
+ * `checkDocsWithinSurface` above uses the same one), the task cannot satisfy
1597
+ * both `doc-coverage` (C5) and `surface-scope` at once, and the
1598
+ * Developer discovers the contradiction only at the first commit. Refusing
1599
+ * here catches it at authoring time instead.
1600
+ *
1601
+ * No second glob matcher is introduced: `globsOverlap` and `globCoversPath`
1602
+ * are the two the product already has, reused verbatim.
1603
+ *
1604
+ * A URL pointer is never a repo path an `out:` glob could cover, so it is
1605
+ * skipped (`isUrlPointer`) — this gate is about the tree, not external docs.
1606
+ * Absence of a binding for any `in:` path, or a bound pointer that simply
1607
+ * isn't excluded, both pass: only an explicit `out:` exclusion of a
1608
+ * bound pointer is a contradiction.
1609
+ *
1610
+ * `docOwnersContent === null` (repo has no manifest) or a `## Surface` that
1611
+ * doesn't parse both pass trivially — nothing to compare, and
1612
+ * `checkIssueBriefSections` already reports a malformed Surface.
1613
+ */
1614
+ export function checkSurfaceExcludesBoundDoc(body: string, docOwnersContent: string | null): IssueSectionResult {
1615
+ if (docOwnersContent === null) return { status: 'pass', errors: [] }
1616
+ const surface = parseIssueSurface(body)
1617
+ if (!surface.ok) return { status: 'pass', errors: [] }
1618
+
1619
+ const { bindings } = parseDocOwners(docOwnersContent)
1620
+ if (bindings.length === 0) return { status: 'pass', errors: [] }
1621
+
1622
+ const errors: string[] = []
1623
+ for (const binding of bindings) {
1624
+ if (isUrlPointer(binding.pointer)) continue
1625
+ const inGlob = surface.value.in.find((g) => globsOverlap(binding.glob, g))
1626
+ if (!inGlob) continue
1627
+ const pointerPath = pointerToPath(binding.pointer)
1628
+ const outGlob = surface.value.out.find((g) => globCoversPath(g, pointerPath))
1629
+ if (!outGlob) continue
1630
+ errors.push(
1631
+ `issue-validation Surface: \`${inGlob}\` in \`## Surface\`'s \`in:\` list matches ${DOC_OWNERS_PATH}:${binding.lineNum} (glob \`${binding.glob}\` → ${binding.pointer}), but \`${outGlob}\` in \`## Surface\`'s \`out:\` list excludes ${binding.pointer} — this task's own surface cannot satisfy doc-coverage and surface-scope at once.`
1632
+ )
1633
+ }
1634
+ return { status: errors.length > 0 ? 'fail' : 'pass', errors }
1635
+ }
1636
+
697
1637
  /** One open task Issue, reduced to what the conflict-completeness warning needs. */
698
1638
  export type TaskIssueFacts = {
699
1639
  /** How the Issue is referred to in a `Conflicts-with` edge — its number, or its task id. */
@@ -703,10 +1643,28 @@ export type TaskIssueFacts = {
703
1643
  conflictsWith: string[]
704
1644
  }
705
1645
 
706
- /** True when either side's declared edges name the other — `#621`, `621` and `8` all count. */
707
- function edgesNameEachOther(a: TaskIssueFacts, b: TaskIssueFacts): boolean {
708
- const norm = (s: string) => s.replace(/^#/, '').trim()
709
- return a.conflictsWith.map(norm).includes(norm(b.ref)) || b.conflictsWith.map(norm).includes(norm(a.ref))
1646
+ /**
1647
+ * True when either side's declared edges name the other — `#NNN`, `NNN` and
1648
+ * a bare task id all count, and so does a slug-qualified edge (`<slug> #NNN`,
1649
+ * `<slug> NNN`): `splitSlugQualifiedEdge` (`@attalabs/aeg-forge-state`, the
1650
+ * same split the dispatch gate's own edge resolver uses) reduces it to its
1651
+ * bare id first, one direction only — a bare id is never treated as
1652
+ * naming a qualified one back. Structural on `{ ref, conflictsWith }` so
1653
+ * both `TaskIssueFacts` and `TaskSurfaceFacts` satisfy it without a cast.
1654
+ */
1655
+ function normalizeEdgeId(s: string): string {
1656
+ const qualified = splitSlugQualifiedEdge(s)
1657
+ return (qualified ? qualified.bareId : s).replace(/^#/, '').trim()
1658
+ }
1659
+
1660
+ export function edgesNameEachOther(
1661
+ a: { ref: string; conflictsWith: string[] },
1662
+ b: { ref: string; conflictsWith: string[] }
1663
+ ): boolean {
1664
+ return (
1665
+ a.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(b.ref)) ||
1666
+ b.conflictsWith.map(normalizeEdgeId).includes(normalizeEdgeId(a.ref))
1667
+ )
710
1668
  }
711
1669
 
712
1670
  /**
@@ -744,3 +1702,462 @@ export function checkConflictCompleteness(
744
1702
  }
745
1703
  return warnings
746
1704
  }
1705
+
1706
+ // ---------------------------------------------------------------------------
1707
+ // O5 — cross-task Surface overlap. Same shape as
1708
+ // `checkConflictCompleteness` above (a subject checked against sibling task
1709
+ // Issues, `edgesNameEachOther` the same mutual-declaration bypass), but a
1710
+ // HARD refusal rather than a warning: `## Surface` `in:` is a structured,
1711
+ // declared fact (the same authority `checkSurfaceGlobsResolve`/`renderBrief`
1712
+ // already treat it as), not a prose heuristic, so a genuine overlap here is
1713
+ // not a hint — it is two Developers about to dispatch onto the same files
1714
+ // with neither task declared as blocking the other.
1715
+ // ---------------------------------------------------------------------------
1716
+
1717
+ /** One open task Issue, reduced to what O5's cross-task Surface-overlap check needs. */
1718
+ export type TaskSurfaceFacts = {
1719
+ /** How the Issue is referred to in a `Conflicts-with`/`Depends-on` edge — its number, or its task id (mirrors `TaskIssueFacts.ref`). */
1720
+ ref: string
1721
+ /** `## Surface` `in:` globs (`parseIssueSurface`) — `[]` when the Issue carries no parseable Surface (nothing to overlap). */
1722
+ surfaceIn: string[]
1723
+ /** Already-parsed `Conflicts-with` ids (`parseRationaleDeps`). */
1724
+ conflictsWith: string[]
1725
+ /** Already-parsed `Depends-on` ids (`parseRationaleDeps`) — issue-657 O2's serialization exemption. */
1726
+ dependsOn: string[]
1727
+ }
1728
+
1729
+ /**
1730
+ * **O5 — two open task Issues in the same Milestone whose declared
1731
+ * `## Surface` `in:` lists overlap, and that do not name each other in
1732
+ * `Conflicts-with`, are refused.** `globsOverlap` (`derive-section7.ts`) is
1733
+ * the same symmetric glob-overlap test `checkSurfaceExcludesBoundDoc` already
1734
+ * uses for a different glob pair (a Surface glob against a doc-owners
1735
+ * binding glob) — reused here for two tasks' Surface glob lists, never a
1736
+ * second matcher. `edgesNameEachOther` exempts the pair as soon as EITHER
1737
+ * side names the other — the same one-sided-is-enough rule
1738
+ * `checkConflictCompleteness` already applies (there, as a warning bypass;
1739
+ * here, as the sanctioned exemption): the edge only needs to be declared
1740
+ * once for both tasks to serialize correctly against it.
1741
+ *
1742
+ * Pure over its inputs — `siblings` is resolved by the caller (the
1743
+ * write-time gate in `apps/cli`'s `forge-write.ts` resolves it from the live
1744
+ * forge, scoped to the subject's own Milestone; the coherence sweep in
1745
+ * `coherence-checks.ts` resolves it from its own already-fetched Issue set)
1746
+ * — one predicate, shared rather than reimplemented at each call site, so
1747
+ * the write-time gate and the coherence sweep can never disagree about what
1748
+ * counts as an overlap.
1749
+ */
1750
+ /**
1751
+ * task 17, O4 — a glob shared by construction is never a real conflict:
1752
+ * every path segment of it is inspected for a literal `tests`/`specs`
1753
+ * directory name (`apps/cli/tests/**`, `packages/aeg-core/tests/**`,
1754
+ * `specs/**` all match; `apps/testsuite/**` does not — segment equality,
1755
+ * never a substring test), and separately, a glob every open task in the
1756
+ * Milestone (the subject plus the FULL sibling set the caller resolved) also
1757
+ * declares VERBATIM is exempt outright: a shared test tree, or a glob the
1758
+ * whole cohort was deliberately given in common, was never two tasks racing
1759
+ * onto the same files by accident.
1760
+ *
1761
+ * The second check is EXACT-STRING membership, never `globsOverlap` — a
1762
+ * fuzzy overlap test here would be circular (two genuinely conflicting
1763
+ * globs overlap each other BY DEFINITION, so "every cohort member declares
1764
+ * some glob that overlaps mine" is trivially true for exactly the pairs this
1765
+ * function exists to still catch). It also requires a real "every task in
1766
+ * the MILESTONE" cohort — at least two siblings, three tasks total: a bare
1767
+ * pairwise duplicate (two tasks, the same single glob, nothing else) is the
1768
+ * exact accidental-full-overlap shape this check exists to catch, not a
1769
+ * cohort-wide convention to exempt.
1770
+ */
1771
+ function isSharedByConstruction(glob: string, subject: TaskSurfaceFacts, siblings: TaskSurfaceFacts[]): boolean {
1772
+ if (glob.split('/').some((segment) => segment === 'tests' || segment === 'specs')) return true
1773
+ if (siblings.length < 2) return false
1774
+ const cohort = [subject, ...siblings]
1775
+ return cohort.every((entry) => entry.surfaceIn.includes(glob))
1776
+ }
1777
+
1778
+ /**
1779
+ * issue-657, O2 — two tasks sharing a Milestone can never run at the same
1780
+ * time when one depends on the other, directly or through a chain of
1781
+ * `Depends-on` edges: A depends on B and B depends on A are both
1782
+ * serialization (the direction is never load-bearing here, only that an
1783
+ * edge exists), and a chain A -> B -> C serializes A and C too even though
1784
+ * neither names the other directly. Union-find-by-BFS over the `dependsOn`
1785
+ * edges of `group` (the subject plus every sibling the caller resolved,
1786
+ * i.e. the same Milestone cohort `checkSurfaceOverlap` already scopes to —
1787
+ * the closure never reaches past that set because `group` never contains
1788
+ * anything outside it).
1789
+ */
1790
+ function dependencyChainSerializes(subjectRef: string, siblingRef: string, group: TaskSurfaceFacts[]): boolean {
1791
+ const target = normalizeEdgeId(siblingRef)
1792
+ const adjacency = new Map<string, Set<string>>()
1793
+ const link = (a: string, b: string) => {
1794
+ if (!adjacency.has(a)) adjacency.set(a, new Set())
1795
+ adjacency.get(a)?.add(b)
1796
+ }
1797
+ for (const entry of group) {
1798
+ const ref = normalizeEdgeId(entry.ref)
1799
+ for (const dep of entry.dependsOn) {
1800
+ const depRef = normalizeEdgeId(dep)
1801
+ link(ref, depRef)
1802
+ link(depRef, ref)
1803
+ }
1804
+ }
1805
+
1806
+ const start = normalizeEdgeId(subjectRef)
1807
+ const seen = new Set<string>([start])
1808
+ const queue: string[] = [start]
1809
+ while (queue.length > 0) {
1810
+ const current = queue.shift() as string
1811
+ if (current === target) return true
1812
+ for (const next of adjacency.get(current) ?? []) {
1813
+ if (seen.has(next)) continue
1814
+ seen.add(next)
1815
+ queue.push(next)
1816
+ }
1817
+ }
1818
+ return false
1819
+ }
1820
+
1821
+ export function checkSurfaceOverlap(subject: TaskSurfaceFacts, siblings: TaskSurfaceFacts[]): IssueSectionResult {
1822
+ const errors: string[] = []
1823
+ const group = [subject, ...siblings]
1824
+ for (const sibling of siblings) {
1825
+ if (sibling.ref === subject.ref) continue
1826
+ if (edgesNameEachOther(subject, sibling)) continue
1827
+ if (dependencyChainSerializes(subject.ref, sibling.ref, group)) continue
1828
+ for (const mine of subject.surfaceIn) {
1829
+ if (isSharedByConstruction(mine, subject, siblings)) continue
1830
+ for (const theirs of sibling.surfaceIn) {
1831
+ if (globsOverlap(mine, theirs)) {
1832
+ errors.push(
1833
+ `issue-validation Surface overlap: this task's \`## Surface\` \`in:\` glob \`${mine}\` overlaps ${sibling.ref}'s \`in:\` glob \`${theirs}\` — both are open task Issues in the same Milestone and neither names the other in \`Conflicts-with\`.`
1834
+ )
1835
+ }
1836
+ }
1837
+ }
1838
+ }
1839
+ return { status: errors.length > 0 ? 'fail' : 'pass', errors }
1840
+ }
1841
+
1842
+ // ---------------------------------------------------------------------------
1843
+ // Three predicates closing the gap between what a task Issue's
1844
+ // Objectives/Parts/Test-plan lines CLAIM and what its own Boundary/Surface
1845
+ // `out:` and rationale actually authorize. Wired into `apps/cli`'s
1846
+ // `validateIssueContent` (the pre-write brief-render gate) and into
1847
+ // `open-issue.ts`'s content gate — never a second copy of either.
1848
+ // ---------------------------------------------------------------------------
1849
+
1850
+ /**
1851
+ * The Boundary field's own `Out:` sub-clause — everything from its `Out:`
1852
+ * marker to the field's end. Scanned separately from the field's `In:` half:
1853
+ * a path Boundary names under `In:` is a legitimate touch-claim (exactly
1854
+ * what `checkRationaleSurfaceCoverage`'s O4 already grades against
1855
+ * `## Surface`'s `in:` list), never an exclusion, and must never trip this
1856
+ * rule.
1857
+ */
1858
+ const BOUNDARY_OUT_RE = /\bOut\s*:\s*([\s\S]*)$/im
1859
+
1860
+ function boundaryOutText(body: string): string {
1861
+ const boundary = rationaleFieldText(PATH_TEXT(body), 'Boundary')
1862
+ const m = BOUNDARY_OUT_RE.exec(boundary)
1863
+ return m ? (m[1] as string) : ''
1864
+ }
1865
+
1866
+ /** Every backticked, `/`-shaped repo-path token in `text` — the same token shape `checkRationaleSurfaceCoverage` reads out of Boundary, reused rather than a second matcher. Never a URL. */
1867
+ function namedPathsIn(text: string): string[] {
1868
+ return [...new Set([...text.matchAll(RATIONALE_PATH_RE_GLOBAL)].map((m) => m[1] as string))].filter(
1869
+ (p) => !/^https?:\/\//i.test(p)
1870
+ )
1871
+ }
1872
+
1873
+ /** A bare (unbackticked), `/`-shaped repo-path token — at least two `/`-separated segments, same shape as `RATIONALE_PATH_RE_GLOBAL`'s capture, minus the backtick requirement. */
1874
+ const BARE_PATH_RE_GLOBAL = /\b[\w.@-]+(?:\/[\w.@-]+)+\b/g
1875
+
1876
+ /**
1877
+ * Every path-shaped token in a Test plan COMMAND line — never backtick-only:
1878
+ * a fenced `[agent]` command list is already inside a code block, so its own
1879
+ * paths are written bare (`bun test apps/cli/tests`), not re-wrapped in
1880
+ * backticks. Prose fields (Objectives/Parts) keep the backtick-only
1881
+ * `namedPathsIn` above — a bare two-segment slash token in ordinary prose
1882
+ * ("either/or") is not a path claim, but inside a command line it always is.
1883
+ */
1884
+ function namedPathsInCommandLine(text: string): string[] {
1885
+ return [...new Set([...text.matchAll(BARE_PATH_RE_GLOBAL)].map((m) => m[0]))].filter((p) => !/^https?:\/\//i.test(p))
1886
+ }
1887
+
1888
+ /**
1889
+ * **The Boundary and the Objectives agree by construction.** An objective,
1890
+ * a Part, or a Test plan line that names a
1891
+ * file, directory, package, or subsystem the Boundary's `Out:` clause or the
1892
+ * Surface's `out:` list names is refused, quoting both the offending line
1893
+ * and the excluding one — this task cannot both disclaim a path and require
1894
+ * work inside it in the same breath.
1895
+ *
1896
+ * `excludes` checks the Surface's own `out:` globs first (`globCoversPath`,
1897
+ * this module's Surface-vs-path matcher, reused verbatim) and falls back to
1898
+ * a backticked path named in the Boundary's `Out:` sub-clause — two sources
1899
+ * of "excluded", never two matchers.
1900
+ */
1901
+ export function checkObjectivesRespectBoundary(body: string): IssueSectionResult {
1902
+ const surface = parseIssueSurface(body)
1903
+ const outGlobs = surface.ok ? surface.value.out : []
1904
+ const boundaryOutPaths = namedPathsIn(boundaryOutText(body))
1905
+ if (outGlobs.length === 0 && boundaryOutPaths.length === 0) return { status: 'pass', errors: [] }
1906
+
1907
+ const excludes = (path: string): string | null => {
1908
+ const glob = outGlobs.find((g) => globCoversPath(g, path))
1909
+ if (glob) return `the Surface's \`out:\` glob \`${glob}\``
1910
+ const boundaryPath = boundaryOutPaths.find((p) => globCoversPath(p, path))
1911
+ return boundaryPath ? `the Boundary's \`Out:\` clause naming \`${boundaryPath}\`` : null
1912
+ }
1913
+
1914
+ const errors: string[] = []
1915
+
1916
+ const objectives = objectivesOf(body)
1917
+ if (objectives.ok) {
1918
+ for (const o of objectives.objectives) {
1919
+ for (const path of namedPathsIn(o.text)) {
1920
+ const excluder = excludes(path)
1921
+ if (excluder) {
1922
+ errors.push(
1923
+ `issue-validation Objectives/Boundary: ${o.id} ("${o.text}") names \`${path}\`, which ${excluder} excludes.`
1924
+ )
1925
+ }
1926
+ }
1927
+ }
1928
+ }
1929
+
1930
+ const parts = parseIssueParts(body)
1931
+ if (parts.ok) {
1932
+ for (const part of parts.value) {
1933
+ for (const path of namedPathsIn(part.text)) {
1934
+ const excluder = excludes(path)
1935
+ if (excluder) {
1936
+ errors.push(
1937
+ `issue-validation Parts/Boundary: Part ${part.n} ("${part.text}") names \`${path}\`, which ${excluder} excludes.`
1938
+ )
1939
+ }
1940
+ }
1941
+ }
1942
+ }
1943
+
1944
+ const testPlan = parseIssueTestPlan(body)
1945
+ if (testPlan.ok && testPlan.value.kind === 'commands') {
1946
+ for (const line of [...testPlan.value.lines, ...testPlan.value.principal]) {
1947
+ for (const path of namedPathsInCommandLine(line)) {
1948
+ const excluder = excludes(path)
1949
+ if (excluder) {
1950
+ errors.push(`issue-validation Test plan/Boundary: "${line}" names \`${path}\`, which ${excluder} excludes.`)
1951
+ }
1952
+ }
1953
+ }
1954
+ }
1955
+
1956
+ return { status: errors.length > 0 ? 'fail' : 'pass', errors }
1957
+ }
1958
+
1959
+ /**
1960
+ * **The rationale belongs to this task.** A Traps, Stop-and-escalate, or
1961
+ * Boundary sentence that names another task's slug-and-number as the OWNER
1962
+ * of work this task's own objectives require is refused. Scoped to those
1963
+ * three fields only — `Dependency rationale` is where a task reference
1964
+ * legitimately belongs (ordering, never ownership), so scanning it here
1965
+ * would misread every `Depends-on`/`Conflicts-with` line as a violation.
1966
+ *
1967
+ * "Assigns ownership" is a lexical heuristic, same posture as
1968
+ * `BLAST_RADIUS_ACK_RE`/`NO_DOC_SURFACE_RE` elsewhere in this module: an
1969
+ * ownership-shaped verb phrase in the same sentence as a task reference
1970
+ * (`#<n>`, or the `<slug> <n>` shape `Dependency rationale`'s own edges
1971
+ * already use). Merely MENTIONING another task trips nothing — a Traps
1972
+ * sentence that names a primitive another task ships (e.g. "call the
1973
+ * primitive the dependency ships") carries a task reference with no
1974
+ * ownership verb anywhere near it, and stays green.
1975
+ */
1976
+ const OWNERSHIP_VERB_RE =
1977
+ /\b(?:is\s+owned\s+by|owned\s+by|owns|is\s+handled\s+by|handled\s+by|is\s+done\s+by|done\s+by|is\s+implemented\s+by|implemented\s+by|is\s+delivered\s+by|delivered\s+by|is\s+(?:the\s+)?responsibility\s+of|is\s+left\s+to|left\s+to|is\s+deferred\s+to|deferred\s+to|belongs\s+to)\b/i
1978
+ const TASK_REF_RE = /#\d+|\b[a-z][a-z0-9]*(?:-[a-z0-9]+)*-v\d+\s+\d+\b/i
1979
+ const SENTENCE_RE = /[^.\n]+[.\n]?/g
1980
+
1981
+ export function checkNoForeignTaskOwnership(body: string): IssueSectionResult {
1982
+ const text = PATH_TEXT(body)
1983
+ const fields: Array<[string, string]> = [
1984
+ ['Traps to avoid', rationaleFieldText(text, 'Traps')],
1985
+ ['Stop-and-escalate', rationaleFieldText(text, 'Stop-and-escalate')],
1986
+ ['Boundary', rationaleFieldText(text, 'Boundary')]
1987
+ ]
1988
+ const errors: string[] = []
1989
+ for (const [name, fieldText] of fields) {
1990
+ if (!fieldText) continue
1991
+ for (const match of fieldText.match(SENTENCE_RE) ?? []) {
1992
+ const sentence = match.trim()
1993
+ if (sentence.length === 0) continue
1994
+ if (OWNERSHIP_VERB_RE.test(sentence) && TASK_REF_RE.test(sentence)) {
1995
+ errors.push(
1996
+ `issue-validation ${name}: "${sentence}" assigns ownership of work to another task — the rationale belongs to THIS task; depend on the other task instead (\`Dependency rationale\`), or fold the work back into this task's own Objectives/Parts.`
1997
+ )
1998
+ }
1999
+ }
2000
+ }
2001
+ return { status: errors.length > 0 ? 'fail' : 'pass', errors }
2002
+ }
2003
+
2004
+ /**
2005
+ * **Parts and Objectives agree by construction, the other half.** A Part
2006
+ * citing an objective `## Objectives` does not define is already refused by
2007
+ * `checkPartsCiteDefinedObjectives`, above; this predicate closes the other
2008
+ * two defects: an objective no Part cites at all, and Parts numbered out of
2009
+ * sequence (not contiguous from 1, in document order).
2010
+ *
2011
+ * Passes trivially when either section fails to parse — `parseIssueParts`/
2012
+ * `objectivesOf`'s own callers already report a malformed section; this
2013
+ * predicate only grades an otherwise well-formed pair.
2014
+ *
2015
+ * The sequence check stops at the first divergence rather than reporting
2016
+ * every downstream index (unlike this module's usual "every violation, not
2017
+ * only the first" convention): one wrong Part number cascades into every
2018
+ * later index also failing "equals its own position", which is one root
2019
+ * cause, not several independent ones — reporting all of them would just be
2020
+ * noise around the single number that needs fixing.
2021
+ */
2022
+ export function checkPartsCoverageAndSequence(body: string): IssueSectionResult {
2023
+ const parts = parseIssueParts(body)
2024
+ const objectives = objectivesOf(body)
2025
+ if (!parts.ok || !objectives.ok) return { status: 'pass', errors: [] }
2026
+
2027
+ const errors: string[] = []
2028
+
2029
+ const citedIds = new Set(parts.value.flatMap((p) => p.objectiveIds))
2030
+ for (const o of objectives.objectives) {
2031
+ const id = Number.parseInt(o.id.slice(1), 10)
2032
+ if (!citedIds.has(id)) {
2033
+ errors.push(
2034
+ `issue-validation Parts coverage: ${o.id} ("${o.text}") is not cited by any \`## Parts\` line — every objective must be cited by at least one Part.`
2035
+ )
2036
+ }
2037
+ }
2038
+
2039
+ const numbers = parts.value.map((p) => p.n)
2040
+ for (let i = 0; i < numbers.length; i++) {
2041
+ const expected = i + 1
2042
+ if (numbers[i] !== expected) {
2043
+ errors.push(
2044
+ `issue-validation Parts sequence: \`## Parts\` line ${i + 1} is numbered Part ${numbers[i]}, expected Part ${expected} — Parts must be numbered contiguously from 1, in document order.`
2045
+ )
2046
+ break
2047
+ }
2048
+ }
2049
+
2050
+ return { status: errors.length > 0 ? 'fail' : 'pass', errors }
2051
+ }
2052
+
2053
+ // ---------------------------------------------------------------------------
2054
+ // O3 — an edit that changes
2055
+ // `## Objectives`, `## Surface`, or `## Parts` on a task Issue whose brief is
2056
+ // already frozen is refused. Design: compare the LIVE Issue body before and
2057
+ // after the edit (never the frozen comment's own rendered text — the brief
2058
+ // render is lossy for `## Surface`'s `in:` glob list and interleaves
2059
+ // `## Parts` with computed file groupings, so it cannot serve as the
2060
+ // comparison target). The frozen
2061
+ // comment's existence is the gate condition and is named in the refusal
2062
+ // message; the pre-edit live body is the comparison basis.
2063
+ // ---------------------------------------------------------------------------
2064
+
2065
+ export type FrozenSection = 'Objectives' | 'Surface' | 'Parts' | 'Documentation'
2066
+
2067
+ /** True when two `## Surface` sections carry the same `in:`/`out:` glob sets, order-insensitive. */
2068
+ function surfacesEqual(a: IssueSurface, b: IssueSurface): boolean {
2069
+ const norm = (globs: string[]) => [...globs].sort().join(' ')
2070
+ return norm(a.in) === norm(b.in) && norm(a.out) === norm(b.out)
2071
+ }
2072
+
2073
+ /**
2074
+ * True when two `## Documentation` sections carry the same sources, in the
2075
+ * same order (a round-2 HIGH security-review finding) — order-significant
2076
+ * like `## Parts`, since a source's own position has no independent meaning
2077
+ * to render but a reordering is still an edit a Planner made, not a no-op.
2078
+ * `{ kind: 'none' }` only ever equals another `{ kind: 'none' }`.
2079
+ */
2080
+ function documentationEqual(a: IssueDocumentation, b: IssueDocumentation): boolean {
2081
+ if (a.kind !== b.kind) return false
2082
+ if (a.kind === 'none') return true
2083
+ const bSources = (b as { kind: 'sources'; sources: IssueDocumentationSource[] }).sources
2084
+ if (a.sources.length !== bSources.length) return false
2085
+ return a.sources.every((s, i) => {
2086
+ const t = bSources[i] as IssueDocumentationSource
2087
+ return (
2088
+ s.source === t.source &&
2089
+ s.mechanism === t.mechanism &&
2090
+ s.objectiveIds.length === t.objectiveIds.length &&
2091
+ s.objectiveIds.every((id, j) => id === t.objectiveIds[j])
2092
+ )
2093
+ })
2094
+ }
2095
+
2096
+ /** True when two `## Parts` lists carry the same `{n, objectiveIds, text}` tuples, in the same order — a Part's own order is significant (it drives §6's rendering), unlike a Surface glob set. */
2097
+ function partsEqual(a: IssuePart[], b: IssuePart[]): boolean {
2098
+ if (a.length !== b.length) return false
2099
+ return a.every((p, i) => {
2100
+ const q = b[i] as IssuePart
2101
+ return (
2102
+ p.n === q.n &&
2103
+ p.text === q.text &&
2104
+ p.objectiveIds.length === q.objectiveIds.length &&
2105
+ p.objectiveIds.every((id, j) => id === q.objectiveIds[j])
2106
+ )
2107
+ })
2108
+ }
2109
+
2110
+ /**
2111
+ * **O3 — which of `## Objectives`/`## Surface`/`## Parts` changed between
2112
+ * `oldBody` and `newBody`.** Pure comparison; the caller decides whether the
2113
+ * Issue's brief is actually frozen (this function runs unconditionally, the
2114
+ * gate is applying it only when a frozen comment exists) and builds the
2115
+ * refusal message (naming the frozen comment and `issue objectives edit`).
2116
+ *
2117
+ * A section that fails to parse on ONE side but not the other counts as
2118
+ * changed (a well-formed section that stopped parsing, or vice versa, is
2119
+ * exactly a change this gate exists to catch). A section that fails to parse
2120
+ * on BOTH sides is not reported here — that Issue predates a cutover or is
2121
+ * otherwise malformed on its own terms, a fact `checkIssueObjectives`/
2122
+ * `checkIssueBriefSections` already report; this function only compares
2123
+ * shapes it can actually read on both sides.
2124
+ */
2125
+ export function frozenSectionsChanged(oldBody: string, newBody: string): FrozenSection[] {
2126
+ const changed: FrozenSection[] = []
2127
+
2128
+ const oldObjectives = objectivesOf(oldBody)
2129
+ const newObjectives = objectivesOf(newBody)
2130
+ if (oldObjectives.ok && newObjectives.ok) {
2131
+ if (objectivesVersion(oldObjectives.objectives) !== objectivesVersion(newObjectives.objectives)) {
2132
+ changed.push('Objectives')
2133
+ }
2134
+ } else if (oldObjectives.ok !== newObjectives.ok) {
2135
+ changed.push('Objectives')
2136
+ }
2137
+
2138
+ const oldSurface = parseIssueSurface(oldBody)
2139
+ const newSurface = parseIssueSurface(newBody)
2140
+ if (oldSurface.ok && newSurface.ok) {
2141
+ if (!surfacesEqual(oldSurface.value, newSurface.value)) changed.push('Surface')
2142
+ } else if (oldSurface.ok !== newSurface.ok) {
2143
+ changed.push('Surface')
2144
+ }
2145
+
2146
+ const oldParts = parseIssueParts(oldBody)
2147
+ const newParts = parseIssueParts(newBody)
2148
+ if (oldParts.ok && newParts.ok) {
2149
+ if (!partsEqual(oldParts.value, newParts.value)) changed.push('Parts')
2150
+ } else if (oldParts.ok !== newParts.ok) {
2151
+ changed.push('Parts')
2152
+ }
2153
+
2154
+ const oldDocumentation = parseIssueDocumentation(oldBody)
2155
+ const newDocumentation = parseIssueDocumentation(newBody)
2156
+ if (oldDocumentation.ok && newDocumentation.ok) {
2157
+ if (!documentationEqual(oldDocumentation.value, newDocumentation.value)) changed.push('Documentation')
2158
+ } else if (oldDocumentation.ok !== newDocumentation.ok) {
2159
+ changed.push('Documentation')
2160
+ }
2161
+
2162
+ return changed
2163
+ }