@bonesofspring/ai-rules 0.2.41 → 0.2.43

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 (528) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/bin/lib/seed-ai-local-team.js +41 -4
  3. package/docs/LOCAL-OVERLAY.md +3 -1
  4. package/docs/specs/INDEX.md +3 -1
  5. package/docs/specs/_templates/feature.md +6 -0
  6. package/package.json +1 -1
  7. package/presets/_shared/ai-local/scripts/derive-gate-signals.mjs +7 -0
  8. package/presets/_shared/assets/docs-specs/_templates/feature.md +6 -0
  9. package/presets/_shared/core/agent-team/agent-artifact-contracts.md +1 -0
  10. package/presets/_shared/core/agent-team/agent-team-orchestrator.md +21 -5
  11. package/presets/_shared/core/agent-team/plan-graph.md +9 -1
  12. package/presets/_shared/core/quality/anti-hallucination-contract.md +2 -0
  13. package/presets/_shared/core/quality/context-and-iteration.md +2 -1
  14. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +1140 -7
  15. package/presets/claude/android-kotlin/agents/ci-investigator.md +1 -1
  16. package/presets/claude/android-kotlin/agents/debugger.md +1 -1
  17. package/presets/claude/android-kotlin/agents/feature-developer.md +1 -1
  18. package/presets/claude/android-kotlin/agents/migration-specialist.md +1 -1
  19. package/presets/claude/android-kotlin/agents/performance-auditor.md +1 -1
  20. package/presets/claude/android-kotlin/agents/qa-tester.md +1 -1
  21. package/presets/claude/android-kotlin/agents/task-analyst.md +1 -1
  22. package/presets/claude/android-kotlin/agents/task-router.md +1 -1
  23. package/presets/claude/android-kotlin/agents/tech-writer.md +1 -1
  24. package/presets/claude/android-kotlin/agents/unit-test-generator.md +1 -1
  25. package/presets/claude/android-kotlin/agents/unit-test-healer.md +1 -1
  26. package/presets/claude/android-kotlin/agents/unit-test-planner.md +1 -1
  27. package/presets/claude/android-kotlin/commands/task-continue.md +1 -1
  28. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +1140 -7
  29. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
  30. package/presets/claude/android-kotlin/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  31. package/presets/claude/android-kotlin/team/README.md +1 -1
  32. package/presets/claude/go/agents/feature-developer.md +1 -1
  33. package/presets/claude/go/agents/task-analyst.md +1 -1
  34. package/presets/claude/go/agents/task-router.md +1 -1
  35. package/presets/claude/go/commands/task-continue.md +1 -1
  36. package/presets/claude/go/hooks/chain-team-phases.sh +1140 -7
  37. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
  38. package/presets/claude/go/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  39. package/presets/claude/go/team/README.md +1 -1
  40. package/presets/claude/ios-swift/agents/feature-developer.md +1 -1
  41. package/presets/claude/ios-swift/agents/task-analyst.md +1 -1
  42. package/presets/claude/ios-swift/agents/task-router.md +1 -1
  43. package/presets/claude/ios-swift/commands/task-continue.md +1 -1
  44. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +1140 -7
  45. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
  46. package/presets/claude/ios-swift/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  47. package/presets/claude/ios-swift/team/README.md +1 -1
  48. package/presets/claude/java/agents/feature-developer.md +1 -1
  49. package/presets/claude/java/agents/task-analyst.md +1 -1
  50. package/presets/claude/java/agents/task-router.md +1 -1
  51. package/presets/claude/java/commands/task-continue.md +1 -1
  52. package/presets/claude/java/hooks/chain-team-phases.sh +1140 -7
  53. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
  54. package/presets/claude/java/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  55. package/presets/claude/java/team/README.md +1 -1
  56. package/presets/claude/mcp-ts/agents/feature-developer.md +1 -1
  57. package/presets/claude/mcp-ts/agents/task-analyst.md +1 -1
  58. package/presets/claude/mcp-ts/agents/task-router.md +1 -1
  59. package/presets/claude/mcp-ts/commands/task-continue.md +1 -1
  60. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +1140 -7
  61. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
  62. package/presets/claude/mcp-ts/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  63. package/presets/claude/mcp-ts/team/README.md +1 -1
  64. package/presets/claude/next/REPO_AGENTS.md +1 -1
  65. package/presets/claude/next/agents/ci-investigator.md +1 -1
  66. package/presets/claude/next/agents/debugger.md +1 -1
  67. package/presets/claude/next/agents/feature-developer.md +1 -1
  68. package/presets/claude/next/agents/migration-specialist.md +1 -1
  69. package/presets/claude/next/agents/openspec-author.md +26 -2
  70. package/presets/claude/next/agents/performance-auditor.md +1 -1
  71. package/presets/claude/next/agents/qa-tester.md +1 -1
  72. package/presets/claude/next/agents/solution-architect.md +1 -1
  73. package/presets/claude/next/agents/task-analyst.md +16 -7
  74. package/presets/claude/next/agents/task-router.md +21 -3
  75. package/presets/claude/next/agents/tech-writer.md +1 -1
  76. package/presets/claude/next/agents/unit-test-generator.md +1 -1
  77. package/presets/claude/next/agents/unit-test-healer.md +1 -1
  78. package/presets/claude/next/agents/unit-test-planner.md +1 -1
  79. package/presets/{cursor/next/ai-local/rules-library → claude/next/ai-local/rules}/task-levels.md +2 -0
  80. package/presets/claude/next/commands/task-continue.md +1 -1
  81. package/presets/claude/next/hooks/chain-team-phases.sh +1140 -7
  82. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
  83. package/presets/claude/next/rules/tooling-and-review/ai-local-overlay.md +1 -1
  84. package/presets/claude/next/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  85. package/presets/claude/next/team/README.md +1 -1
  86. package/presets/claude/nuxt/agents/README.md +1 -1
  87. package/presets/claude/nuxt/agents/ci-investigator.md +1 -1
  88. package/presets/claude/nuxt/agents/debugger.md +1 -1
  89. package/presets/claude/nuxt/agents/feature-developer.md +1 -1
  90. package/presets/claude/nuxt/agents/migration-specialist.md +1 -1
  91. package/presets/claude/nuxt/agents/performance-auditor.md +1 -1
  92. package/presets/claude/nuxt/agents/qa-tester.md +1 -1
  93. package/presets/claude/nuxt/agents/solution-architect.md +1 -1
  94. package/presets/claude/nuxt/agents/task-analyst.md +1 -1
  95. package/presets/claude/nuxt/agents/task-router.md +1 -1
  96. package/presets/claude/nuxt/agents/tech-writer.md +1 -1
  97. package/presets/claude/nuxt/agents/unit-test-generator.md +1 -1
  98. package/presets/claude/nuxt/agents/unit-test-healer.md +1 -1
  99. package/presets/claude/nuxt/agents/unit-test-planner.md +1 -1
  100. package/presets/claude/nuxt/commands/task-continue.md +1 -1
  101. package/presets/claude/nuxt/hooks/chain-team-phases.sh +1140 -7
  102. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
  103. package/presets/claude/nuxt/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  104. package/presets/claude/nuxt/team/README.md +1 -1
  105. package/presets/claude/php-hexagonal/agents/feature-developer.md +1 -1
  106. package/presets/claude/php-hexagonal/agents/task-analyst.md +1 -1
  107. package/presets/claude/php-hexagonal/agents/task-router.md +1 -1
  108. package/presets/claude/php-hexagonal/commands/task-continue.md +1 -1
  109. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +1140 -7
  110. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
  111. package/presets/claude/php-hexagonal/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  112. package/presets/claude/php-hexagonal/team/README.md +1 -1
  113. package/presets/claude/php-laravel/agents/feature-developer.md +1 -1
  114. package/presets/claude/php-laravel/agents/task-analyst.md +1 -1
  115. package/presets/claude/php-laravel/agents/task-router.md +1 -1
  116. package/presets/claude/php-laravel/commands/task-continue.md +1 -1
  117. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +1140 -7
  118. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
  119. package/presets/claude/php-laravel/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  120. package/presets/claude/php-laravel/team/README.md +1 -1
  121. package/presets/claude/svelte/agents/README.md +1 -1
  122. package/presets/claude/svelte/agents/ci-investigator.md +1 -1
  123. package/presets/claude/svelte/agents/debugger.md +1 -1
  124. package/presets/claude/svelte/agents/feature-developer.md +1 -1
  125. package/presets/claude/svelte/agents/migration-specialist.md +1 -1
  126. package/presets/claude/svelte/agents/performance-auditor.md +1 -1
  127. package/presets/claude/svelte/agents/qa-tester.md +1 -1
  128. package/presets/claude/svelte/agents/solution-architect.md +1 -1
  129. package/presets/claude/svelte/agents/task-analyst.md +1 -1
  130. package/presets/claude/svelte/agents/task-router.md +1 -1
  131. package/presets/claude/svelte/agents/tech-writer.md +1 -1
  132. package/presets/claude/svelte/agents/unit-test-generator.md +1 -1
  133. package/presets/claude/svelte/agents/unit-test-healer.md +1 -1
  134. package/presets/claude/svelte/agents/unit-test-planner.md +1 -1
  135. package/presets/claude/svelte/commands/task-continue.md +1 -1
  136. package/presets/claude/svelte/hooks/chain-team-phases.sh +1140 -7
  137. package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
  138. package/presets/claude/svelte/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
  139. package/presets/claude/svelte/team/README.md +1 -1
  140. package/presets/cursor/android-kotlin/agents/ci-investigator.md +1 -1
  141. package/presets/cursor/android-kotlin/agents/debugger.md +1 -1
  142. package/presets/cursor/android-kotlin/agents/feature-developer.md +1 -1
  143. package/presets/cursor/android-kotlin/agents/migration-specialist.md +1 -1
  144. package/presets/cursor/android-kotlin/agents/performance-auditor.md +1 -1
  145. package/presets/cursor/android-kotlin/agents/qa-tester.md +1 -1
  146. package/presets/cursor/android-kotlin/agents/task-analyst.md +1 -1
  147. package/presets/cursor/android-kotlin/agents/task-router.md +1 -1
  148. package/presets/cursor/android-kotlin/agents/tech-writer.md +1 -1
  149. package/presets/cursor/android-kotlin/agents/unit-test-generator.md +1 -1
  150. package/presets/cursor/android-kotlin/agents/unit-test-healer.md +1 -1
  151. package/presets/cursor/android-kotlin/agents/unit-test-planner.md +1 -1
  152. package/presets/cursor/android-kotlin/commands/task-continue.md +1 -1
  153. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +1140 -7
  154. package/presets/cursor/android-kotlin/rules/anti-hallucination-contract.mdc +2 -0
  155. package/presets/cursor/android-kotlin/team/README.md +1 -1
  156. package/presets/cursor/go/agents/feature-developer.md +1 -1
  157. package/presets/cursor/go/agents/task-analyst.md +1 -1
  158. package/presets/cursor/go/agents/task-router.md +1 -1
  159. package/presets/cursor/go/commands/task-continue.md +1 -1
  160. package/presets/cursor/go/hooks/chain-team-phases.sh +1140 -7
  161. package/presets/cursor/go/rules/anti-hallucination-contract.mdc +2 -0
  162. package/presets/cursor/go/team/README.md +1 -1
  163. package/presets/cursor/ios-swift/agents/feature-developer.md +1 -1
  164. package/presets/cursor/ios-swift/agents/task-analyst.md +1 -1
  165. package/presets/cursor/ios-swift/agents/task-router.md +1 -1
  166. package/presets/cursor/ios-swift/commands/task-continue.md +1 -1
  167. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +1140 -7
  168. package/presets/cursor/ios-swift/rules/anti-hallucination-contract.mdc +2 -0
  169. package/presets/cursor/ios-swift/team/README.md +1 -1
  170. package/presets/cursor/java/agents/feature-developer.md +1 -1
  171. package/presets/cursor/java/agents/task-analyst.md +1 -1
  172. package/presets/cursor/java/agents/task-router.md +1 -1
  173. package/presets/cursor/java/commands/task-continue.md +1 -1
  174. package/presets/cursor/java/hooks/chain-team-phases.sh +1140 -7
  175. package/presets/cursor/java/rules/anti-hallucination-contract.mdc +2 -0
  176. package/presets/cursor/java/team/README.md +1 -1
  177. package/presets/cursor/mcp-ts/agents/feature-developer.md +1 -1
  178. package/presets/cursor/mcp-ts/agents/task-analyst.md +1 -1
  179. package/presets/cursor/mcp-ts/agents/task-router.md +1 -1
  180. package/presets/cursor/mcp-ts/commands/task-continue.md +1 -1
  181. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +1140 -7
  182. package/presets/cursor/mcp-ts/rules/anti-hallucination-contract.mdc +2 -0
  183. package/presets/cursor/mcp-ts/team/README.md +1 -1
  184. package/presets/cursor/next/REPO_AGENTS.md +1 -1
  185. package/presets/cursor/next/agents/README.md +1 -1
  186. package/presets/cursor/next/agents/build-verifier.md +2 -0
  187. package/presets/cursor/next/agents/ci-investigator.md +1 -1
  188. package/presets/cursor/next/agents/debugger.md +1 -1
  189. package/presets/cursor/next/agents/feature-developer.md +10 -1
  190. package/presets/cursor/next/agents/migration-specialist.md +1 -1
  191. package/presets/cursor/next/agents/openspec-author.md +26 -2
  192. package/presets/cursor/next/agents/performance-auditor.md +1 -1
  193. package/presets/cursor/next/agents/qa-tester.md +1 -1
  194. package/presets/cursor/next/agents/solution-architect.md +1 -1
  195. package/presets/cursor/next/agents/task-analyst.md +21 -7
  196. package/presets/cursor/next/agents/task-router.md +32 -3
  197. package/presets/cursor/next/agents/tech-writer.md +1 -1
  198. package/presets/cursor/next/agents/unit-test-generator.md +1 -1
  199. package/presets/cursor/next/agents/unit-test-healer.md +1 -1
  200. package/presets/cursor/next/agents/unit-test-planner.md +1 -1
  201. package/presets/cursor/next/ai-local/conventions.md +20 -0
  202. package/presets/{mavis/next/ai-local/rules-library → cursor/next/ai-local/rules}/task-levels.md +12 -0
  203. package/presets/cursor/next/commands/task-continue.md +1 -1
  204. package/presets/cursor/next/hooks/chain-team-phases.sh +1140 -7
  205. package/presets/cursor/next/rules/agent-team-orchestrator.mdc +18 -2
  206. package/presets/cursor/next/rules/ai-local-overlay.mdc +1 -1
  207. package/presets/cursor/next/rules/anti-hallucination-contract.mdc +2 -0
  208. package/presets/cursor/next/team/README.md +1 -1
  209. package/presets/cursor/nuxt/agents/README.md +1 -1
  210. package/presets/cursor/nuxt/agents/ci-investigator.md +1 -1
  211. package/presets/cursor/nuxt/agents/debugger.md +1 -1
  212. package/presets/cursor/nuxt/agents/feature-developer.md +1 -1
  213. package/presets/cursor/nuxt/agents/migration-specialist.md +1 -1
  214. package/presets/cursor/nuxt/agents/performance-auditor.md +1 -1
  215. package/presets/cursor/nuxt/agents/qa-tester.md +1 -1
  216. package/presets/cursor/nuxt/agents/solution-architect.md +1 -1
  217. package/presets/cursor/nuxt/agents/task-analyst.md +1 -1
  218. package/presets/cursor/nuxt/agents/task-router.md +1 -1
  219. package/presets/cursor/nuxt/agents/tech-writer.md +1 -1
  220. package/presets/cursor/nuxt/agents/unit-test-generator.md +1 -1
  221. package/presets/cursor/nuxt/agents/unit-test-healer.md +1 -1
  222. package/presets/cursor/nuxt/agents/unit-test-planner.md +1 -1
  223. package/presets/cursor/nuxt/commands/task-continue.md +1 -1
  224. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +1140 -7
  225. package/presets/cursor/nuxt/rules/anti-hallucination-contract.mdc +2 -0
  226. package/presets/cursor/nuxt/team/README.md +1 -1
  227. package/presets/cursor/php-hexagonal/agents/feature-developer.md +1 -1
  228. package/presets/cursor/php-hexagonal/agents/task-analyst.md +1 -1
  229. package/presets/cursor/php-hexagonal/agents/task-router.md +1 -1
  230. package/presets/cursor/php-hexagonal/commands/task-continue.md +1 -1
  231. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +1140 -7
  232. package/presets/cursor/php-hexagonal/rules/anti-hallucination-contract.mdc +2 -0
  233. package/presets/cursor/php-hexagonal/team/README.md +1 -1
  234. package/presets/cursor/php-laravel/agents/feature-developer.md +1 -1
  235. package/presets/cursor/php-laravel/agents/task-analyst.md +1 -1
  236. package/presets/cursor/php-laravel/agents/task-router.md +1 -1
  237. package/presets/cursor/php-laravel/commands/task-continue.md +1 -1
  238. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +1140 -7
  239. package/presets/cursor/php-laravel/rules/anti-hallucination-contract.mdc +2 -0
  240. package/presets/cursor/php-laravel/team/README.md +1 -1
  241. package/presets/cursor/svelte/agents/README.md +1 -1
  242. package/presets/cursor/svelte/agents/ci-investigator.md +1 -1
  243. package/presets/cursor/svelte/agents/debugger.md +1 -1
  244. package/presets/cursor/svelte/agents/feature-developer.md +1 -1
  245. package/presets/cursor/svelte/agents/migration-specialist.md +1 -1
  246. package/presets/cursor/svelte/agents/performance-auditor.md +1 -1
  247. package/presets/cursor/svelte/agents/qa-tester.md +1 -1
  248. package/presets/cursor/svelte/agents/solution-architect.md +1 -1
  249. package/presets/cursor/svelte/agents/task-analyst.md +1 -1
  250. package/presets/cursor/svelte/agents/task-router.md +1 -1
  251. package/presets/cursor/svelte/agents/tech-writer.md +1 -1
  252. package/presets/cursor/svelte/agents/unit-test-generator.md +1 -1
  253. package/presets/cursor/svelte/agents/unit-test-healer.md +1 -1
  254. package/presets/cursor/svelte/agents/unit-test-planner.md +1 -1
  255. package/presets/cursor/svelte/commands/task-continue.md +1 -1
  256. package/presets/cursor/svelte/hooks/chain-team-phases.sh +1140 -7
  257. package/presets/cursor/svelte/rules/anti-hallucination-contract.mdc +2 -0
  258. package/presets/cursor/svelte/team/README.md +1 -1
  259. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  260. package/presets/mavis/android-kotlin/agents/ci-investigator.md +1 -1
  261. package/presets/mavis/android-kotlin/agents/debugger.md +1 -1
  262. package/presets/mavis/android-kotlin/agents/feature-developer.md +1 -1
  263. package/presets/mavis/android-kotlin/agents/migration-specialist.md +1 -1
  264. package/presets/mavis/android-kotlin/agents/performance-auditor.md +1 -1
  265. package/presets/mavis/android-kotlin/agents/qa-tester.md +1 -1
  266. package/presets/mavis/android-kotlin/agents/task-analyst.md +1 -1
  267. package/presets/mavis/android-kotlin/agents/task-router.md +1 -1
  268. package/presets/mavis/android-kotlin/agents/tech-writer.md +1 -1
  269. package/presets/mavis/android-kotlin/agents/unit-test-generator.md +1 -1
  270. package/presets/mavis/android-kotlin/agents/unit-test-healer.md +1 -1
  271. package/presets/mavis/android-kotlin/agents/unit-test-planner.md +1 -1
  272. package/presets/mavis/android-kotlin/commands/task-continue.md +1 -1
  273. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +1140 -7
  274. package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +21 -5
  275. package/presets/mavis/android-kotlin/rules/anti-hallucination-contract.md +2 -0
  276. package/presets/mavis/android-kotlin/team/README.md +1 -1
  277. package/presets/mavis/go/adapter-map.json +1 -1
  278. package/presets/mavis/go/agents/feature-developer.md +1 -1
  279. package/presets/mavis/go/agents/task-analyst.md +1 -1
  280. package/presets/mavis/go/agents/task-router.md +1 -1
  281. package/presets/mavis/go/commands/task-continue.md +1 -1
  282. package/presets/mavis/go/hooks/chain-team-phases.sh +1140 -7
  283. package/presets/mavis/go/rules/agent-team-orchestrator.md +21 -5
  284. package/presets/mavis/go/rules/anti-hallucination-contract.md +2 -0
  285. package/presets/mavis/go/team/README.md +1 -1
  286. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  287. package/presets/mavis/ios-swift/agents/feature-developer.md +1 -1
  288. package/presets/mavis/ios-swift/agents/task-analyst.md +1 -1
  289. package/presets/mavis/ios-swift/agents/task-router.md +1 -1
  290. package/presets/mavis/ios-swift/commands/task-continue.md +1 -1
  291. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +1140 -7
  292. package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +21 -5
  293. package/presets/mavis/ios-swift/rules/anti-hallucination-contract.md +2 -0
  294. package/presets/mavis/ios-swift/team/README.md +1 -1
  295. package/presets/mavis/java/adapter-map.json +1 -1
  296. package/presets/mavis/java/agents/feature-developer.md +1 -1
  297. package/presets/mavis/java/agents/task-analyst.md +1 -1
  298. package/presets/mavis/java/agents/task-router.md +1 -1
  299. package/presets/mavis/java/commands/task-continue.md +1 -1
  300. package/presets/mavis/java/hooks/chain-team-phases.sh +1140 -7
  301. package/presets/mavis/java/rules/agent-team-orchestrator.md +21 -5
  302. package/presets/mavis/java/rules/anti-hallucination-contract.md +2 -0
  303. package/presets/mavis/java/team/README.md +1 -1
  304. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  305. package/presets/mavis/mcp-ts/agents/feature-developer.md +1 -1
  306. package/presets/mavis/mcp-ts/agents/task-analyst.md +1 -1
  307. package/presets/mavis/mcp-ts/agents/task-router.md +1 -1
  308. package/presets/mavis/mcp-ts/commands/task-continue.md +1 -1
  309. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +1140 -7
  310. package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +21 -5
  311. package/presets/mavis/mcp-ts/rules/anti-hallucination-contract.md +2 -0
  312. package/presets/mavis/mcp-ts/team/README.md +1 -1
  313. package/presets/mavis/next/REPO_AGENTS.md +1 -1
  314. package/presets/mavis/next/adapter-map.json +5 -5
  315. package/presets/mavis/next/agents/build-verifier.md +2 -0
  316. package/presets/mavis/next/agents/ci-investigator.md +1 -1
  317. package/presets/mavis/next/agents/debugger.md +1 -1
  318. package/presets/mavis/next/agents/feature-developer.md +10 -1
  319. package/presets/mavis/next/agents/migration-specialist.md +1 -1
  320. package/presets/mavis/next/agents/openspec-author.md +26 -2
  321. package/presets/mavis/next/agents/performance-auditor.md +1 -1
  322. package/presets/mavis/next/agents/qa-tester.md +1 -1
  323. package/presets/mavis/next/agents/solution-architect.md +1 -1
  324. package/presets/mavis/next/agents/task-analyst.md +21 -7
  325. package/presets/mavis/next/agents/task-router.md +32 -3
  326. package/presets/mavis/next/agents/tech-writer.md +1 -1
  327. package/presets/mavis/next/agents/unit-test-generator.md +1 -1
  328. package/presets/mavis/next/agents/unit-test-healer.md +1 -1
  329. package/presets/mavis/next/agents/unit-test-planner.md +1 -1
  330. package/presets/mavis/next/ai-local/conventions.md +20 -0
  331. package/presets/{opencode/next/ai-local/rules-library → mavis/next/ai-local/rules}/task-levels.md +12 -0
  332. package/presets/mavis/next/commands/task-continue.md +1 -1
  333. package/presets/mavis/next/hooks/chain-team-phases.sh +1140 -7
  334. package/presets/mavis/next/rules/agent-team-orchestrator.md +21 -5
  335. package/presets/mavis/next/rules/ai-local-overlay.md +1 -1
  336. package/presets/mavis/next/rules/anti-hallucination-contract.md +2 -0
  337. package/presets/mavis/next/team/README.md +1 -1
  338. package/presets/mavis/nuxt/adapter-map.json +1 -1
  339. package/presets/mavis/nuxt/agents/ci-investigator.md +1 -1
  340. package/presets/mavis/nuxt/agents/debugger.md +1 -1
  341. package/presets/mavis/nuxt/agents/feature-developer.md +1 -1
  342. package/presets/mavis/nuxt/agents/migration-specialist.md +1 -1
  343. package/presets/mavis/nuxt/agents/performance-auditor.md +1 -1
  344. package/presets/mavis/nuxt/agents/qa-tester.md +1 -1
  345. package/presets/mavis/nuxt/agents/solution-architect.md +1 -1
  346. package/presets/mavis/nuxt/agents/task-analyst.md +1 -1
  347. package/presets/mavis/nuxt/agents/task-router.md +1 -1
  348. package/presets/mavis/nuxt/agents/tech-writer.md +1 -1
  349. package/presets/mavis/nuxt/agents/unit-test-generator.md +1 -1
  350. package/presets/mavis/nuxt/agents/unit-test-healer.md +1 -1
  351. package/presets/mavis/nuxt/agents/unit-test-planner.md +1 -1
  352. package/presets/mavis/nuxt/commands/task-continue.md +1 -1
  353. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +1140 -7
  354. package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +21 -5
  355. package/presets/mavis/nuxt/rules/anti-hallucination-contract.md +2 -0
  356. package/presets/mavis/nuxt/team/README.md +1 -1
  357. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  358. package/presets/mavis/php-hexagonal/agents/feature-developer.md +1 -1
  359. package/presets/mavis/php-hexagonal/agents/task-analyst.md +1 -1
  360. package/presets/mavis/php-hexagonal/agents/task-router.md +1 -1
  361. package/presets/mavis/php-hexagonal/commands/task-continue.md +1 -1
  362. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +1140 -7
  363. package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +21 -5
  364. package/presets/mavis/php-hexagonal/rules/anti-hallucination-contract.md +2 -0
  365. package/presets/mavis/php-hexagonal/team/README.md +1 -1
  366. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  367. package/presets/mavis/php-laravel/agents/feature-developer.md +1 -1
  368. package/presets/mavis/php-laravel/agents/task-analyst.md +1 -1
  369. package/presets/mavis/php-laravel/agents/task-router.md +1 -1
  370. package/presets/mavis/php-laravel/commands/task-continue.md +1 -1
  371. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +1140 -7
  372. package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +21 -5
  373. package/presets/mavis/php-laravel/rules/anti-hallucination-contract.md +2 -0
  374. package/presets/mavis/php-laravel/team/README.md +1 -1
  375. package/presets/mavis/svelte/adapter-map.json +1 -1
  376. package/presets/mavis/svelte/agents/ci-investigator.md +1 -1
  377. package/presets/mavis/svelte/agents/debugger.md +1 -1
  378. package/presets/mavis/svelte/agents/feature-developer.md +1 -1
  379. package/presets/mavis/svelte/agents/migration-specialist.md +1 -1
  380. package/presets/mavis/svelte/agents/performance-auditor.md +1 -1
  381. package/presets/mavis/svelte/agents/qa-tester.md +1 -1
  382. package/presets/mavis/svelte/agents/solution-architect.md +1 -1
  383. package/presets/mavis/svelte/agents/task-analyst.md +1 -1
  384. package/presets/mavis/svelte/agents/task-router.md +1 -1
  385. package/presets/mavis/svelte/agents/tech-writer.md +1 -1
  386. package/presets/mavis/svelte/agents/unit-test-generator.md +1 -1
  387. package/presets/mavis/svelte/agents/unit-test-healer.md +1 -1
  388. package/presets/mavis/svelte/agents/unit-test-planner.md +1 -1
  389. package/presets/mavis/svelte/commands/task-continue.md +1 -1
  390. package/presets/mavis/svelte/hooks/chain-team-phases.sh +1140 -7
  391. package/presets/mavis/svelte/rules/agent-team-orchestrator.md +21 -5
  392. package/presets/mavis/svelte/rules/anti-hallucination-contract.md +2 -0
  393. package/presets/mavis/svelte/team/README.md +1 -1
  394. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  395. package/presets/opencode/android-kotlin/agents/ci-investigator.md +1 -1
  396. package/presets/opencode/android-kotlin/agents/debugger.md +1 -1
  397. package/presets/opencode/android-kotlin/agents/feature-developer.md +1 -1
  398. package/presets/opencode/android-kotlin/agents/migration-specialist.md +1 -1
  399. package/presets/opencode/android-kotlin/agents/performance-auditor.md +1 -1
  400. package/presets/opencode/android-kotlin/agents/qa-tester.md +1 -1
  401. package/presets/opencode/android-kotlin/agents/task-analyst.md +1 -1
  402. package/presets/opencode/android-kotlin/agents/task-router.md +1 -1
  403. package/presets/opencode/android-kotlin/agents/tech-writer.md +1 -1
  404. package/presets/opencode/android-kotlin/agents/unit-test-generator.md +1 -1
  405. package/presets/opencode/android-kotlin/agents/unit-test-healer.md +1 -1
  406. package/presets/opencode/android-kotlin/agents/unit-test-planner.md +1 -1
  407. package/presets/opencode/android-kotlin/commands/task-continue.md +1 -1
  408. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +1140 -7
  409. package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +21 -5
  410. package/presets/opencode/android-kotlin/rules/anti-hallucination-contract.md +2 -0
  411. package/presets/opencode/android-kotlin/team/README.md +1 -1
  412. package/presets/opencode/go/adapter-map.json +1 -1
  413. package/presets/opencode/go/agents/feature-developer.md +1 -1
  414. package/presets/opencode/go/agents/task-analyst.md +1 -1
  415. package/presets/opencode/go/agents/task-router.md +1 -1
  416. package/presets/opencode/go/commands/task-continue.md +1 -1
  417. package/presets/opencode/go/hooks/chain-team-phases.sh +1140 -7
  418. package/presets/opencode/go/rules/agent-team-orchestrator.md +21 -5
  419. package/presets/opencode/go/rules/anti-hallucination-contract.md +2 -0
  420. package/presets/opencode/go/team/README.md +1 -1
  421. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  422. package/presets/opencode/ios-swift/agents/feature-developer.md +1 -1
  423. package/presets/opencode/ios-swift/agents/task-analyst.md +1 -1
  424. package/presets/opencode/ios-swift/agents/task-router.md +1 -1
  425. package/presets/opencode/ios-swift/commands/task-continue.md +1 -1
  426. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +1140 -7
  427. package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +21 -5
  428. package/presets/opencode/ios-swift/rules/anti-hallucination-contract.md +2 -0
  429. package/presets/opencode/ios-swift/team/README.md +1 -1
  430. package/presets/opencode/java/adapter-map.json +1 -1
  431. package/presets/opencode/java/agents/feature-developer.md +1 -1
  432. package/presets/opencode/java/agents/task-analyst.md +1 -1
  433. package/presets/opencode/java/agents/task-router.md +1 -1
  434. package/presets/opencode/java/commands/task-continue.md +1 -1
  435. package/presets/opencode/java/hooks/chain-team-phases.sh +1140 -7
  436. package/presets/opencode/java/rules/agent-team-orchestrator.md +21 -5
  437. package/presets/opencode/java/rules/anti-hallucination-contract.md +2 -0
  438. package/presets/opencode/java/team/README.md +1 -1
  439. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  440. package/presets/opencode/mcp-ts/agents/feature-developer.md +1 -1
  441. package/presets/opencode/mcp-ts/agents/task-analyst.md +1 -1
  442. package/presets/opencode/mcp-ts/agents/task-router.md +1 -1
  443. package/presets/opencode/mcp-ts/commands/task-continue.md +1 -1
  444. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +1140 -7
  445. package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +21 -5
  446. package/presets/opencode/mcp-ts/rules/anti-hallucination-contract.md +2 -0
  447. package/presets/opencode/mcp-ts/team/README.md +1 -1
  448. package/presets/opencode/next/REPO_AGENTS.md +1 -1
  449. package/presets/opencode/next/adapter-map.json +5 -5
  450. package/presets/opencode/next/agents/build-verifier.md +2 -0
  451. package/presets/opencode/next/agents/ci-investigator.md +1 -1
  452. package/presets/opencode/next/agents/debugger.md +1 -1
  453. package/presets/opencode/next/agents/feature-developer.md +10 -1
  454. package/presets/opencode/next/agents/migration-specialist.md +1 -1
  455. package/presets/opencode/next/agents/openspec-author.md +26 -2
  456. package/presets/opencode/next/agents/performance-auditor.md +1 -1
  457. package/presets/opencode/next/agents/qa-tester.md +1 -1
  458. package/presets/opencode/next/agents/solution-architect.md +1 -1
  459. package/presets/opencode/next/agents/task-analyst.md +21 -7
  460. package/presets/opencode/next/agents/task-router.md +32 -3
  461. package/presets/opencode/next/agents/tech-writer.md +1 -1
  462. package/presets/opencode/next/agents/unit-test-generator.md +1 -1
  463. package/presets/opencode/next/agents/unit-test-healer.md +1 -1
  464. package/presets/opencode/next/agents/unit-test-planner.md +1 -1
  465. package/presets/opencode/next/ai-local/conventions.md +20 -0
  466. package/presets/opencode/next/ai-local/rules/task-levels.md +40 -0
  467. package/presets/opencode/next/commands/task-continue.md +1 -1
  468. package/presets/opencode/next/hooks/chain-team-phases.sh +1140 -7
  469. package/presets/opencode/next/rules/agent-team-orchestrator.md +21 -5
  470. package/presets/opencode/next/rules/ai-local-overlay.md +1 -1
  471. package/presets/opencode/next/rules/anti-hallucination-contract.md +2 -0
  472. package/presets/opencode/next/team/README.md +1 -1
  473. package/presets/opencode/nuxt/adapter-map.json +1 -1
  474. package/presets/opencode/nuxt/agents/ci-investigator.md +1 -1
  475. package/presets/opencode/nuxt/agents/debugger.md +1 -1
  476. package/presets/opencode/nuxt/agents/feature-developer.md +1 -1
  477. package/presets/opencode/nuxt/agents/migration-specialist.md +1 -1
  478. package/presets/opencode/nuxt/agents/performance-auditor.md +1 -1
  479. package/presets/opencode/nuxt/agents/qa-tester.md +1 -1
  480. package/presets/opencode/nuxt/agents/solution-architect.md +1 -1
  481. package/presets/opencode/nuxt/agents/task-analyst.md +1 -1
  482. package/presets/opencode/nuxt/agents/task-router.md +1 -1
  483. package/presets/opencode/nuxt/agents/tech-writer.md +1 -1
  484. package/presets/opencode/nuxt/agents/unit-test-generator.md +1 -1
  485. package/presets/opencode/nuxt/agents/unit-test-healer.md +1 -1
  486. package/presets/opencode/nuxt/agents/unit-test-planner.md +1 -1
  487. package/presets/opencode/nuxt/commands/task-continue.md +1 -1
  488. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +1140 -7
  489. package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +21 -5
  490. package/presets/opencode/nuxt/rules/anti-hallucination-contract.md +2 -0
  491. package/presets/opencode/nuxt/team/README.md +1 -1
  492. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  493. package/presets/opencode/php-hexagonal/agents/feature-developer.md +1 -1
  494. package/presets/opencode/php-hexagonal/agents/task-analyst.md +1 -1
  495. package/presets/opencode/php-hexagonal/agents/task-router.md +1 -1
  496. package/presets/opencode/php-hexagonal/commands/task-continue.md +1 -1
  497. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +1140 -7
  498. package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +21 -5
  499. package/presets/opencode/php-hexagonal/rules/anti-hallucination-contract.md +2 -0
  500. package/presets/opencode/php-hexagonal/team/README.md +1 -1
  501. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  502. package/presets/opencode/php-laravel/agents/feature-developer.md +1 -1
  503. package/presets/opencode/php-laravel/agents/task-analyst.md +1 -1
  504. package/presets/opencode/php-laravel/agents/task-router.md +1 -1
  505. package/presets/opencode/php-laravel/commands/task-continue.md +1 -1
  506. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +1140 -7
  507. package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +21 -5
  508. package/presets/opencode/php-laravel/rules/anti-hallucination-contract.md +2 -0
  509. package/presets/opencode/php-laravel/team/README.md +1 -1
  510. package/presets/opencode/svelte/adapter-map.json +1 -1
  511. package/presets/opencode/svelte/agents/ci-investigator.md +1 -1
  512. package/presets/opencode/svelte/agents/debugger.md +1 -1
  513. package/presets/opencode/svelte/agents/feature-developer.md +1 -1
  514. package/presets/opencode/svelte/agents/migration-specialist.md +1 -1
  515. package/presets/opencode/svelte/agents/performance-auditor.md +1 -1
  516. package/presets/opencode/svelte/agents/qa-tester.md +1 -1
  517. package/presets/opencode/svelte/agents/solution-architect.md +1 -1
  518. package/presets/opencode/svelte/agents/task-analyst.md +1 -1
  519. package/presets/opencode/svelte/agents/task-router.md +1 -1
  520. package/presets/opencode/svelte/agents/tech-writer.md +1 -1
  521. package/presets/opencode/svelte/agents/unit-test-generator.md +1 -1
  522. package/presets/opencode/svelte/agents/unit-test-healer.md +1 -1
  523. package/presets/opencode/svelte/agents/unit-test-planner.md +1 -1
  524. package/presets/opencode/svelte/commands/task-continue.md +1 -1
  525. package/presets/opencode/svelte/hooks/chain-team-phases.sh +1140 -7
  526. package/presets/opencode/svelte/rules/agent-team-orchestrator.md +21 -5
  527. package/presets/opencode/svelte/rules/anti-hallucination-contract.md +2 -0
  528. package/presets/opencode/svelte/team/README.md +1 -1
@@ -273,10 +273,429 @@ function writeSkeletonManifest(manifestPath) {
273
273
  }
274
274
  }
275
275
 
276
+ function normalizeRepoPath(value) {
277
+ let text = typeof value === 'string' ? value.trim() : '';
278
+ text = text.replace(/\\/g, '/');
279
+ while (text.startsWith('./')) text = text.slice(2);
280
+ if (!text || text === '—' || text === '-' || text === '–') return '';
281
+ if (/[\s()]/.test(text)) return '';
282
+ return text;
283
+ }
284
+
285
+ function isAppPath(file) {
286
+ const normalized = normalizeRepoPath(file);
287
+ return normalized === 'app' || normalized.startsWith('app/') || normalized.startsWith('app/**') || normalized.startsWith('app/*');
288
+ }
289
+
290
+ function isSpecFolderPath(file) {
291
+ const normalized = normalizeRepoPath(file);
292
+ return normalized.startsWith('docs/specs/') || normalized.startsWith('docs/specs/**') || normalized.startsWith('openspec/') || normalized.startsWith('openspec/**');
293
+ }
294
+
295
+ function listsBothSpecAndApp(files) {
296
+ let app = false;
297
+ let spec = false;
298
+ for (const file of files || []) {
299
+ if (isAppPath(file)) app = true;
300
+ if (isSpecFolderPath(file)) spec = true;
301
+ }
302
+ return app && spec;
303
+ }
304
+
305
+ function pathInWriteScopes(file, writeScopes) {
306
+ const target = normalizeRepoPath(file);
307
+ if (!target) return false;
308
+ const scopes = Array.isArray(writeScopes) ? writeScopes : [];
309
+ for (const scope of scopes) {
310
+ const normalized = normalizeRepoPath(scope);
311
+ if (!normalized) continue;
312
+ if (normalized === target) return true;
313
+ if (normalized.endsWith('/**')) {
314
+ const prefix = normalized.slice(0, -3);
315
+ if (target === prefix || target.startsWith(prefix + '/')) return true;
316
+ } else if (normalized.endsWith('/*')) {
317
+ const prefix = normalized.slice(0, -2);
318
+ const rest = target.startsWith(prefix + '/') ? target.slice(prefix.length + 1) : '';
319
+ if (rest && !rest.includes('/')) return true;
320
+ }
321
+ }
322
+ return false;
323
+ }
324
+
325
+ function taskFileSet(task) {
326
+ const all = []
327
+ .concat((task && task.files) || [], (task && task.specFiles) || [], (task && task.appFiles) || [])
328
+ .map((file) => normalizeRepoPath(file))
329
+ .filter(Boolean);
330
+ return new Set(all);
331
+ }
332
+
333
+ function taskReaches(tasks, startId, targetId) {
334
+ const byId = new Map(tasks.map((task) => [String(task.id), task]));
335
+ const seen = new Set();
336
+ const stack = [String(startId)];
337
+ while (stack.length > 0) {
338
+ const id = stack.pop();
339
+ if (seen.has(id)) continue;
340
+ seen.add(id);
341
+ const task = byId.get(id);
342
+ const deps = task && Array.isArray(task.dependsOn) ? task.dependsOn : [];
343
+ for (const dep of deps) {
344
+ if (String(dep) === String(targetId)) return true;
345
+ stack.push(String(dep));
346
+ }
347
+ }
348
+ return false;
349
+ }
350
+
351
+ function tasksAreOrdered(tasks, left, right) {
352
+ return taskReaches(tasks, left.id, right.id) || taskReaches(tasks, right.id, left.id);
353
+ }
354
+
355
+ function validateTaskFileLists(tasks, writeScopes) {
356
+ const list = Array.isArray(tasks) ? tasks : [];
357
+ const scopes = Array.isArray(writeScopes) ? writeScopes : [];
358
+ for (const task of list) {
359
+ const id = task && task.id ? task.id : '(unnamed)';
360
+ const files = (task && task.files) || [];
361
+ if (listsBothSpecAndApp(files)) {
362
+ return 'task "' + id + '" lists spec-folder paths and app/** paths in one file list; they are different lists';
363
+ }
364
+ if (scopes.length === 0) continue;
365
+ const combined = files.concat((task && task.specFiles) || [], (task && task.appFiles) || []);
366
+ for (const file of combined) {
367
+ if (!pathInWriteScopes(file, scopes)) {
368
+ const label = normalizeRepoPath(file) || file;
369
+ return 'task "' + id + '" file "' + label + '" is outside the implementing step writeScopes';
370
+ }
371
+ }
372
+ }
373
+ for (let i = 0; i < list.length; i += 1) {
374
+ for (let j = i + 1; j < list.length; j += 1) {
375
+ if (tasksAreOrdered(list, list[i], list[j])) continue;
376
+ const left = taskFileSet(list[i]);
377
+ let shared = '';
378
+ for (const file of taskFileSet(list[j])) {
379
+ if (left.has(file)) {
380
+ shared = file;
381
+ break;
382
+ }
383
+ }
384
+ if (shared) return 'parallel tasks "' + list[i].id + '" and "' + list[j].id + '" share "' + shared + '"';
385
+ }
386
+ }
387
+ return null;
388
+ }
389
+
390
+ function productionPathsOutsideTaskList(paths, tasks) {
391
+ const allowed = new Set();
392
+ for (const task of tasks || []) {
393
+ for (const file of taskFileSet(task)) allowed.add(file);
394
+ }
395
+ const outside = [];
396
+ for (const cited of paths || []) {
397
+ const normalized = normalizeRepoPath(cited);
398
+ if (normalized && !allowed.has(normalized)) outside.push(normalized);
399
+ }
400
+ return outside;
401
+ }
402
+
403
+ function splitMarkdownCells(line) {
404
+ const trimmed = String(line || '').trim();
405
+ if (!trimmed.startsWith('|')) return [];
406
+ const cells = trimmed.split('|').map((cell) => cell.trim());
407
+ if (cells.length && cells[0] === '') cells.shift();
408
+ if (cells.length && cells[cells.length - 1] === '') cells.pop();
409
+ return cells;
410
+ }
411
+
412
+ function isSeparatorRow(cells) {
413
+ return cells.length > 0 && cells.every((cell) => /^:?-{3,}:?$/.test(cell));
414
+ }
415
+
416
+ function pathsFromCell(cell) {
417
+ const text = String(cell || '');
418
+ const found = [];
419
+ const pattern = /`([^`]+)`/g;
420
+ let match = pattern.exec(text);
421
+ while (match) {
422
+ const normalized = normalizeRepoPath(match[1]);
423
+ if (normalized && normalized.includes('/')) found.push(normalized);
424
+ match = pattern.exec(text);
425
+ }
426
+ if (found.length > 0) return found;
427
+ return text.split(',').map((part) => normalizeRepoPath(part)).filter((part) => part.includes('/'));
428
+ }
429
+
430
+ function dependsFromCell(cell) {
431
+ const cleaned = String(cell || '').replace(/[`*]/g, '').trim();
432
+ if (!cleaned || cleaned === '—' || cleaned === '-' || cleaned === '–') return [];
433
+ return cleaned.split(/[,|/]/).map((part) => part.trim()).filter((part) => /^[A-Za-z][A-Za-z0-9._-]*$/.test(part));
434
+ }
435
+
436
+ function cellIsComplete(cell) {
437
+ const cleaned = String(cell || '').replace(/[`*[\]]/g, '').trim().toLowerCase();
438
+ return cleaned === 'complete' || cleaned === 'completed' || cleaned === 'done' || cleaned === 'x';
439
+ }
440
+
441
+ function absorbMarkdownTable(block, byId) {
442
+ const rows = [];
443
+ for (const line of block) {
444
+ const cells = splitMarkdownCells(line);
445
+ if (cells.length === 0 || isSeparatorRow(cells)) continue;
446
+ rows.push(cells);
447
+ }
448
+ if (rows.length < 2) return false;
449
+ const headers = rows[0].map((cell) => cell.replace(/[`*]/g, '').trim());
450
+ const idIndex = headers.findIndex((header) => /^id$/i.test(header));
451
+ if (idIndex < 0) return false;
452
+ const dependsIndex = headers.findIndex((header) => /dependson/i.test(header));
453
+ const specIndex = headers.findIndex((header) => /spec files/i.test(header));
454
+ const appIndex = headers.findIndex((header) => /^app files$/i.test(header));
455
+ const filesIndex = headers.findIndex((header, index) => index !== specIndex && index !== appIndex && /files|paths/i.test(header));
456
+ const statusIndex = headers.findIndex((header) => /^(status|done|state)$/i.test(header));
457
+ const sawFiles = specIndex >= 0 || appIndex >= 0 || filesIndex >= 0;
458
+ for (const cells of rows.slice(1)) {
459
+ const id = String(cells[idIndex] || '').replace(/[`*]/g, '').trim();
460
+ if (!id || /^id$/i.test(id)) continue;
461
+ const task = byId.get(id) || { id, dependsOn: [], files: [], specFiles: [], appFiles: [], tracked: false, rowComplete: false };
462
+ if (dependsIndex >= 0) {
463
+ task.dependsOn = dependsFromCell(cells[dependsIndex] || '');
464
+ task.tracked = true;
465
+ }
466
+ if (statusIndex >= 0) task.rowComplete = cellIsComplete(cells[statusIndex] || '');
467
+ if (filesIndex >= 0) {
468
+ const parsed = pathsFromCell(cells[filesIndex] || '');
469
+ if (parsed.length > 0) task.files = parsed;
470
+ }
471
+ if (specIndex >= 0) {
472
+ const parsed = pathsFromCell(cells[specIndex] || '');
473
+ if (parsed.length > 0) task.specFiles = parsed;
474
+ }
475
+ if (appIndex >= 0) {
476
+ const parsed = pathsFromCell(cells[appIndex] || '');
477
+ if (parsed.length > 0) task.appFiles = parsed;
478
+ }
479
+ byId.set(id, task);
480
+ }
481
+ return sawFiles;
482
+ }
483
+
484
+ function parseDecompositionTaskFileLists(markdown) {
485
+ const lines = String(markdown || '').split(/\r?\n/);
486
+ const byId = new Map();
487
+ let hasFileColumn = false;
488
+ let index = 0;
489
+ while (index < lines.length) {
490
+ if (!String(lines[index] || '').trim().startsWith('|')) {
491
+ index += 1;
492
+ continue;
493
+ }
494
+ const block = [];
495
+ while (index < lines.length && String(lines[index] || '').trim().startsWith('|')) {
496
+ block.push(lines[index]);
497
+ index += 1;
498
+ }
499
+ if (absorbMarkdownTable(block, byId)) hasFileColumn = true;
500
+ }
501
+ return { tasks: [...byId.values()], hasFileColumn };
502
+ }
503
+
504
+ function parseDecompositionTasks(markdown) {
505
+ const lines = String(markdown || '').split(/\r?\n/);
506
+ const byId = new Map();
507
+ let index = 0;
508
+ while (index < lines.length) {
509
+ if (!String(lines[index] || '').trim().startsWith('|')) {
510
+ index += 1;
511
+ continue;
512
+ }
513
+ const block = [];
514
+ while (index < lines.length && String(lines[index] || '').trim().startsWith('|')) {
515
+ block.push(lines[index]);
516
+ index += 1;
517
+ }
518
+ absorbMarkdownTable(block, byId);
519
+ }
520
+ return [...byId.values()].filter((task) => task.tracked === true);
521
+ }
522
+
523
+ function taskCoveredByCompletedArtifact(taskId, artifacts) {
524
+ const id = String(taskId);
525
+ const list = Array.isArray(artifacts) ? artifacts : [];
526
+ for (let index = 0; index < list.length; index += 1) {
527
+ const artifact = list[index];
528
+ if (!artifact || artifact.status !== 'completed') continue;
529
+ if (String(artifact.id) === id) return true;
530
+ const taskIds = Array.isArray(artifact.taskIds) ? artifact.taskIds : [];
531
+ for (let taskIndex = 0; taskIndex < taskIds.length; taskIndex += 1) {
532
+ if (String(taskIds[taskIndex]) === id) return true;
533
+ }
534
+ }
535
+ return false;
536
+ }
537
+
538
+ function computeDecompositionReadySet(tasks, artifacts) {
539
+ const list = (Array.isArray(tasks) ? tasks : []).filter((task) => task && task.id && task.tracked !== false);
540
+ const complete = new Set();
541
+ for (let index = 0; index < list.length; index += 1) {
542
+ const task = list[index];
543
+ if (task.rowComplete === true || taskCoveredByCompletedArtifact(task.id, artifacts)) complete.add(String(task.id));
544
+ }
545
+ const ready = [];
546
+ const blocked = [];
547
+ for (let index = 0; index < list.length; index += 1) {
548
+ const task = list[index];
549
+ const id = String(task.id);
550
+ if (complete.has(id)) continue;
551
+ const deps = Array.isArray(task.dependsOn) ? task.dependsOn.map((dep) => String(dep)) : [];
552
+ const waiting = [];
553
+ const seen = new Set();
554
+ for (let depIndex = 0; depIndex < deps.length; depIndex += 1) {
555
+ const dep = deps[depIndex];
556
+ if (!dep || seen.has(dep) || complete.has(dep)) continue;
557
+ seen.add(dep);
558
+ waiting.push(dep);
559
+ }
560
+ if (waiting.length === 0) ready.push(id);
561
+ else blocked.push({ id, waiting_on: waiting });
562
+ }
563
+ return { ready, blocked };
564
+ }
565
+
566
+ function readManifestArtifacts(dir) {
567
+ try {
568
+ const manifest = JSON.parse(fs.readFileSync(path.join(dir, 'artifact-manifest.json'), 'utf8'));
569
+ return Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
570
+ } catch {
571
+ return [];
572
+ }
573
+ }
574
+
575
+ function readDecompositionReadySet(dir) {
576
+ let markdown = '';
577
+ try {
578
+ markdown = fs.readFileSync(path.join(dir, 'decomposition.md'), 'utf8');
579
+ } catch {
580
+ markdown = '';
581
+ }
582
+ return computeDecompositionReadySet(parseDecompositionTasks(markdown), readManifestArtifacts(dir));
583
+ }
584
+
585
+ function formatDecompositionReadyClause(report, stepsForRows) {
586
+ const source = report && typeof report === 'object' ? report : { ready: [], blocked: [] };
587
+ const stepList = Array.isArray(stepsForRows) ? stepsForRows : [];
588
+ const allow = [];
589
+ for (let index = 0; index < stepList.length; index += 1) {
590
+ const taskIds = stepList[index] && stepList[index].taskIds;
591
+ if (!Array.isArray(taskIds)) continue;
592
+ for (let idIndex = 0; idIndex < taskIds.length; idIndex += 1) {
593
+ if (taskIds[idIndex] != null && String(taskIds[idIndex])) allow.push(String(taskIds[idIndex]));
594
+ }
595
+ }
596
+ const gate = allow.length > 0 ? new Set(allow) : null;
597
+ const ready = (Array.isArray(source.ready) ? source.ready : []).filter((id) => !gate || gate.has(String(id)));
598
+ const blocked = (Array.isArray(source.blocked) ? source.blocked : []).filter((row) => row && (!gate || gate.has(String(row.id))));
599
+ const readyText = ready.length > 0 ? ready.join(', ') : '(none)';
600
+ let text = ' Decomposition ready set: ' + readyText + '.';
601
+ if (blocked.length > 0) {
602
+ const parts = [];
603
+ for (let index = 0; index < blocked.length; index += 1) {
604
+ const row = blocked[index];
605
+ const waiting = Array.isArray(row.waiting_on) ? row.waiting_on.join(', ') : '';
606
+ parts.push(String(row.id) + ' waiting_on ' + waiting);
607
+ }
608
+ text += ' Blocked: ' + parts.join('; ') + '.';
609
+ }
610
+ return text;
611
+ }
612
+
613
+ function decompositionReadyClause(stepsForRows) {
614
+ try {
615
+ return formatDecompositionReadyClause(readDecompositionReadySet(taskDir), stepsForRows);
616
+ } catch {
617
+ return ' Decomposition ready set: (none).';
618
+ }
619
+ }
620
+
621
+ function productionCitationRepoPath(cited) {
622
+ const value = typeof cited === 'string' ? cited.trim() : '';
623
+ if (!value) return null;
624
+ const normalized = value.replace(/\\/g, '/');
625
+ if (path.isAbsolute(normalized)) {
626
+ const fromCwd = path.relative(process.cwd(), normalized);
627
+ if (fromCwd && !fromCwd.startsWith('..') && !path.isAbsolute(fromCwd)) return normalizeRepoPath(fromCwd);
628
+ return normalizeRepoPath(normalized) || normalized;
629
+ }
630
+ const taskResolved = path.resolve(taskDir, normalized);
631
+ const taskRelative = path.relative(taskDir, taskResolved);
632
+ const insideTask = taskRelative !== '' && taskRelative !== '..' && !taskRelative.startsWith('..' + path.sep) && !path.isAbsolute(taskRelative);
633
+ if (insideTask) {
634
+ try {
635
+ if (fs.statSync(taskResolved).isFile()) return null;
636
+ } catch {}
637
+ }
638
+ return normalizeRepoPath(normalized);
639
+ }
640
+
641
+ function implementingStepForTaskIds(taskIds) {
642
+ if (!Array.isArray(steps) || taskIds.length === 0) return null;
643
+ return steps.find((step) => Array.isArray(step && step.taskIds) && taskIds.some((id) => step.taskIds.map((item) => String(item)).includes(String(id)))) || null;
644
+ }
645
+
646
+ function productionWriteListError(entry) {
647
+ const artifactId = entry && entry.id ? entry.id : '(unnamed)';
648
+ const resume = 'Then resume with: /task-continue ' + slug;
649
+ const fail = (detail) => '[chain-team-phases] ' + slug + ': receipt "' + artifactId + '" ' + detail + ' ' + resume;
650
+ try {
651
+ const evidence = entry && Array.isArray(entry.evidencePaths) ? entry.evidencePaths : [];
652
+ const production = [];
653
+ for (const cited of evidence) {
654
+ const repoPath = productionCitationRepoPath(cited);
655
+ if (repoPath) production.push(repoPath);
656
+ }
657
+ if (production.length === 0) return null;
658
+ let markdown = '';
659
+ try {
660
+ markdown = fs.readFileSync(path.join(taskDir, 'decomposition.md'), 'utf8');
661
+ } catch {
662
+ markdown = '';
663
+ }
664
+ const parsed = parseDecompositionTaskFileLists(markdown);
665
+ if (!parsed.hasFileColumn) return null;
666
+ const tasks = parsed.tasks;
667
+ const taskIds = Array.isArray(entry && entry.taskIds) ? entry.taskIds.map((id) => String(id)) : [];
668
+ const step = implementingStepForTaskIds(taskIds);
669
+ const selectedIds = new Set(taskIds);
670
+ if (step && Array.isArray(step.taskIds)) {
671
+ for (const id of step.taskIds) selectedIds.add(String(id));
672
+ }
673
+ const selected = tasks.filter((task) => selectedIds.has(String(task.id)));
674
+ if (selected.length === 0) {
675
+ return fail('cites production paths but decomposition.md has no file list for ' + (taskIds.join(', ') || '(none)') + '. Record the task file list.');
676
+ }
677
+ const writeScopes = step && Array.isArray(step.writeScopes) ? step.writeScopes : [];
678
+ const listError = validateTaskFileLists(selected, writeScopes);
679
+ if (listError) return fail(listError + '.');
680
+ const owned = selected.filter((task) => taskIds.includes(String(task.id)));
681
+ const citedAgainst = owned.length > 0 ? owned : selected;
682
+ const outside = productionPathsOutsideTaskList(production, citedAgainst);
683
+ if (outside.length > 0) {
684
+ const ids = taskIds.length > 0 ? taskIds.join(', ') : citedAgainst.map((task) => task.id).join(', ');
685
+ return fail('cites production path "' + outside[0] + '", which is not on the decomposition file list for ' + ids + '.');
686
+ }
687
+ return null;
688
+ } catch (error) {
689
+ return fail('production file-list check failed (' + (error && error.message ? error.message : error) + ').');
690
+ }
691
+ }
692
+
276
693
  // A2: a `completed` receipt must cite evidence the harness can inspect. Order is
277
694
  // the message order — the first failing predicate wins, so the operator sees one
278
695
  // actionable line. `authoritativePaths[]` stays task-dir-relative; external
279
- // references belong in `evidencePaths[]`.
696
+ // references belong in `evidencePaths[]`. The task-folder checks below stay in
697
+ // place. A later production evidencePaths check uses the decomposition file list
698
+ // only when that list column exists.
280
699
  function validateCompletedArtifact(entry) {
281
700
  const artifactId = entry && entry.id ? entry.id : '(unnamed)';
282
701
  const entryStatus = entry && entry.status;
@@ -308,6 +727,8 @@ function validateCompletedArtifact(entry) {
308
727
  }
309
728
  }
310
729
  }
730
+ const productionListError = productionWriteListError(entry);
731
+ if (productionListError) return productionListError;
311
732
  return null;
312
733
  }
313
734
 
@@ -453,7 +874,21 @@ function endHumanGateIfResumed() {
453
874
  appendMetric({ type: 'human_gate_ended', at: now, gateStartedEventId: status.activeHumanGateEventId, source: 'hook', attributionConfidence: 'high' });
454
875
  delete status.activeHumanGateEventId;
455
876
  }
456
- function completeTaskMetrics() { appendMetric({ type: 'task_completed', at: now, outcome: status.state === 'completed' ? 'completed' : 'unknown', source: 'hook', attributionConfidence: 'high' }); }
877
+ function completeTaskMetrics() {
878
+ // Two hook processes can both enter completion before either writes the
879
+ // event. The metrics lock serializes them; the second sees the first write.
880
+ mutateMetrics((metrics) => {
881
+ if (metrics.events.some((event) => event && event.type === 'task_completed')) return;
882
+ metrics.events.push({
883
+ eventId: `${metrics.task.runId}:${Date.now()}:${Math.random().toString(16).slice(2)}`,
884
+ type: 'task_completed',
885
+ at: now,
886
+ outcome: status.state === 'completed' ? 'completed' : 'unknown',
887
+ source: 'hook',
888
+ attributionConfidence: 'high',
889
+ });
890
+ });
891
+ }
457
892
  function recordSkippedStep(step, stepIndex) {
458
893
  for (const agent of getStepAgents(step)) {
459
894
  const runId = status.metricsRunId || `${slug}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
@@ -463,6 +898,309 @@ function recordSkippedStep(step, stepIndex) {
463
898
  }
464
899
  }
465
900
 
901
+ // Living task files and the hook ledger stay put. A completed entry's other markdown is the body that leaves the default read.
902
+ const CLOSED_BODY_KEEP = new Set([
903
+ 'brief.md',
904
+ 'decomposition.md',
905
+ 'goal.md',
906
+ 'prompt.md',
907
+ 'prompt-log.md',
908
+ 'pipeline.json',
909
+ 'implementation.md',
910
+ '.memlog.md',
911
+ 'focus.md',
912
+ 'status.json',
913
+ 'metrics.json',
914
+ 'artifact-manifest.json',
915
+ 'overlay-scope.json',
916
+ ]);
917
+
918
+ function closedMarkdownBody(dir, cited) {
919
+ if (typeof cited !== 'string') return null;
920
+ const value = cited.trim();
921
+ if (!value || path.isAbsolute(value)) return null;
922
+ const resolved = path.resolve(dir, value);
923
+ const relative = path.relative(dir, resolved);
924
+ if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) return null;
925
+ const normalized = relative.split(path.sep).join('/');
926
+ if (!/\.md$/i.test(normalized) || normalized.startsWith('archive/')) return null;
927
+ const base = normalized.slice(normalized.lastIndexOf('/') + 1);
928
+ if (CLOSED_BODY_KEEP.has(base) || CLOSED_BODY_KEEP.has(normalized)) return null;
929
+ return { resolved, base };
930
+ }
931
+
932
+ function archiveClosedBody(dir, date, id, body) {
933
+ const archiveDir = path.join(dir, 'archive', date);
934
+ fs.mkdirSync(archiveDir, { recursive: true });
935
+ let name = body.base;
936
+ let destination = path.join(archiveDir, name);
937
+ if (fs.existsSync(destination)) {
938
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id)) return null;
939
+ name = id + '--' + body.base;
940
+ destination = path.join(archiveDir, name);
941
+ }
942
+ if (fs.existsSync(destination)) return null;
943
+ fs.renameSync(body.resolved, destination);
944
+ return 'archive/' + date + '/' + name;
945
+ }
946
+
947
+ function appendMemlogEvent(dir, text) {
948
+ const memlogPath = path.join(dir, '.memlog.md');
949
+ const line = '- `event`: ' + text + '\n';
950
+ let existing = '';
951
+ try { existing = fs.readFileSync(memlogPath, 'utf8'); } catch { existing = ''; }
952
+ if (existing.includes(text)) return existing;
953
+ const prefix = existing.length > 0 && !existing.endsWith('\n') ? '\n' : '';
954
+ fs.appendFileSync(memlogPath, prefix + line);
955
+ return existing + prefix + line;
956
+ }
957
+
958
+ function writeJsonFile(filePath, value) {
959
+ const temporary = filePath + '.' + String(process.pid) + '.tmp';
960
+ const fd = fs.openSync(temporary, 'w');
961
+ try {
962
+ fs.writeSync(fd, JSON.stringify(value, null, 2) + '\n');
963
+ } finally {
964
+ fs.closeSync(fd);
965
+ }
966
+ fs.renameSync(temporary, filePath);
967
+ }
968
+
969
+ function compactClosedManifestBodies(dir, closedOn) {
970
+ const date = typeof closedOn === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(closedOn)
971
+ ? closedOn
972
+ : new Date().toISOString().slice(0, 10);
973
+ const manifestPath = path.join(dir, 'artifact-manifest.json');
974
+ let manifest;
975
+ try {
976
+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
977
+ } catch {
978
+ return { moved: [] };
979
+ }
980
+ const slugBefore = manifest.slug;
981
+ const artifacts = Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
982
+ let memlog = '';
983
+ try { memlog = fs.readFileSync(path.join(dir, '.memlog.md'), 'utf8'); } catch { memlog = ''; }
984
+ let manifestChanged = false;
985
+ const moved = [];
986
+ for (let index = 0; index < artifacts.length; index += 1) {
987
+ const entry = artifacts[index];
988
+ if (!entry || entry.status !== 'completed' || typeof entry.id !== 'string' || !entry.id) continue;
989
+ const marker = 'closed manifest artifact ' + entry.id + ';';
990
+ if (memlog.includes(marker)) continue;
991
+ const cited = Array.isArray(entry.authoritativePaths) ? entry.authoritativePaths.slice() : [];
992
+ const relocated = [];
993
+ for (let pathIndex = 0; pathIndex < cited.length; pathIndex += 1) {
994
+ const body = closedMarkdownBody(dir, cited[pathIndex]);
995
+ if (!body) continue;
996
+ let stat = null;
997
+ try { stat = fs.statSync(body.resolved); } catch { stat = null; }
998
+ if (!stat || !stat.isFile()) continue;
999
+ let content = '';
1000
+ try { content = fs.readFileSync(body.resolved, 'utf8'); } catch { content = ''; }
1001
+ if (!/\S/.test(content)) continue;
1002
+ const archived = archiveClosedBody(dir, date, entry.id, body);
1003
+ if (!archived) continue;
1004
+ cited[pathIndex] = archived;
1005
+ relocated.push(archived);
1006
+ moved.push(archived);
1007
+ manifestChanged = true;
1008
+ }
1009
+ if (relocated.length > 0) entry.authoritativePaths = cited;
1010
+ let archiveHint = relocated.length > 0 ? 'archive/' + date + '/' : '';
1011
+ if (!archiveHint) {
1012
+ for (let pathIndex = 0; pathIndex < cited.length; pathIndex += 1) {
1013
+ const value = typeof cited[pathIndex] === 'string' ? cited[pathIndex].trim() : '';
1014
+ const match = /^archive\/\d{4}-\d{2}-\d{2}\//.exec(value);
1015
+ if (match) {
1016
+ archiveHint = match[0];
1017
+ break;
1018
+ }
1019
+ }
1020
+ }
1021
+ const text = archiveHint
1022
+ ? 'closed manifest artifact ' + entry.id + '; body archived under ' + archiveHint
1023
+ : 'closed manifest artifact ' + entry.id + '; no bulky markdown body moved';
1024
+ memlog = appendMemlogEvent(dir, text);
1025
+ }
1026
+ if (manifest.slug !== slugBefore) manifest.slug = slugBefore;
1027
+ if (manifestChanged) writeJsonFile(manifestPath, manifest);
1028
+ return { moved };
1029
+ }
1030
+
1031
+ function projectResumeArtifact(entry) {
1032
+ if (!entry || typeof entry !== 'object') return entry;
1033
+ if (entry.status !== 'completed') return entry;
1034
+ return {
1035
+ id: entry.id,
1036
+ status: entry.status,
1037
+ authoritativePaths: Array.isArray(entry.authoritativePaths) ? entry.authoritativePaths : [],
1038
+ };
1039
+ }
1040
+
1041
+ function defaultResumeRead(dir) {
1042
+ const chunks = [];
1043
+ try { chunks.push(fs.readFileSync(path.join(dir, 'focus.md'), 'utf8')); } catch {}
1044
+ try {
1045
+ const manifest = JSON.parse(fs.readFileSync(path.join(dir, 'artifact-manifest.json'), 'utf8'));
1046
+ const artifacts = Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
1047
+ const projected = [];
1048
+ for (let index = 0; index < artifacts.length; index += 1) {
1049
+ projected.push(projectResumeArtifact(artifacts[index]));
1050
+ }
1051
+ chunks.push(JSON.stringify({ slug: manifest.slug, artifacts: projected }));
1052
+ } catch {}
1053
+ try { chunks.push(fs.readFileSync(path.join(dir, '.memlog.md'), 'utf8')); } catch {}
1054
+ return chunks.join('\n');
1055
+ }
1056
+
1057
+ function archiveIndexLine(dir) {
1058
+ const root = path.join(dir, 'archive');
1059
+ let names = [];
1060
+ try { names = fs.readdirSync(root); } catch { names = []; }
1061
+ const dates = [];
1062
+ for (let index = 0; index < names.length; index += 1) {
1063
+ const name = names[index];
1064
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(name)) continue;
1065
+ let stat = null;
1066
+ try { stat = fs.statSync(path.join(root, name)); } catch { stat = null; }
1067
+ if (stat && stat.isDirectory()) dates.push(name);
1068
+ }
1069
+ dates.sort();
1070
+ if (dates.length === 0) return '- archive index: (none)';
1071
+ const parts = [];
1072
+ for (let index = 0; index < dates.length; index += 1) parts.push('archive/' + dates[index] + '/');
1073
+ return '- archive index: ' + parts.join(', ');
1074
+ }
1075
+
1076
+ function focusDigestMarkdown(dir, statusSnapshot) {
1077
+ const snapshot = statusSnapshot && typeof statusSnapshot === 'object' ? statusSnapshot : {};
1078
+ const slugValue = typeof snapshot.slug === 'string' ? snapshot.slug : '';
1079
+ const stepIndex = Number.isInteger(snapshot.pipelineIndex) ? snapshot.pipelineIndex : 0;
1080
+ const incomplete = [];
1081
+ try {
1082
+ const manifest = JSON.parse(fs.readFileSync(path.join(dir, 'artifact-manifest.json'), 'utf8'));
1083
+ const artifacts = Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
1084
+ for (let index = 0; index < artifacts.length; index += 1) {
1085
+ const artifact = artifacts[index];
1086
+ if (!artifact || artifact.status === 'completed') continue;
1087
+ const id = typeof artifact.id === 'string' ? artifact.id : '(no id)';
1088
+ const cited = Array.isArray(artifact.authoritativePaths) ? artifact.authoritativePaths : [];
1089
+ const paths = [];
1090
+ for (let pathIndex = 0; pathIndex < cited.length; pathIndex += 1) {
1091
+ if (typeof cited[pathIndex] === 'string') paths.push(cited[pathIndex]);
1092
+ }
1093
+ incomplete.push({ id, paths });
1094
+ }
1095
+ } catch {}
1096
+ let lastEvent = '(none)';
1097
+ try {
1098
+ const raw = fs.readFileSync(path.join(dir, '.memlog.md'), 'utf8');
1099
+ const lines = raw.split(/\r?\n/);
1100
+ const tickEvent = /`event`:\s*(.*)$/;
1101
+ const bareEvent = /(?:^|\s)event:\s*(.*)$/;
1102
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
1103
+ const line = lines[index];
1104
+ let matched = tickEvent.exec(line);
1105
+ if (!matched) matched = bareEvent.exec(line);
1106
+ if (matched && matched[1].trim()) {
1107
+ lastEvent = matched[1].trim();
1108
+ break;
1109
+ }
1110
+ }
1111
+ } catch {}
1112
+ let nextGate = 'none';
1113
+ if (snapshot.awaitingHumanGate === true || snapshot.state === 'awaiting_approval') {
1114
+ nextGate = 'human gate — /task-continue ' + slugValue;
1115
+ } else {
1116
+ try {
1117
+ const pipeline = JSON.parse(fs.readFileSync(path.join(dir, 'pipeline.json'), 'utf8'));
1118
+ const steps = Array.isArray(pipeline.steps) ? pipeline.steps : [];
1119
+ const gates = Array.isArray(pipeline.humanGates) ? pipeline.humanGates : [];
1120
+ for (let index = stepIndex; index < steps.length; index += 1) {
1121
+ const step = steps[index];
1122
+ const agents = !step ? [] : (Array.isArray(step.agent) ? step.agent : [step.agent]);
1123
+ let hit = '';
1124
+ for (let agentIndex = 0; agentIndex < agents.length; agentIndex += 1) {
1125
+ const agent = agents[agentIndex];
1126
+ if (typeof agent === 'string' && gates.indexOf('after:' + agent) !== -1) {
1127
+ hit = agent;
1128
+ break;
1129
+ }
1130
+ }
1131
+ if (hit) {
1132
+ const stepId = step && typeof step.id === 'string' ? step.id : 'step-' + String(index);
1133
+ nextGate = 'after:' + hit + ' (step ' + stepId + ', index ' + String(index) + ')';
1134
+ break;
1135
+ }
1136
+ }
1137
+ } catch {}
1138
+ }
1139
+ const pathLines = [];
1140
+ if (incomplete.length === 0) pathLines.push(' - (none)');
1141
+ else {
1142
+ for (let index = 0; index < incomplete.length; index += 1) {
1143
+ const item = incomplete[index];
1144
+ if (item.paths.length === 0) pathLines.push(' - ' + item.id + ': (none)');
1145
+ else {
1146
+ for (let pathIndex = 0; pathIndex < item.paths.length; pathIndex += 1) {
1147
+ pathLines.push(' - ' + item.id + ': ' + item.paths[pathIndex]);
1148
+ }
1149
+ }
1150
+ }
1151
+ }
1152
+ let readyLine = '- decomposition ready set: (none)';
1153
+ try {
1154
+ const report = readDecompositionReadySet(dir);
1155
+ const ids = Array.isArray(report.ready) ? report.ready : [];
1156
+ readyLine = '- decomposition ready set: ' + (ids.length > 0 ? ids.join(', ') : '(none)');
1157
+ } catch {
1158
+ readyLine = '- decomposition ready set: (none)';
1159
+ }
1160
+ const head = [
1161
+ '# focus.md',
1162
+ '',
1163
+ 'View only. `status.json`, `metrics.json`, `artifact-manifest.json`, and `.memlog.md` stay the system of record.',
1164
+ '',
1165
+ '- slug: ' + slugValue,
1166
+ '- pipeline step index: ' + String(stepIndex),
1167
+ readyLine,
1168
+ archiveIndexLine(dir),
1169
+ '- incomplete authoritative paths:',
1170
+ ];
1171
+ const tail = [
1172
+ '- last memlog event: ' + lastEvent,
1173
+ '- next gate: ' + nextGate,
1174
+ ];
1175
+ let pathBudget = 99 - head.length - tail.length;
1176
+ if (pathBudget < 1) pathBudget = 1;
1177
+ let kept = pathLines;
1178
+ if (pathLines.length > pathBudget) {
1179
+ const room = pathBudget - 1;
1180
+ kept = pathLines.slice(0, room);
1181
+ const omitted = pathLines.length - kept.length;
1182
+ kept.push(' - (' + String(omitted) + ' lines omitted to stay under 100)');
1183
+ }
1184
+ return head.concat(kept, tail).join('\n') + '\n';
1185
+ }
1186
+
1187
+ function writeFocusDigest() {
1188
+ const focusPath = path.join(taskDir, 'focus.md');
1189
+ const temporary = focusPath + '.' + String(process.pid) + '.' + String(Date.now()) + '.tmp';
1190
+ try {
1191
+ const markdown = focusDigestMarkdown(taskDir, status);
1192
+ const fd = fs.openSync(temporary, 'w');
1193
+ try {
1194
+ fs.writeSync(fd, markdown);
1195
+ try { fs.fsyncSync(fd); } catch {}
1196
+ } finally {
1197
+ fs.closeSync(fd);
1198
+ }
1199
+ fs.renameSync(temporary, focusPath);
1200
+ } catch {
1201
+ try { fs.unlinkSync(temporary); } catch {}
1202
+ }
1203
+ }
466
1204
 
467
1205
  function writeStatus(next) {
468
1206
  status = { ...status, ...next, slug, updatedAt: now };
@@ -479,6 +1217,11 @@ function writeStatus(next) {
479
1217
  fs.closeSync(fd);
480
1218
  }
481
1219
  fs.renameSync(temporary, statusPath);
1220
+ // Closed bodies move after the checkpoint lands. A compaction miss must not roll status.json back.
1221
+ try { compactClosedManifestBodies(taskDir, now.slice(0, 10)); } catch {}
1222
+ // focus.md is a view of this checkpoint. It is written after status.json
1223
+ // lands so a digest failure cannot roll the checkpoint back.
1224
+ writeFocusDigest();
482
1225
  }
483
1226
 
484
1227
  function out(message) {
@@ -641,7 +1384,8 @@ function handoffForWave(units, waveId) {
641
1384
  `Invoke IN PARALLEL (one message, multiple Task calls): ${labels.join(' AND ')} for slug "${slug}"${waveId ? ` (waveId=${waveId})` : ''}. ` +
642
1385
  `Each agent writes its artifact and owned receipt; the hook records slot joins from stops. Do not mutate status.json lifecycle fields. ` +
643
1386
  `Artifact inputs: ${inputIds.length > 0 ? inputIds.join(', ') : 'manifest defaults'}; owned output IDs: ${outputIds.join('; ')}. ` +
644
- `Metrics attemptIds: ${attemptIds.join('; ')}. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not calculate duration.`
1387
+ `Metrics attemptIds: ${attemptIds.join('; ')}. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not calculate duration. ${receiptPathClause()}` +
1388
+ decompositionReadyClause(units.map((unit) => steps[unit.stepIndex]))
645
1389
  );
646
1390
  }
647
1391
  function blockedNotice(blockedIndex, agent) {
@@ -657,16 +1401,29 @@ function noProgressNotice() {
657
1401
  const pending = pendingStepIndexes().map((index) => steps[index].id || `step-${index}`);
658
1402
  return `No schedulable step remains for slug "${slug}" (unsatisfied: ${pending.join(', ')}). Resume only via /task-continue ${slug}.`;
659
1403
  }
1404
+ function deferReason(wave, deferred) {
1405
+ const sameAgent = deferred.some((index) => wave.some((chosen) => {
1406
+ const left = getStepAgents(steps[chosen]);
1407
+ return getStepAgents(steps[index]).some((agent) => left.includes(agent));
1408
+ }));
1409
+ if (sameAgent) return 'same agent already in the wave';
1410
+ const missingScope = [...wave, ...deferred].some((index) => declaredScopes(steps[index]).length === 0);
1411
+ if (missingScope) return 'writeScopes undeclared';
1412
+ return 'writeScopes overlap';
1413
+ }
660
1414
  function dispatchReadyWave(prefixMessage) {
661
1415
  const ready = computeReadySteps();
662
1416
  if (ready.length === 0) return false;
663
1417
  const { wave, deferred } = selectWave(ready);
664
1418
  if (deferred.length > 0) {
665
- appendMetric({ type: 'parallel_conflict_deferred', at: now, stepIndex: wave[0], deferredStepIndexes: deferred, reason: 'ready set not conflict-free or writeScopes undeclared', source: 'hook', attributionConfidence: 'fallback' });
1419
+ appendMetric({ type: 'parallel_conflict_deferred', at: now, stepIndex: wave[0], deferredStepIndexes: deferred, reason: deferReason(wave, deferred), source: 'hook', attributionConfidence: 'fallback' });
666
1420
  }
667
1421
  // Slot-filtered dispatch: only unsatisfied (stepIndex, agent) slots are invoked.
668
1422
  const units = wave.flatMap((stepIndex) => unsatisfiedAgents(stepIndex).map((agent) => ({ stepIndex, agent })));
669
1423
  if (units.length === 0) return false;
1424
+ const unitAgents = units.map((unit) => unit.agent);
1425
+ refuseImplementationStart(unitAgents, (agent) => implementationDebugRetry(agent));
1426
+ recordAllowedDebugRetries(unitAgents);
670
1427
  const first = units[0].stepIndex;
671
1428
  const waveId = `${status.metricsRunId || slug}:wave-${first}`;
672
1429
  for (const unit of units) activateAttempts(steps[unit.stepIndex], unit.stepIndex, units.length > 1 ? waveId : null, [unit.agent]);
@@ -810,15 +1567,173 @@ function metricsHandoff(agent) {
810
1567
  return ' Metrics: use the supplied attemptId when available; for a parallel completion, write a minimal { attemptId, outcome } receipt to .metrics-receipts.json rather than relying on currentAgent. Do not calculate duration.';
811
1568
  }
812
1569
 
1570
+ function receiptPathClause() {
1571
+ return 'authoritativePaths are relative to the task folder (brief.md), not the repo root; put external files in evidencePaths.';
1572
+ }
813
1573
  function artifactHandoff(step, agent) {
814
1574
  const inputIds = Array.isArray(step?.artifactInputIds) ? step.artifactInputIds.join(', ') : 'manifest defaults';
815
- return ` Artifact inputs: ${inputIds}; owned output ID: ${artifactOutputIdFor(step, agent)}. Bind the terminal receipt to the supplied attemptId.`;
1575
+ return ` Artifact inputs: ${inputIds}; owned output ID: ${artifactOutputIdFor(step, agent)}. Bind the terminal receipt to the supplied attemptId. ${receiptPathClause()}`;
1576
+ }
1577
+
1578
+ // <<<implementation-rail>>>
1579
+ // Opt-in. Omitted, "off", and non-production intents stay off. Only "on" applies.
1580
+ function testBeforeHandoffRule() {
1581
+ return 'Include unit tests for mappers/logic before handoff.';
1582
+ }
1583
+ function railOnHandoffClause() {
1584
+ return ' Strict implementation rail: write a failing test before production edits; use a branch or worktree before the first implementation task; run code-reviewer between decomposition tasks; debug retries for this handoff are capped at two.';
1585
+ }
1586
+ function implementationRailApplies(pipeline) {
1587
+ if (!pipeline || typeof pipeline !== 'object') return false;
1588
+ const intent = typeof pipeline.intent === 'string' ? pipeline.intent : '';
1589
+ const level = pipeline.taskLevel;
1590
+ if (level === 'L0' || level === 0 || level === '0') return false;
1591
+ if (intent === 'docs-only' || intent === 'research' || intent === 'preset-only' || intent === 'spike') return false;
1592
+ if (pipeline.presetOnly === true) return false;
1593
+ return pipeline.implementationRail === 'on';
1594
+ }
1595
+ function briefHasOpenClarificationMarker(text) {
1596
+ if (typeof text !== 'string' || text.length === 0) return false;
1597
+ const lines = text.split(/\r?\n/);
1598
+ for (let index = 0; index < lines.length; index += 1) {
1599
+ let body = lines[index].trim().replace(/^(?:>\s*)+/, '');
1600
+ body = body.replace(/^(?:[-*+]|\d+[.)])\s+/, '');
1601
+ if (body.startsWith('[NEEDS CLARIFICATION]')) return true;
1602
+ }
1603
+ return false;
1604
+ }
1605
+ function implementationHandoffDecision(input) {
1606
+ const agent = input && input.agent;
1607
+ const applies = agent === 'feature-developer' && implementationRailApplies(input && input.pipeline);
1608
+ if (!applies) {
1609
+ return {
1610
+ start: true,
1611
+ rail: 'off',
1612
+ handoffRule: agent === 'feature-developer' ? testBeforeHandoffRule() : null,
1613
+ constraints: [],
1614
+ };
1615
+ }
1616
+ if (briefHasOpenClarificationMarker(input && input.briefText)) {
1617
+ return { start: false, rail: 'on', reason: 'open-marker', handoffRule: testBeforeHandoffRule(), constraints: [] };
1618
+ }
1619
+ const debugRetries = Number(input && input.debugRetryCount) || 0;
1620
+ if (input && input.debugRetry === true && debugRetries >= 2) {
1621
+ return { start: false, rail: 'on', reason: 'debug-retry-cap', handoffRule: testBeforeHandoffRule(), constraints: [] };
1622
+ }
1623
+ return {
1624
+ start: true,
1625
+ rail: 'on',
1626
+ handoffRule: testBeforeHandoffRule(),
1627
+ constraints: [
1628
+ 'failing test before production edits',
1629
+ 'branch or worktree before the first implementation task',
1630
+ 'code-reviewer between decomposition tasks',
1631
+ 'debug retries capped at two',
1632
+ ],
1633
+ };
1634
+ }
1635
+ // <<<implementation-rail-end>>>
1636
+
1637
+ function readPipelineRecord() {
1638
+ try {
1639
+ return JSON.parse(fs.readFileSync(pipelinePath, 'utf8'));
1640
+ } catch {
1641
+ return null;
1642
+ }
1643
+ }
1644
+ function readBriefText() {
1645
+ try {
1646
+ return fs.readFileSync(path.join(taskDir, 'brief.md'), 'utf8');
1647
+ } catch {
1648
+ return '';
1649
+ }
1650
+ }
1651
+ function countDebugImplementationRetries() {
1652
+ try {
1653
+ const metrics = JSON.parse(fs.readFileSync(METRICS_PATH, 'utf8'));
1654
+ const events = Array.isArray(metrics.events) ? metrics.events : [];
1655
+ return events.filter((event) => event && event.type === 'retry_scheduled' && event.nextAgent === 'feature-developer' && event.retryAfterFix === 'debugger').length;
1656
+ } catch {
1657
+ return 0;
1658
+ }
1659
+ }
1660
+ function featureDeveloperAlreadyStarted() {
1661
+ try {
1662
+ const metrics = JSON.parse(fs.readFileSync(METRICS_PATH, 'utf8'));
1663
+ const events = Array.isArray(metrics.events) ? metrics.events : [];
1664
+ return events.some((event) => event && event.type === 'attempt_started' && event.agent === 'feature-developer');
1665
+ } catch {
1666
+ return false;
1667
+ }
1668
+ }
1669
+ function implementationDebugRetry(agent) {
1670
+ return agent === 'feature-developer' && status.currentAgent === 'debugger' && featureDeveloperAlreadyStarted();
1671
+ }
1672
+ function blockImplementationStart(agent, debugRetry) {
1673
+ const decision = implementationHandoffDecision({
1674
+ agent,
1675
+ pipeline: readPipelineRecord(),
1676
+ briefText: readBriefText(),
1677
+ debugRetry: Boolean(debugRetry),
1678
+ debugRetryCount: countDebugImplementationRetries(),
1679
+ });
1680
+ if (decision.start) return null;
1681
+ if (decision.reason === 'debug-retry-cap') {
1682
+ return `Strict implementation rail is on for slug "${slug}". Debug retries for the implementation handoff are capped at two. Do not start implementation.`;
1683
+ }
1684
+ return `Strict implementation rail is on for slug "${slug}" and a [NEEDS CLARIFICATION] marker is open. Do not start implementation.`;
1685
+ }
1686
+ function refuseImplementationStart(agents, debugRetryFor) {
1687
+ const list = Array.isArray(agents) ? agents : [agents];
1688
+ for (let index = 0; index < list.length; index += 1) {
1689
+ const block = blockImplementationStart(list[index], debugRetryFor(list[index]));
1690
+ if (!block) continue;
1691
+ beginHumanGate();
1692
+ writeStatus({
1693
+ state: 'awaiting_approval',
1694
+ phase: 'human_gate',
1695
+ awaitingHumanGate: true,
1696
+ waveSteps: [],
1697
+ waveId: null,
1698
+ retryAfterFix: null,
1699
+ retryAfterFixStepIndex: null,
1700
+ });
1701
+ out(block);
1702
+ process.exit(0);
1703
+ }
1704
+ }
1705
+ function recordAllowedDebugRetries(agents) {
1706
+ if (!implementationRailApplies(readPipelineRecord())) return;
1707
+ const list = Array.isArray(agents) ? agents : [agents];
1708
+ for (let index = 0; index < list.length; index += 1) {
1709
+ if (!implementationDebugRetry(list[index])) continue;
1710
+ appendMetric({
1711
+ type: 'retry_scheduled',
1712
+ at: now,
1713
+ attemptId: null,
1714
+ nextAgent: 'feature-developer',
1715
+ retryAfterFix: 'debugger',
1716
+ source: 'hook',
1717
+ attributionConfidence: 'high',
1718
+ });
1719
+ }
1720
+ }
1721
+ function railInstructionClause(agent) {
1722
+ const decision = implementationHandoffDecision({
1723
+ agent,
1724
+ pipeline: readPipelineRecord(),
1725
+ briefText: readBriefText(),
1726
+ debugRetry: false,
1727
+ debugRetryCount: 0,
1728
+ });
1729
+ if (decision.rail !== 'on' || !decision.start) return '';
1730
+ return railOnHandoffClause();
816
1731
  }
817
1732
 
818
1733
  function handoffForAgent(agent, scope, step = null) {
819
1734
  const fn = AGENT_HANDOFF[agent];
820
1735
  const handoff = fn ? fn(slug, scope) : `Invoke ${agent} subagent for slug "${slug}". Upsert the owned terminal receipt in artifact-manifest.json; do not mutate status.json lifecycle fields.`;
821
- return handoff + artifactHandoff(step, agent) + metricsHandoff(agent);
1736
+ return handoff + railInstructionClause(agent) + artifactHandoff(step, agent) + metricsHandoff(agent) + decompositionReadyClause(step ? [step] : []);
822
1737
  }
823
1738
 
824
1739
  function handoffForParallelStep(step) {
@@ -830,7 +1745,8 @@ function handoffForParallelStep(step) {
830
1745
  `Invoke IN PARALLEL (one message, multiple Task calls): ${agents.join(' AND ')} for slug "${slug}". ` +
831
1746
  `Each agent writes its artifact and owned receipt; the hook records parallelCompleted from stops. Do not mutate status.json lifecycle fields. ` +
832
1747
  `Artifact inputs: ${Array.isArray(step.artifactInputIds) ? step.artifactInputIds.join(', ') : 'manifest defaults'}; owned output IDs: ${agents.map((agent) => `${agent}=${artifactOutputIdFor(step, agent)}`).join('; ')}. ` +
833
- `Metrics attemptIds: ${attemptIds.join('; ')}. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not calculate duration.`
1748
+ `Metrics attemptIds: ${attemptIds.join('; ')}. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not calculate duration. ${receiptPathClause()}` +
1749
+ decompositionReadyClause([step])
834
1750
  );
835
1751
  }
836
1752
 
@@ -839,9 +1755,35 @@ function hasGateAfter(agent, humanGates) {
839
1755
  }
840
1756
 
841
1757
  function hasGateAfterStep(step, humanGates) {
1758
+ if (!Array.isArray(humanGates) || !step) return false;
1759
+ if (typeof step.id === 'string' && step.id.length > 0 && humanGates.includes(`after:${step.id}`)) return true;
842
1760
  return getStepAgents(step).some((a) => hasGateAfter(a, humanGates));
843
1761
  }
844
1762
 
1763
+ // A followup loop of the subagent that just finished arrives with no attemptId
1764
+ // and no receipt for the attempt this same transition opened. That stop is not
1765
+ // the next agent. A stop more than 15s later, still without a receipt, is a
1766
+ // real missing receipt and must stall.
1767
+ function isSchedulingEcho() {
1768
+ if (typeof hookInput.attemptId === 'string' && hookInput.attemptId.length > 0) return false;
1769
+ const entries = Object.entries(status.activeAttempts || {});
1770
+ if (entries.length !== 1) return false;
1771
+ const [attemptId, entry] = entries[0];
1772
+ const previous = status.lastCompletedAttempt;
1773
+ if (!previous || previous.completedAt !== entry.startedAt) return false;
1774
+ const ageMs = Date.parse(now) - Date.parse(entry.startedAt);
1775
+ if (!Number.isFinite(ageMs) || ageMs < 0 || ageMs > 15000) return false;
1776
+ const previousJoined = Object.values(status.joinedSlots || {}).some((slot) => slot && slot.attemptId === previous.attemptId);
1777
+ const linearAdvance = !isGraphMode() && typeof entry.stepIndex === 'number' && entry.stepIndex > 0;
1778
+ if (!previousJoined && !linearAdvance) return false;
1779
+ try {
1780
+ const manifest = JSON.parse(fs.readFileSync(path.join(taskDir, 'artifact-manifest.json'), 'utf8'));
1781
+ const artifacts = Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
1782
+ if (artifacts.some((item) => item && item.receipt && item.receipt.attemptId === attemptId)) return false;
1783
+ } catch {}
1784
+ return true;
1785
+ }
1786
+
845
1787
  function legacyFlow() {
846
1788
  if (status.phase === 'analysis') {
847
1789
  process.stdout.write('{}');
@@ -967,6 +1909,8 @@ if (hookInput.action === 'end_human_gate') {
967
1909
  const resumeNext = findNextExecutableStep(resumeSteps, resumeStart, taskDir);
968
1910
  if (resumeNext) {
969
1911
  const resumeAgents = getStepAgents(resumeNext.step);
1912
+ refuseImplementationStart(resumeAgents, (agent) => implementationDebugRetry(agent));
1913
+ recordAllowedDebugRetries(resumeAgents);
970
1914
  activateAttempts(resumeNext.step, resumeNext.index);
971
1915
  writeStatus({
972
1916
  pipelineIndex: resumeNext.index,
@@ -1059,6 +2003,10 @@ if (pipelineParseError) {
1059
2003
  }
1060
2004
 
1061
2005
  steps = pipeline.steps || [];
2006
+ if (isSchedulingEcho()) {
2007
+ process.stdout.write('{}');
2008
+ process.exit(0);
2009
+ }
1062
2010
  const initialIdx = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
1063
2011
  const initialStep = steps[initialIdx];
1064
2012
  const activeAttemptCountBeforeFinish = Object.keys(status.activeAttempts || {}).length;
@@ -1119,6 +2067,9 @@ function nearestPrecedingStepIndex(agent, fromIndex, fallback) {
1119
2067
  return match >= 0 ? match : fallback;
1120
2068
  }
1121
2069
  function scheduleRetry(agent, retryAfterFix, predecessor, explicitStepIndex = null) {
2070
+ if (agent === 'feature-developer') {
2071
+ refuseImplementationStart([agent], () => retryAfterFix === 'debugger');
2072
+ }
1122
2073
  const currentIndex = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
1123
2074
  const explicitOk = Number.isInteger(explicitStepIndex) && getStepAgents(steps[explicitStepIndex]).includes(agent);
1124
2075
  const stepIndex = explicitOk ? explicitStepIndex : nearestPrecedingStepIndex(agent, currentIndex, -1);
@@ -1426,6 +2377,8 @@ if (!next) {
1426
2377
  const { step: nextStep, index: nextIdx } = next;
1427
2378
  const nextAgents = getStepAgents(nextStep);
1428
2379
 
2380
+ refuseImplementationStart(nextAgents, (agent) => implementationDebugRetry(agent));
2381
+ recordAllowedDebugRetries(nextAgents);
1429
2382
  activateAttempts(nextStep, nextIdx);
1430
2383
  writeStatus({
1431
2384
  pipelineIndex: nextIdx,
@@ -1454,6 +2407,180 @@ const fs = require('fs');
1454
2407
  const path = require('path');
1455
2408
  const { spawnSync } = require('child_process');
1456
2409
 
2410
+ // <<<standards-draft>>>
2411
+ // Explicit payload only. This postflight never walks the repo and never
2412
+ // creates `.ai.local/rules/`. The same provenance tag does not rewrite an
2413
+ // accepted Gotchas, Patterns, or Decisions line.
2414
+ function standardsDraftTag(provenance) {
2415
+ return '(`' + provenance + '`)';
2416
+ }
2417
+
2418
+ function standardsDraftLineIndex(content, header) {
2419
+ if (content.startsWith(header) && (content.length === header.length || content.charAt(header.length) === '\n')) return 0;
2420
+ const at = content.indexOf('\n' + header + '\n');
2421
+ if (at !== -1) return at + 1;
2422
+ if (content.endsWith('\n' + header)) return content.length - header.length;
2423
+ return -1;
2424
+ }
2425
+
2426
+ function standardsDraftSection(content, name) {
2427
+ const header = '## ' + name;
2428
+ const start = standardsDraftLineIndex(content, header);
2429
+ if (start === -1) return null;
2430
+ const from = start + header.length;
2431
+ const next = content.indexOf('\n## ', from);
2432
+ const end = next === -1 ? content.length : next;
2433
+ return content.slice(start, end);
2434
+ }
2435
+
2436
+ function standardsDraftProtected(content) {
2437
+ const names = ['Language', 'Gotchas', 'Patterns', 'Decisions', 'Advisory index'];
2438
+ let snapshot = '';
2439
+ for (let index = 0; index < names.length; index += 1) {
2440
+ const body = standardsDraftSection(content, names[index]);
2441
+ snapshot += names[index] + '\n' + (body === null ? '' : body) + '\n';
2442
+ }
2443
+ return snapshot;
2444
+ }
2445
+
2446
+ function standardsDraftNormalize(line) {
2447
+ return line.trim().replace(/\s+/g, ' ').replace(/^-\s+/, '').replace(/\s+\(`[^`]*`\)$/, '').toLowerCase();
2448
+ }
2449
+
2450
+ function standardsDraftAccepted(content, text) {
2451
+ const pending = standardsDraftSection(content, 'Pending');
2452
+ let rest = content;
2453
+ if (pending !== null) {
2454
+ const start = content.indexOf(pending);
2455
+ rest = content.slice(0, start) + content.slice(start + pending.length);
2456
+ }
2457
+ const needle = standardsDraftNormalize(text);
2458
+ if (!needle) return false;
2459
+ const lines = rest.split('\n');
2460
+ for (let index = 0; index < lines.length; index += 1) {
2461
+ const line = lines[index];
2462
+ if (!/^-\s+\S/.test(line)) continue;
2463
+ if (standardsDraftNormalize(line) === needle) return true;
2464
+ }
2465
+ return false;
2466
+ }
2467
+
2468
+ function standardsDraftAppendPending(content, line) {
2469
+ const header = '## Pending';
2470
+ const start = standardsDraftLineIndex(content, header);
2471
+ if (start === -1) {
2472
+ const sep = content.endsWith('\n') ? '\n' : '\n\n';
2473
+ return content + sep + header + '\n\n' + line + '\n';
2474
+ }
2475
+ const from = start + header.length;
2476
+ const next = content.indexOf('\n## ', from);
2477
+ const end = next === -1 ? content.length : next;
2478
+ let body = content.slice(from, end);
2479
+ const hasBullet = /(^|\n)-\s+\S/.test(body);
2480
+ if (!hasBullet && /(^|\n)-[ \t]*(?=\n|$)/.test(body)) {
2481
+ body = body.replace(/(^|\n)-[ \t]*(?=\n|$)/, '$1' + line);
2482
+ } else if (body.endsWith('\n\n')) {
2483
+ body = body.slice(0, -1) + line + '\n\n';
2484
+ } else if (body.endsWith('\n')) {
2485
+ body = body + line + '\n';
2486
+ } else {
2487
+ body = body + '\n' + line + '\n';
2488
+ }
2489
+ return content.slice(0, from) + body + content.slice(end);
2490
+ }
2491
+
2492
+ function standardsDraftProvenance(draft) {
2493
+ if (!draft || typeof draft.provenance !== 'string') return '';
2494
+ const provenance = draft.provenance.trim();
2495
+ if (/^incident: [A-Za-z0-9][A-Za-z0-9._:-]{0,80}$/.test(provenance)) return provenance;
2496
+ const read = /^read: ([A-Za-z0-9][A-Za-z0-9._/-]{0,160})$/.exec(provenance);
2497
+ if (!read) return '';
2498
+ const parts = read[1].split('/');
2499
+ if (parts.indexOf('..') !== -1 || parts.indexOf('.') !== -1) return '';
2500
+ if (read[1] === '.ai.local/rules' || read[1].indexOf('.ai.local/rules/') === 0) return '';
2501
+ return provenance;
2502
+ }
2503
+
2504
+ function standardsDraftWrite(target, content) {
2505
+ fs.mkdirSync(path.dirname(target), { recursive: true });
2506
+ const temporary = target + '.' + String(process.pid) + '.tmp';
2507
+ fs.writeFileSync(temporary, content);
2508
+ fs.renameSync(temporary, target);
2509
+ }
2510
+
2511
+ function appendOptionalStandardsDraft(root, draft) {
2512
+ const provenance = standardsDraftProvenance(draft);
2513
+ if (!provenance) return { wrote: false, reason: 'provenance' };
2514
+ const text = draft && typeof draft.text === 'string' ? draft.text.trim() : '';
2515
+ if (!text || text.length > 400 || text.indexOf('\n') !== -1 || text.indexOf('\r') !== -1 || text.indexOf('## ') !== -1) {
2516
+ return { wrote: false, reason: 'text' };
2517
+ }
2518
+ let destination = 'conventions';
2519
+ if (draft.destination != null) {
2520
+ if (draft.destination === 'conventions' || draft.destination === 'rules-library') destination = draft.destination;
2521
+ else return { wrote: false, reason: 'destination' };
2522
+ }
2523
+ const line = '- ' + text + ' ' + standardsDraftTag(provenance);
2524
+ const overlay = path.join(root, '.ai.local');
2525
+ const rulesDir = path.join(overlay, 'rules');
2526
+ const rulesPrefix = rulesDir + path.sep;
2527
+
2528
+ if (destination === 'rules-library') {
2529
+ const stem = draft && typeof draft.stem === 'string' ? draft.stem : '';
2530
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+){0,8}$/.test(stem) || stem.length > 48) {
2531
+ return { wrote: false, reason: 'stem' };
2532
+ }
2533
+ const libraryDir = path.join(overlay, 'rules-library');
2534
+ const target = path.join(libraryDir, stem + '.md');
2535
+ const libraryPrefix = libraryDir + path.sep;
2536
+ if (!target.startsWith(libraryPrefix)) return { wrote: false, reason: 'path' };
2537
+ if (target === rulesDir || target.startsWith(rulesPrefix)) return { wrote: false, reason: 'rules' };
2538
+ let existing = null;
2539
+ try {
2540
+ existing = fs.readFileSync(target, 'utf8');
2541
+ } catch (error) {
2542
+ if (!error || error.code !== 'ENOENT') throw error;
2543
+ }
2544
+ if (existing !== null) {
2545
+ if (existing.indexOf(standardsDraftTag(provenance)) !== -1) {
2546
+ return { wrote: false, reason: 'same-provenance', target: target };
2547
+ }
2548
+ const prefix = existing.endsWith('\n') ? '' : '\n';
2549
+ fs.appendFileSync(target, prefix + line + '\n');
2550
+ return { wrote: true, target: target, mode: 'append-provenance' };
2551
+ }
2552
+ standardsDraftWrite(target, '# ' + stem + '\n\nPending draft. Inactive until a human moves this file into `.ai.local/rules/`.\n\n' + line + '\n');
2553
+ return { wrote: true, target: target, mode: 'create' };
2554
+ }
2555
+
2556
+ const conventionsPath = path.join(overlay, 'conventions.md');
2557
+ if (conventionsPath === rulesDir || conventionsPath.startsWith(rulesPrefix)) {
2558
+ return { wrote: false, reason: 'rules' };
2559
+ }
2560
+ let content = null;
2561
+ try {
2562
+ content = fs.readFileSync(conventionsPath, 'utf8');
2563
+ } catch (error) {
2564
+ if (!error || error.code !== 'ENOENT') throw error;
2565
+ }
2566
+ if (content === null) content = '# Living conventions\n';
2567
+ if (content.indexOf(standardsDraftTag(provenance)) !== -1) {
2568
+ return { wrote: false, reason: 'same-provenance', target: conventionsPath };
2569
+ }
2570
+ const before = standardsDraftProtected(content);
2571
+ const next = standardsDraftAppendPending(content, line);
2572
+ if (standardsDraftProtected(next) !== before) {
2573
+ return { wrote: false, reason: 'protected', target: conventionsPath };
2574
+ }
2575
+ standardsDraftWrite(conventionsPath, next);
2576
+ return {
2577
+ wrote: true,
2578
+ target: conventionsPath,
2579
+ mode: standardsDraftAccepted(content, text) ? 'provenance-only' : 'pending',
2580
+ };
2581
+ }
2582
+ // <<<standards-draft-end>>>
2583
+
1457
2584
  let input;
1458
2585
  try {
1459
2586
  input = JSON.parse(process.env.INPUT || '');
@@ -1486,6 +2613,12 @@ if (pipeline && (pipeline.profile === 'light' || pipeline.intent === 'spike')) {
1486
2613
  process.exit(0);
1487
2614
  }
1488
2615
 
2616
+ try {
2617
+ appendOptionalStandardsDraft(process.cwd(), input.standardsDraft);
2618
+ } catch {
2619
+ // A draft failure must not fail the stop, and must not add a WARNING.
2620
+ }
2621
+
1489
2622
  if (!fs.existsSync(path.join(process.cwd(), '.ai.local', 'scripts', 'run.mjs'))) {
1490
2623
  process.stderr.write(
1491
2624
  'WARNING: self-learning loop skipped: .ai.local/scripts/run.mjs is missing (install it with `npx @bonesofspring/ai-rules init <tool> --preset <stack>`)\n',