@bonesofspring/ai-rules 0.2.87 → 0.2.91

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 (470) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +9 -1
  3. package/bin/lib/engine-scripts.js +7 -0
  4. package/bin/lib/seed-ai-local-team.js +40 -0
  5. package/bin/opencode-install.js +11 -10
  6. package/docs/OPENCODE-COMPATIBILITY.md +2 -1
  7. package/docs/OPENCODE.md +27 -5
  8. package/docs/openapi/team-db.v1.json +2 -2
  9. package/package.json +1 -1
  10. package/presets/_shared/ai-local/env.example +54 -0
  11. package/presets/_shared/ai-local/scripts/aggregate-agent-task-metrics.mjs +34 -5
  12. package/presets/_shared/ai-local/scripts/check-task-repositories.mjs +25 -22
  13. package/presets/_shared/ai-local/scripts/process-lease.mjs +3 -2
  14. package/presets/_shared/ai-local/scripts/processes.mjs +52 -20
  15. package/presets/_shared/ai-local/scripts/run.mjs +38 -6
  16. package/presets/_shared/ai-local/scripts/settings.mjs +246 -0
  17. package/presets/_shared/ai-local/scripts/task-worktree.mjs +364 -0
  18. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +2 -2
  19. package/presets/_shared/ai-local/scripts/team-db-project.mjs +87 -14
  20. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +102 -12
  21. package/presets/_shared/ai-local/scripts/team-db-tracker.mjs +35 -0
  22. package/presets/_shared/ai-local/scripts/tracker-planned-drain.mjs +10 -1
  23. package/presets/_shared/ai-local/scripts/verification.mjs +106 -11
  24. package/presets/_shared/core/agent-team/agent-task-metrics.md +10 -2
  25. package/presets/_shared/core/agent-team/agent-team-intake.md +2 -0
  26. package/presets/_shared/core/agent-team/agent-team-orchestrator.md +2 -2
  27. package/presets/_shared/core/meta/preset-writing-style.md +8 -0
  28. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +541 -61
  29. package/presets/_shared/hooks/guard-shell-command.mjs.tmpl +733 -9
  30. package/presets/_shared/hooks/prompt-autoroute.mjs.tmpl +153 -0
  31. package/presets/claude/android-kotlin/CLAUDE.md +2 -4
  32. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +541 -61
  33. package/presets/claude/android-kotlin/hooks/guard-shell-command.mjs +733 -9
  34. package/presets/claude/android-kotlin/hooks/prompt-autoroute.mjs +153 -0
  35. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-intake.md +2 -0
  36. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +2 -2
  37. package/presets/claude/android-kotlin/rules/tooling-and-review/preset-writing-style.md +8 -0
  38. package/presets/claude/android-kotlin/settings.json +15 -5
  39. package/presets/claude/go/CLAUDE.md +2 -4
  40. package/presets/claude/go/hooks/chain-team-phases.sh +541 -61
  41. package/presets/claude/go/hooks/guard-shell-command.mjs +733 -9
  42. package/presets/claude/go/hooks/prompt-autoroute.mjs +153 -0
  43. package/presets/claude/go/rules/tooling-and-review/agent-team-intake.md +2 -0
  44. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +2 -2
  45. package/presets/claude/go/rules/tooling-and-review/preset-writing-style.md +8 -0
  46. package/presets/claude/go/settings.json +15 -5
  47. package/presets/claude/ios-swift/CLAUDE.md +2 -4
  48. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +541 -61
  49. package/presets/claude/ios-swift/hooks/guard-shell-command.mjs +733 -9
  50. package/presets/claude/ios-swift/hooks/prompt-autoroute.mjs +153 -0
  51. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-intake.md +2 -0
  52. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +2 -2
  53. package/presets/claude/ios-swift/rules/tooling-and-review/preset-writing-style.md +8 -0
  54. package/presets/claude/ios-swift/settings.json +15 -5
  55. package/presets/claude/java/CLAUDE.md +2 -4
  56. package/presets/claude/java/hooks/chain-team-phases.sh +541 -61
  57. package/presets/claude/java/hooks/guard-shell-command.mjs +733 -9
  58. package/presets/claude/java/hooks/prompt-autoroute.mjs +153 -0
  59. package/presets/claude/java/rules/tooling-and-review/agent-team-intake.md +2 -0
  60. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +2 -2
  61. package/presets/claude/java/rules/tooling-and-review/preset-writing-style.md +8 -0
  62. package/presets/claude/java/settings.json +15 -5
  63. package/presets/claude/mcp-ts/CLAUDE.md +2 -4
  64. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +541 -61
  65. package/presets/claude/mcp-ts/hooks/guard-shell-command.mjs +733 -9
  66. package/presets/claude/mcp-ts/hooks/prompt-autoroute.mjs +153 -0
  67. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-intake.md +2 -0
  68. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +2 -2
  69. package/presets/claude/mcp-ts/rules/tooling-and-review/preset-writing-style.md +8 -0
  70. package/presets/claude/mcp-ts/settings.json +15 -5
  71. package/presets/claude/mol/CLAUDE.md +2 -4
  72. package/presets/claude/mol/agents/feature-developer.md +1 -1
  73. package/presets/claude/mol/ai-local/rules-library/commit-hygiene.md +1 -1
  74. package/presets/claude/mol/commands/task-evil.md +8 -0
  75. package/presets/claude/mol/hooks/chain-team-phases.sh +541 -61
  76. package/presets/claude/mol/hooks/guard-shell-command.mjs +733 -9
  77. package/presets/claude/mol/hooks/prompt-autoroute.mjs +153 -0
  78. package/presets/claude/mol/rules/tooling-and-review/agent-team-intake.md +2 -0
  79. package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +2 -2
  80. package/presets/claude/mol/rules/tooling-and-review/preset-writing-style.md +8 -0
  81. package/presets/claude/mol/settings.json +15 -4
  82. package/presets/claude/next/CLAUDE.md +2 -4
  83. package/presets/claude/next/REPO_AGENTS.md +2 -0
  84. package/presets/claude/next/agents/feature-developer.md +1 -1
  85. package/presets/claude/next/agents/task-analyst.md +1 -7
  86. package/presets/claude/next/agents/task-router.md +1 -1
  87. package/presets/claude/next/ai-local/rules-library/commit-hygiene.md +1 -1
  88. package/presets/claude/next/commands/spec-start.md +3 -4
  89. package/presets/claude/next/commands/task-continue.md +9 -8
  90. package/presets/claude/next/commands/task-evil.md +8 -0
  91. package/presets/claude/next/commands/task.md +1 -1
  92. package/presets/claude/next/hooks/chain-team-phases.sh +541 -61
  93. package/presets/claude/next/hooks/guard-shell-command.mjs +733 -9
  94. package/presets/claude/next/hooks/prompt-autoroute.mjs +153 -0
  95. package/presets/claude/next/rules/tooling-and-review/agent-team-intake.md +2 -0
  96. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +2 -2
  97. package/presets/claude/next/rules/tooling-and-review/preset-writing-style.md +8 -0
  98. package/presets/claude/next/settings.json +15 -4
  99. package/presets/claude/next/team/README.md +1 -1
  100. package/presets/claude/nuxt/CLAUDE.md +2 -4
  101. package/presets/claude/nuxt/hooks/chain-team-phases.sh +541 -61
  102. package/presets/claude/nuxt/hooks/guard-shell-command.mjs +733 -9
  103. package/presets/claude/nuxt/hooks/prompt-autoroute.mjs +153 -0
  104. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-intake.md +2 -0
  105. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +2 -2
  106. package/presets/claude/nuxt/rules/tooling-and-review/preset-writing-style.md +8 -0
  107. package/presets/claude/nuxt/settings.json +15 -4
  108. package/presets/claude/php-hexagonal/CLAUDE.md +2 -4
  109. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +541 -61
  110. package/presets/claude/php-hexagonal/hooks/guard-shell-command.mjs +733 -9
  111. package/presets/claude/php-hexagonal/hooks/prompt-autoroute.mjs +153 -0
  112. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-intake.md +2 -0
  113. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +2 -2
  114. package/presets/claude/php-hexagonal/rules/tooling-and-review/preset-writing-style.md +8 -0
  115. package/presets/claude/php-hexagonal/settings.json +15 -5
  116. package/presets/claude/php-laravel/CLAUDE.md +2 -4
  117. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +541 -61
  118. package/presets/claude/php-laravel/hooks/guard-shell-command.mjs +733 -9
  119. package/presets/claude/php-laravel/hooks/prompt-autoroute.mjs +153 -0
  120. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-intake.md +2 -0
  121. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +2 -2
  122. package/presets/claude/php-laravel/rules/tooling-and-review/preset-writing-style.md +8 -0
  123. package/presets/claude/php-laravel/settings.json +15 -5
  124. package/presets/claude/svelte/CLAUDE.md +2 -4
  125. package/presets/claude/svelte/hooks/chain-team-phases.sh +541 -61
  126. package/presets/claude/svelte/hooks/guard-shell-command.mjs +733 -9
  127. package/presets/claude/svelte/hooks/prompt-autoroute.mjs +153 -0
  128. package/presets/claude/svelte/rules/tooling-and-review/agent-team-intake.md +2 -0
  129. package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +2 -2
  130. package/presets/claude/svelte/rules/tooling-and-review/preset-writing-style.md +8 -0
  131. package/presets/claude/svelte/settings.json +15 -4
  132. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +541 -61
  133. package/presets/cursor/android-kotlin/hooks/guard-shell-command.mjs +733 -9
  134. package/presets/cursor/android-kotlin/rules/agent-team-intake.mdc +2 -0
  135. package/presets/cursor/android-kotlin/rules/agent-team-orchestrator.mdc +1 -1
  136. package/presets/cursor/android-kotlin/rules/preset-writing-style.mdc +8 -0
  137. package/presets/cursor/go/hooks/chain-team-phases.sh +541 -61
  138. package/presets/cursor/go/hooks/guard-shell-command.mjs +733 -9
  139. package/presets/cursor/go/rules/agent-team-intake.mdc +2 -0
  140. package/presets/cursor/go/rules/agent-team-orchestrator.mdc +1 -1
  141. package/presets/cursor/go/rules/preset-writing-style.mdc +8 -0
  142. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +541 -61
  143. package/presets/cursor/ios-swift/hooks/guard-shell-command.mjs +733 -9
  144. package/presets/cursor/ios-swift/rules/agent-team-intake.mdc +2 -0
  145. package/presets/cursor/ios-swift/rules/agent-team-orchestrator.mdc +1 -1
  146. package/presets/cursor/ios-swift/rules/preset-writing-style.mdc +8 -0
  147. package/presets/cursor/java/hooks/chain-team-phases.sh +541 -61
  148. package/presets/cursor/java/hooks/guard-shell-command.mjs +733 -9
  149. package/presets/cursor/java/rules/agent-team-intake.mdc +2 -0
  150. package/presets/cursor/java/rules/agent-team-orchestrator.mdc +1 -1
  151. package/presets/cursor/java/rules/preset-writing-style.mdc +8 -0
  152. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +541 -61
  153. package/presets/cursor/mcp-ts/hooks/guard-shell-command.mjs +733 -9
  154. package/presets/cursor/mcp-ts/rules/agent-team-intake.mdc +2 -0
  155. package/presets/cursor/mcp-ts/rules/agent-team-orchestrator.mdc +1 -1
  156. package/presets/cursor/mcp-ts/rules/preset-writing-style.mdc +8 -0
  157. package/presets/cursor/mol/agents/feature-developer.md +1 -1
  158. package/presets/cursor/mol/ai-local/rules-library/commit-hygiene.md +1 -1
  159. package/presets/cursor/mol/commands/task-evil.md +8 -0
  160. package/presets/cursor/mol/hooks/chain-team-phases.sh +541 -61
  161. package/presets/cursor/mol/hooks/guard-shell-command.mjs +733 -9
  162. package/presets/cursor/mol/rules/agent-team-intake.mdc +2 -0
  163. package/presets/cursor/mol/rules/agent-team-orchestrator.mdc +1 -1
  164. package/presets/cursor/mol/rules/preset-writing-style.mdc +8 -0
  165. package/presets/cursor/next/REPO_AGENTS.md +2 -0
  166. package/presets/cursor/next/agents/feature-developer.md +1 -1
  167. package/presets/cursor/next/agents/task-analyst.md +1 -7
  168. package/presets/cursor/next/agents/task-router.md +1 -1
  169. package/presets/cursor/next/ai-local/rules-library/commit-hygiene.md +1 -1
  170. package/presets/cursor/next/commands/spec-start.md +3 -4
  171. package/presets/cursor/next/commands/task-continue.md +9 -8
  172. package/presets/cursor/next/commands/task-evil.md +8 -0
  173. package/presets/cursor/next/commands/task.md +1 -1
  174. package/presets/cursor/next/hooks/chain-team-phases.sh +541 -61
  175. package/presets/cursor/next/hooks/guard-shell-command.mjs +733 -9
  176. package/presets/cursor/next/rules/agent-team-intake.mdc +2 -0
  177. package/presets/cursor/next/rules/agent-team-orchestrator.mdc +2 -2
  178. package/presets/cursor/next/rules/preset-writing-style.mdc +8 -0
  179. package/presets/cursor/next/team/README.md +1 -1
  180. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +541 -61
  181. package/presets/cursor/nuxt/hooks/guard-shell-command.mjs +733 -9
  182. package/presets/cursor/nuxt/rules/agent-team-intake.mdc +2 -0
  183. package/presets/cursor/nuxt/rules/agent-team-orchestrator.mdc +1 -1
  184. package/presets/cursor/nuxt/rules/preset-writing-style.mdc +8 -0
  185. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +541 -61
  186. package/presets/cursor/php-hexagonal/hooks/guard-shell-command.mjs +733 -9
  187. package/presets/cursor/php-hexagonal/rules/agent-team-intake.mdc +2 -0
  188. package/presets/cursor/php-hexagonal/rules/agent-team-orchestrator.mdc +1 -1
  189. package/presets/cursor/php-hexagonal/rules/preset-writing-style.mdc +8 -0
  190. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +541 -61
  191. package/presets/cursor/php-laravel/hooks/guard-shell-command.mjs +733 -9
  192. package/presets/cursor/php-laravel/rules/agent-team-intake.mdc +2 -0
  193. package/presets/cursor/php-laravel/rules/agent-team-orchestrator.mdc +1 -1
  194. package/presets/cursor/php-laravel/rules/preset-writing-style.mdc +8 -0
  195. package/presets/cursor/svelte/hooks/chain-team-phases.sh +541 -61
  196. package/presets/cursor/svelte/hooks/guard-shell-command.mjs +733 -9
  197. package/presets/cursor/svelte/rules/agent-team-intake.mdc +2 -0
  198. package/presets/cursor/svelte/rules/agent-team-orchestrator.mdc +1 -1
  199. package/presets/cursor/svelte/rules/preset-writing-style.mdc +8 -0
  200. package/presets/mavis/android-kotlin/MAVIS.md +1 -1
  201. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  202. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +541 -61
  203. package/presets/mavis/android-kotlin/rules/agent-team-intake.md +2 -0
  204. package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +2 -2
  205. package/presets/mavis/android-kotlin/rules/preset-writing-style.md +8 -0
  206. package/presets/mavis/go/MAVIS.md +1 -1
  207. package/presets/mavis/go/adapter-map.json +1 -1
  208. package/presets/mavis/go/hooks/chain-team-phases.sh +541 -61
  209. package/presets/mavis/go/rules/agent-team-intake.md +2 -0
  210. package/presets/mavis/go/rules/agent-team-orchestrator.md +2 -2
  211. package/presets/mavis/go/rules/preset-writing-style.md +8 -0
  212. package/presets/mavis/ios-swift/MAVIS.md +1 -1
  213. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  214. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +541 -61
  215. package/presets/mavis/ios-swift/rules/agent-team-intake.md +2 -0
  216. package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +2 -2
  217. package/presets/mavis/ios-swift/rules/preset-writing-style.md +8 -0
  218. package/presets/mavis/java/MAVIS.md +1 -1
  219. package/presets/mavis/java/adapter-map.json +1 -1
  220. package/presets/mavis/java/hooks/chain-team-phases.sh +541 -61
  221. package/presets/mavis/java/rules/agent-team-intake.md +2 -0
  222. package/presets/mavis/java/rules/agent-team-orchestrator.md +2 -2
  223. package/presets/mavis/java/rules/preset-writing-style.md +8 -0
  224. package/presets/mavis/mcp-ts/MAVIS.md +1 -1
  225. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  226. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +541 -61
  227. package/presets/mavis/mcp-ts/rules/agent-team-intake.md +2 -0
  228. package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +2 -2
  229. package/presets/mavis/mcp-ts/rules/preset-writing-style.md +8 -0
  230. package/presets/mavis/mol/MAVIS.md +1 -1
  231. package/presets/mavis/mol/adapter-map.json +1 -1
  232. package/presets/mavis/mol/agents/feature-developer.md +1 -1
  233. package/presets/mavis/mol/ai-local/rules-library/commit-hygiene.md +1 -1
  234. package/presets/mavis/mol/commands/task-evil.md +8 -0
  235. package/presets/mavis/mol/hooks/chain-team-phases.sh +541 -61
  236. package/presets/mavis/mol/native-skills/task-evil/SKILL.md +8 -0
  237. package/presets/mavis/mol/rules/agent-team-intake.md +2 -0
  238. package/presets/mavis/mol/rules/agent-team-orchestrator.md +2 -2
  239. package/presets/mavis/mol/rules/preset-writing-style.md +8 -0
  240. package/presets/mavis/next/MAVIS.md +1 -1
  241. package/presets/mavis/next/REPO_AGENTS.md +2 -0
  242. package/presets/mavis/next/adapter-map.json +1 -1
  243. package/presets/mavis/next/agents/feature-developer.md +1 -1
  244. package/presets/mavis/next/agents/task-analyst.md +1 -7
  245. package/presets/mavis/next/agents/task-router.md +1 -1
  246. package/presets/mavis/next/ai-local/rules-library/commit-hygiene.md +1 -1
  247. package/presets/mavis/next/commands/spec-start.md +3 -4
  248. package/presets/mavis/next/commands/task-continue.md +9 -8
  249. package/presets/mavis/next/commands/task-evil.md +8 -0
  250. package/presets/mavis/next/commands/task.md +1 -1
  251. package/presets/mavis/next/hooks/chain-team-phases.sh +541 -61
  252. package/presets/mavis/next/native-skills/spec-start/SKILL.md +3 -4
  253. package/presets/mavis/next/native-skills/task/SKILL.md +1 -1
  254. package/presets/mavis/next/native-skills/task-continue/SKILL.md +9 -8
  255. package/presets/mavis/next/native-skills/task-evil/SKILL.md +8 -0
  256. package/presets/mavis/next/rules/agent-team-intake.md +2 -0
  257. package/presets/mavis/next/rules/agent-team-orchestrator.md +2 -2
  258. package/presets/mavis/next/rules/preset-writing-style.md +8 -0
  259. package/presets/mavis/next/team/README.md +1 -1
  260. package/presets/mavis/nuxt/MAVIS.md +1 -1
  261. package/presets/mavis/nuxt/adapter-map.json +1 -1
  262. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +541 -61
  263. package/presets/mavis/nuxt/rules/agent-team-intake.md +2 -0
  264. package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +2 -2
  265. package/presets/mavis/nuxt/rules/preset-writing-style.md +8 -0
  266. package/presets/mavis/php-hexagonal/MAVIS.md +1 -1
  267. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  268. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +541 -61
  269. package/presets/mavis/php-hexagonal/rules/agent-team-intake.md +2 -0
  270. package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +2 -2
  271. package/presets/mavis/php-hexagonal/rules/preset-writing-style.md +8 -0
  272. package/presets/mavis/php-laravel/MAVIS.md +1 -1
  273. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  274. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +541 -61
  275. package/presets/mavis/php-laravel/rules/agent-team-intake.md +2 -0
  276. package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +2 -2
  277. package/presets/mavis/php-laravel/rules/preset-writing-style.md +8 -0
  278. package/presets/mavis/svelte/MAVIS.md +1 -1
  279. package/presets/mavis/svelte/adapter-map.json +1 -1
  280. package/presets/mavis/svelte/hooks/chain-team-phases.sh +541 -61
  281. package/presets/mavis/svelte/rules/agent-team-intake.md +2 -0
  282. package/presets/mavis/svelte/rules/agent-team-orchestrator.md +2 -2
  283. package/presets/mavis/svelte/rules/preset-writing-style.md +8 -0
  284. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  285. package/presets/opencode/android-kotlin/hooks/README.md +6 -5
  286. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +541 -61
  287. package/presets/opencode/android-kotlin/hooks/guard-shell-command.mjs +733 -9
  288. package/presets/opencode/android-kotlin/opencode.json +4 -4
  289. package/presets/opencode/android-kotlin/rules/agent-team-intake.md +2 -0
  290. package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +2 -2
  291. package/presets/opencode/android-kotlin/rules/preset-writing-style.md +8 -0
  292. package/presets/opencode/go/adapter-map.json +1 -1
  293. package/presets/opencode/go/hooks/README.md +6 -5
  294. package/presets/opencode/go/hooks/chain-team-phases.sh +541 -61
  295. package/presets/opencode/go/hooks/guard-shell-command.mjs +733 -9
  296. package/presets/opencode/go/opencode.json +4 -4
  297. package/presets/opencode/go/rules/agent-team-intake.md +2 -0
  298. package/presets/opencode/go/rules/agent-team-orchestrator.md +2 -2
  299. package/presets/opencode/go/rules/preset-writing-style.md +8 -0
  300. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  301. package/presets/opencode/ios-swift/hooks/README.md +6 -5
  302. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +541 -61
  303. package/presets/opencode/ios-swift/hooks/guard-shell-command.mjs +733 -9
  304. package/presets/opencode/ios-swift/opencode.json +4 -4
  305. package/presets/opencode/ios-swift/rules/agent-team-intake.md +2 -0
  306. package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +2 -2
  307. package/presets/opencode/ios-swift/rules/preset-writing-style.md +8 -0
  308. package/presets/opencode/java/adapter-map.json +1 -1
  309. package/presets/opencode/java/hooks/README.md +6 -5
  310. package/presets/opencode/java/hooks/chain-team-phases.sh +541 -61
  311. package/presets/opencode/java/hooks/guard-shell-command.mjs +733 -9
  312. package/presets/opencode/java/opencode.json +4 -4
  313. package/presets/opencode/java/rules/agent-team-intake.md +2 -0
  314. package/presets/opencode/java/rules/agent-team-orchestrator.md +2 -2
  315. package/presets/opencode/java/rules/preset-writing-style.md +8 -0
  316. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  317. package/presets/opencode/mcp-ts/hooks/README.md +6 -5
  318. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +541 -61
  319. package/presets/opencode/mcp-ts/hooks/guard-shell-command.mjs +733 -9
  320. package/presets/opencode/mcp-ts/opencode.json +4 -4
  321. package/presets/opencode/mcp-ts/rules/agent-team-intake.md +2 -0
  322. package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +2 -2
  323. package/presets/opencode/mcp-ts/rules/preset-writing-style.md +8 -0
  324. package/presets/opencode/mol/adapter-map.json +1 -1
  325. package/presets/opencode/mol/agents/feature-developer.md +1 -1
  326. package/presets/opencode/mol/ai-local/rules-library/commit-hygiene.md +1 -1
  327. package/presets/opencode/mol/commands/task-evil.md +8 -0
  328. package/presets/opencode/mol/hooks/README.md +6 -5
  329. package/presets/opencode/mol/hooks/chain-team-phases.sh +541 -61
  330. package/presets/opencode/mol/hooks/guard-shell-command.mjs +733 -9
  331. package/presets/opencode/mol/opencode.json +4 -4
  332. package/presets/opencode/mol/rules/agent-team-intake.md +2 -0
  333. package/presets/opencode/mol/rules/agent-team-orchestrator.md +2 -2
  334. package/presets/opencode/mol/rules/preset-writing-style.md +8 -0
  335. package/presets/opencode/next/REPO_AGENTS.md +2 -0
  336. package/presets/opencode/next/adapter-map.json +1 -1
  337. package/presets/opencode/next/agents/feature-developer.md +1 -1
  338. package/presets/opencode/next/agents/task-analyst.md +1 -7
  339. package/presets/opencode/next/agents/task-router.md +1 -1
  340. package/presets/opencode/next/ai-local/rules-library/commit-hygiene.md +1 -1
  341. package/presets/opencode/next/commands/spec-start.md +3 -4
  342. package/presets/opencode/next/commands/task-continue.md +9 -8
  343. package/presets/opencode/next/commands/task-evil.md +8 -0
  344. package/presets/opencode/next/commands/task.md +1 -1
  345. package/presets/opencode/next/hooks/README.md +6 -5
  346. package/presets/opencode/next/hooks/chain-team-phases.sh +541 -61
  347. package/presets/opencode/next/hooks/guard-shell-command.mjs +733 -9
  348. package/presets/opencode/next/opencode.json +4 -4
  349. package/presets/opencode/next/rules/agent-team-intake.md +2 -0
  350. package/presets/opencode/next/rules/agent-team-orchestrator.md +2 -2
  351. package/presets/opencode/next/rules/preset-writing-style.md +8 -0
  352. package/presets/opencode/next/team/README.md +1 -1
  353. package/presets/opencode/nuxt/adapter-map.json +1 -1
  354. package/presets/opencode/nuxt/hooks/README.md +6 -5
  355. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +541 -61
  356. package/presets/opencode/nuxt/hooks/guard-shell-command.mjs +733 -9
  357. package/presets/opencode/nuxt/opencode.json +4 -4
  358. package/presets/opencode/nuxt/rules/agent-team-intake.md +2 -0
  359. package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +2 -2
  360. package/presets/opencode/nuxt/rules/preset-writing-style.md +8 -0
  361. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  362. package/presets/opencode/php-hexagonal/hooks/README.md +6 -5
  363. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +541 -61
  364. package/presets/opencode/php-hexagonal/hooks/guard-shell-command.mjs +733 -9
  365. package/presets/opencode/php-hexagonal/opencode.json +4 -4
  366. package/presets/opencode/php-hexagonal/rules/agent-team-intake.md +2 -0
  367. package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +2 -2
  368. package/presets/opencode/php-hexagonal/rules/preset-writing-style.md +8 -0
  369. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  370. package/presets/opencode/php-laravel/hooks/README.md +6 -5
  371. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +541 -61
  372. package/presets/opencode/php-laravel/hooks/guard-shell-command.mjs +733 -9
  373. package/presets/opencode/php-laravel/opencode.json +4 -4
  374. package/presets/opencode/php-laravel/rules/agent-team-intake.md +2 -0
  375. package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +2 -2
  376. package/presets/opencode/php-laravel/rules/preset-writing-style.md +8 -0
  377. package/presets/opencode/plugins/output-guard/README.md +4 -3
  378. package/presets/opencode/plugins/output-guard/index.ts +4 -3
  379. package/presets/opencode/plugins/output-guard/rewrite.ts +1 -2
  380. package/presets/opencode/plugins/rule-attach/README.md +1 -1
  381. package/presets/opencode/plugins/rule-attach/index.ts +23 -4
  382. package/presets/opencode/plugins/settings-guard/README.md +28 -0
  383. package/presets/opencode/plugins/settings-guard/index.ts +114 -0
  384. package/presets/opencode/plugins/settings-guard/package.json +9 -0
  385. package/presets/opencode/plugins/settings-guard/policy.mjs +85 -0
  386. package/presets/opencode/plugins/settings-guard/prompt-face.mjs +153 -0
  387. package/presets/opencode/plugins/task-status/README.md +13 -8
  388. package/presets/opencode/plugins/task-status/deepseek.ts +23 -8
  389. package/presets/opencode/plugins/task-status/eta.ts +20 -7
  390. package/presets/opencode/plugins/task-status/index.ts +14 -1
  391. package/presets/opencode/plugins/task-status/task-view.ts +168 -9
  392. package/presets/opencode/plugins/task-status/timing.ts +244 -0
  393. package/presets/opencode/plugins/task-status/tui.tsx +12 -3
  394. package/presets/opencode/plugins/task-status/types.ts +6 -0
  395. package/presets/opencode/svelte/adapter-map.json +1 -1
  396. package/presets/opencode/svelte/hooks/README.md +6 -5
  397. package/presets/opencode/svelte/hooks/chain-team-phases.sh +541 -61
  398. package/presets/opencode/svelte/hooks/guard-shell-command.mjs +733 -9
  399. package/presets/opencode/svelte/opencode.json +4 -4
  400. package/presets/opencode/svelte/rules/agent-team-intake.md +2 -0
  401. package/presets/opencode/svelte/rules/agent-team-orchestrator.md +2 -2
  402. package/presets/opencode/svelte/rules/preset-writing-style.md +8 -0
  403. package/presets/zcode/android-kotlin/adapter-map.json +1 -1
  404. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +541 -61
  405. package/presets/zcode/android-kotlin/rules/agent-team-intake.md +2 -0
  406. package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +2 -2
  407. package/presets/zcode/android-kotlin/rules/preset-writing-style.md +8 -0
  408. package/presets/zcode/go/adapter-map.json +1 -1
  409. package/presets/zcode/go/hooks/chain-team-phases.sh +541 -61
  410. package/presets/zcode/go/rules/agent-team-intake.md +2 -0
  411. package/presets/zcode/go/rules/agent-team-orchestrator.md +2 -2
  412. package/presets/zcode/go/rules/preset-writing-style.md +8 -0
  413. package/presets/zcode/ios-swift/adapter-map.json +1 -1
  414. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +541 -61
  415. package/presets/zcode/ios-swift/rules/agent-team-intake.md +2 -0
  416. package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +2 -2
  417. package/presets/zcode/ios-swift/rules/preset-writing-style.md +8 -0
  418. package/presets/zcode/java/adapter-map.json +1 -1
  419. package/presets/zcode/java/hooks/chain-team-phases.sh +541 -61
  420. package/presets/zcode/java/rules/agent-team-intake.md +2 -0
  421. package/presets/zcode/java/rules/agent-team-orchestrator.md +2 -2
  422. package/presets/zcode/java/rules/preset-writing-style.md +8 -0
  423. package/presets/zcode/mcp-ts/adapter-map.json +1 -1
  424. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +541 -61
  425. package/presets/zcode/mcp-ts/rules/agent-team-intake.md +2 -0
  426. package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +2 -2
  427. package/presets/zcode/mcp-ts/rules/preset-writing-style.md +8 -0
  428. package/presets/zcode/mol/adapter-map.json +1 -1
  429. package/presets/zcode/mol/agents/feature-developer.md +1 -1
  430. package/presets/zcode/mol/ai-local/rules-library/commit-hygiene.md +1 -1
  431. package/presets/zcode/mol/commands/task-evil.md +8 -0
  432. package/presets/zcode/mol/hooks/chain-team-phases.sh +541 -61
  433. package/presets/zcode/mol/rules/agent-team-intake.md +2 -0
  434. package/presets/zcode/mol/rules/agent-team-orchestrator.md +2 -2
  435. package/presets/zcode/mol/rules/preset-writing-style.md +8 -0
  436. package/presets/zcode/next/REPO_AGENTS.md +2 -0
  437. package/presets/zcode/next/adapter-map.json +1 -1
  438. package/presets/zcode/next/agents/feature-developer.md +1 -1
  439. package/presets/zcode/next/agents/task-analyst.md +1 -7
  440. package/presets/zcode/next/agents/task-router.md +1 -1
  441. package/presets/zcode/next/ai-local/rules-library/commit-hygiene.md +1 -1
  442. package/presets/zcode/next/commands/spec-start.md +3 -4
  443. package/presets/zcode/next/commands/task-continue.md +9 -8
  444. package/presets/zcode/next/commands/task-evil.md +8 -0
  445. package/presets/zcode/next/commands/task.md +1 -1
  446. package/presets/zcode/next/hooks/chain-team-phases.sh +541 -61
  447. package/presets/zcode/next/rules/agent-team-intake.md +2 -0
  448. package/presets/zcode/next/rules/agent-team-orchestrator.md +2 -2
  449. package/presets/zcode/next/rules/preset-writing-style.md +8 -0
  450. package/presets/zcode/next/team/README.md +1 -1
  451. package/presets/zcode/nuxt/adapter-map.json +1 -1
  452. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +541 -61
  453. package/presets/zcode/nuxt/rules/agent-team-intake.md +2 -0
  454. package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +2 -2
  455. package/presets/zcode/nuxt/rules/preset-writing-style.md +8 -0
  456. package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
  457. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +541 -61
  458. package/presets/zcode/php-hexagonal/rules/agent-team-intake.md +2 -0
  459. package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +2 -2
  460. package/presets/zcode/php-hexagonal/rules/preset-writing-style.md +8 -0
  461. package/presets/zcode/php-laravel/adapter-map.json +1 -1
  462. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +541 -61
  463. package/presets/zcode/php-laravel/rules/agent-team-intake.md +2 -0
  464. package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +2 -2
  465. package/presets/zcode/php-laravel/rules/preset-writing-style.md +8 -0
  466. package/presets/zcode/svelte/adapter-map.json +1 -1
  467. package/presets/zcode/svelte/hooks/chain-team-phases.sh +541 -61
  468. package/presets/zcode/svelte/rules/agent-team-intake.md +2 -0
  469. package/presets/zcode/svelte/rules/agent-team-orchestrator.md +2 -2
  470. package/presets/zcode/svelte/rules/preset-writing-style.md +8 -0
@@ -10,7 +10,10 @@ const fs = require('fs');
10
10
  const path = require('path');
11
11
  const crypto = require('crypto');
12
12
 
13
- const TEAM_ROOT = path.join(process.cwd(), '.ai.local', 'team');
13
+ // Worktree hooks set AI_RULES_TEAM_ROOT so cwd does not open a second store.
14
+ const TEAM_ROOT = process.env.AI_RULES_TEAM_ROOT
15
+ ? path.resolve(process.env.AI_RULES_TEAM_ROOT)
16
+ : path.join(process.cwd(), '.ai.local', 'team');
14
17
 
15
18
  const inputRaw = process.env.INPUT || '';
16
19
  let hookInput;
@@ -36,11 +39,15 @@ if (hookInput.status !== 'completed') {
36
39
  // Slug resolution, strongest first:
37
40
  // 1. TEAM_TASK_SLUG — the orchestrator's explicit binding for this call.
38
41
  // 2. the per-session lease `.ai.local/team/.session-leases/<session>.json`,
39
- // written by an earlier call that carried (1) in the same host session.
40
- // 3. active-task.json — a single-slot fallback for the UI and older hosts;
41
- // parallel sessions overwrite it, so a miss is reported on stderr.
42
- // Only (1) writes the lease: a fallback-derived slug must never become this
43
- // session's binding, or one session would inherit another's task.
42
+ // written by an earlier call that carried (1), or by the OpenCode
43
+ // task-status plugin when it pinned this tab.
44
+ // 3. active-task.json — a UI projection of the live slugs (rebuilt by
45
+ // `team-db sync`), read only as a fallback for older hosts; when more
46
+ // than one slug is live the resolution is ambiguous and refused below.
47
+ // Only (1) writes the lease from this hook. The OpenCode task-status plugin
48
+ // writes the same file when it pins a tab, and `shell.env` injects the session
49
+ // id so this lookup sees that pin. A pointer fallback never writes a lease:
50
+ // that would let one session inherit another's task.
44
51
  const SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
45
52
  const LEASE_ROOT = path.join(TEAM_ROOT, '.session-leases');
46
53
  const LEASE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
@@ -104,21 +111,24 @@ if (!slug && sessionId) {
104
111
  }
105
112
  }
106
113
  if (!slug) {
107
- const activePath = path.join(TEAM_ROOT, 'active-task.json');
108
-
109
- if (!fs.existsSync(activePath)) {
110
- process.stdout.write('{}');
111
- process.exit(0);
112
- }
113
-
114
- let active;
114
+ let active = null;
115
115
  try {
116
- active = JSON.parse(fs.readFileSync(activePath, 'utf8'));
116
+ active = JSON.parse(fs.readFileSync(path.join(TEAM_ROOT, 'active-task.json'), 'utf8'));
117
117
  } catch {
118
+ active = null;
119
+ }
120
+ // Back-compat reader: the projection shape `{"slugs": [...]}` (rebuilt by
121
+ // `team-db sync`) and the legacy single-slot `{"slug"}` shape are accepted
122
+ // forever. An empty or unreadable projection is identical to a missing
123
+ // file: a `{}` no-op.
124
+ const pointerSlugs = active && Array.isArray(active.slugs)
125
+ ? active.slugs
126
+ : (active && typeof active.slug === 'string' && active.slug ? [active.slug] : []);
127
+ if (pointerSlugs.length === 0) {
118
128
  process.stdout.write('{}');
119
129
  process.exit(0);
120
130
  }
121
- slug = active.slug;
131
+ slug = pointerSlugs[0];
122
132
  slugSource = 'active-task.json';
123
133
  }
124
134
  // Reject non-kebab / traversal slugs: the runtime writes status.json and
@@ -128,6 +138,44 @@ if (typeof slug !== 'string' || slug.length > 48 || !SLUG_RE.test(slug)) {
128
138
  process.stdout.write('{}');
129
139
  process.exit(0);
130
140
  }
141
+ // Canonical live-slug scan over the task store, never the pointer: a slug is
142
+ // live when `tasks/<name>/status.json` parses and its state is not terminal.
143
+ const TERMINAL_STATES = new Set(['completed', 'blocked', 'changes_requested', 'validation_failed']);
144
+ function liveSlugs() {
145
+ const tasksDir = path.join(TEAM_ROOT, 'tasks');
146
+ let entries;
147
+ try {
148
+ entries = fs.readdirSync(tasksDir, { withFileTypes: true });
149
+ } catch {
150
+ return [];
151
+ }
152
+ const live = [];
153
+ for (const entry of entries) {
154
+ if (!entry.isDirectory()) continue;
155
+ try {
156
+ const status = JSON.parse(fs.readFileSync(path.join(tasksDir, entry.name, 'status.json'), 'utf8'));
157
+ if (status && typeof status.state === 'string' && !TERMINAL_STATES.has(status.state)) live.push(entry.name);
158
+ } catch {}
159
+ }
160
+ return live.sort();
161
+ }
162
+ // Level-3 (pointer) resolution guard: when the slug came from
163
+ // active-task.json and any other live slug exists, the pointer cannot say
164
+ // which task this call belongs to. Refuse loudly — `ok:false` with exit 0,
165
+ // the hook's refusal convention (a non-zero exit would be read as a blocking
166
+ // platform error by Stop-class hook consumers) — so the caller re-runs with
167
+ // `TEAM_TASK_SLUG=<slug>` instead of silently acting on the wrong task.
168
+ // Exactly one live slug keeps today's warning-only behaviour, so older hosts
169
+ // keep working until they pass the env.
170
+ if (slugSource === 'active-task.json') {
171
+ const live = liveSlugs();
172
+ if (live.some((name) => name !== slug)) {
173
+ const shown = live.slice(0, 5).join(', ');
174
+ process.stderr.write(`ERROR: ${slug}: active-task.json is ambiguous — ${live.length} live slugs (${shown}${live.length > 5 ? ', max 5 shown' : ''}); pass TEAM_TASK_SLUG=<slug> on every hook call.\n`);
175
+ process.stdout.write(JSON.stringify({ ok: false, reason: 'active-task-pointer-ambiguous', slug, liveSlugs: live }));
176
+ process.exit(0);
177
+ }
178
+ }
131
179
  if (slugSource !== 'TEAM_TASK_SLUG') {
132
180
  process.stderr.write(`WARNING: ${slug}: chain hook resolved the slug from ${slugSource}; pass TEAM_TASK_SLUG=<slug> on every hook call so parallel sessions cannot no-op each other.\n`);
133
181
  }
@@ -297,6 +345,86 @@ function attemptStaleMs() {
297
345
  const value = Number(raw);
298
346
  return Number.isFinite(value) && value >= MIN_ATTEMPT_STALE_MS ? value : DEFAULT_ATTEMPT_STALE_MS;
299
347
  }
348
+ // Work a single attempt may claim. Wall time beyond it is suspension, a hang, or
349
+ // a stop that arrived days after the agent died, and it is recorded as idle.
350
+ const DEFAULT_ATTEMPT_MAX_MS = 4 * 60 * 60 * 1000;
351
+ const MIN_ATTEMPT_MAX_MS = 10 * 60 * 1000;
352
+ function attemptMaxMs() {
353
+ const raw = process.env.AI_RULES_ATTEMPT_MAX_MS;
354
+ if (typeof raw !== 'string' || raw.trim() === '') return DEFAULT_ATTEMPT_MAX_MS;
355
+ const value = Number(raw);
356
+ return Number.isFinite(value) && value >= MIN_ATTEMPT_MAX_MS ? value : DEFAULT_ATTEMPT_MAX_MS;
357
+ }
358
+ // Intervals appended by the sidebar's suspend detector: the host did not run, so
359
+ // the attempt did not work. Written as JSONL, one { from, to } per line.
360
+ function readSuspendIntervals() {
361
+ const file = path.join(taskDir, '.suspend.jsonl');
362
+ let raw;
363
+ try { raw = fs.readFileSync(file, 'utf8'); } catch { return []; }
364
+ const intervals = [];
365
+ for (const line of raw.split('\n')) {
366
+ const trimmed = line.trim();
367
+ if (trimmed === '') continue;
368
+ try {
369
+ const row = JSON.parse(trimmed);
370
+ const from = Date.parse(row && row.from);
371
+ const to = Date.parse(row && row.to);
372
+ if (Number.isFinite(from) && Number.isFinite(to) && to > from) intervals.push([from, to]);
373
+ } catch { /* a torn last line is re-read when the file grows */ }
374
+ }
375
+ return intervals;
376
+ }
377
+ function unionOverlapMs(intervals, from, to) {
378
+ if (!Number.isFinite(from) || !Number.isFinite(to) || to <= from) return 0;
379
+ const sorted = intervals
380
+ .filter((pair) => Array.isArray(pair) && Number.isFinite(pair[0]) && Number.isFinite(pair[1]) && pair[1] > pair[0])
381
+ .sort((left, right) => left[0] - right[0]);
382
+ let total = 0;
383
+ let cursor = from;
384
+ for (const [start, end] of sorted) {
385
+ const overlapStart = Math.max(start, from, cursor);
386
+ const overlapEnd = Math.min(end, to);
387
+ if (overlapEnd <= overlapStart) continue;
388
+ total += overlapEnd - overlapStart;
389
+ cursor = overlapEnd;
390
+ }
391
+ return total;
392
+ }
393
+ // Everything the ledger can prove was not work: a gate, an operator pause, a
394
+ // host suspension. Attempt wall time minus this is the attempt's active time.
395
+ function attemptIdleMs(startedAtMs, endedAtMs, events) {
396
+ const intervals = readSuspendIntervals();
397
+ // The sentinel is the control plane: it is engaged before `task_paused` is
398
+ // written, so a stop that notices it must still charge the wait as idle.
399
+ const livePause = readPauseSentinel();
400
+ if (livePause.engaged && livePause.at) {
401
+ intervals.push([Date.parse(livePause.at), endedAtMs]);
402
+ }
403
+ const gates = new Map();
404
+ for (const event of events) {
405
+ if (event && event.type === 'human_gate_started' && event.eventId) gates.set(event.eventId, Date.parse(event.at));
406
+ }
407
+ for (const event of events) {
408
+ if (!event) continue;
409
+ if (event.type === 'human_gate_ended' && event.gateStartedEventId) {
410
+ const start = gates.get(event.gateStartedEventId);
411
+ const end = Date.parse(event.at);
412
+ if (Number.isFinite(start) && Number.isFinite(end)) intervals.push([start, end]);
413
+ }
414
+ }
415
+ let openPause = null;
416
+ for (const event of events) {
417
+ if (!event) continue;
418
+ if (event.type === 'task_paused') openPause = Date.parse(event.at);
419
+ if (event.type === 'task_resumed' && openPause !== null) {
420
+ const end = Date.parse(event.at);
421
+ if (Number.isFinite(end) && end > openPause) intervals.push([openPause, end]);
422
+ openPause = null;
423
+ }
424
+ }
425
+ if (openPause !== null && Number.isFinite(openPause)) intervals.push([openPause, endedAtMs]);
426
+ return unionOverlapMs(intervals, startedAtMs, endedAtMs);
427
+ }
300
428
  function hasTerminalReceipt(attemptId, entry) {
301
429
  const manifestPath = path.join(taskDir, 'artifact-manifest.json');
302
430
  if (!fs.existsSync(manifestPath)) return false;
@@ -354,6 +482,9 @@ function reclaimStaleAttempts(scope) {
354
482
  role: roleFor(entry.agent),
355
483
  outcome: 'stale',
356
484
  durationMs: ageMs,
485
+ wallMs: ageMs,
486
+ activeMs: Math.min(ageMs, attemptMaxMs()),
487
+ idleMs: Math.max(0, ageMs - Math.min(ageMs, attemptMaxMs())),
357
488
  retryAfterFix: status.retryAfterFix || null,
358
489
  source: 'hook',
359
490
  attributionConfidence: 'high',
@@ -1202,7 +1333,33 @@ function sanitizeUsage(value) {
1202
1333
  /**
1203
1334
  * Freshness of a persisted verification snapshot against the current worktree.
1204
1335
  * Read-only: closure warns, it never blocks on a stale snapshot.
1336
+ *
1337
+ * Task scoping: with the slug's write-scope step baselines
1338
+ * (`.write-scope/<slug>/*.json`) the evidence hash covers the union of the
1339
+ * baselines' recorded paths only, so another live slug's uncommitted work
1340
+ * cannot stale this task's evidence. Known limit: a file created after baseline
1341
+ * activation outside the claimed path set is invisible to `scopeHash`; the
1342
+ * write-scope audit and `check:task` still attribute such files at gate time
1343
+ * (content-hash delta). The scoped hash is a change detector, not an
1344
+ * attribution tool. `environmentHash` (renamed from `worktreeHash`) keeps the
1345
+ * whole-tree capture as diagnostics only.
1205
1346
  */
1347
+ function writeScopeBaselinePaths(dir) {
1348
+ let entries;
1349
+ try { entries = fs.readdirSync(dir); } catch { return null; }
1350
+ const paths = new Set();
1351
+ for (const entry of entries) {
1352
+ if (!entry.endsWith('.json')) continue;
1353
+ let parsed = null;
1354
+ try { parsed = JSON.parse(fs.readFileSync(path.join(dir, entry), 'utf8')); } catch { parsed = null; }
1355
+ const record = parsed && typeof parsed === 'object' && parsed.paths && typeof parsed.paths === 'object' && !Array.isArray(parsed.paths) ? parsed.paths : null;
1356
+ if (!record) continue;
1357
+ for (const key of Object.keys(record)) {
1358
+ if (typeof key === 'string' && key !== '') paths.add(key.split(path.sep).join('/'));
1359
+ }
1360
+ }
1361
+ return paths.size > 0 ? [...paths].sort() : null;
1362
+ }
1206
1363
  function gitSnapshot() {
1207
1364
  const { spawnSync } = require('child_process');
1208
1365
  const git = (args) => {
@@ -1216,11 +1373,30 @@ function gitSnapshot() {
1216
1373
  const statusText = git(['status', '--porcelain=v1', ...exclude]) || '';
1217
1374
  const diffText = git(['diff', '--binary', 'HEAD', ...exclude]) || '';
1218
1375
  const untracked = git(['ls-files', '--others', '--exclude-standard', ...exclude]) || '';
1376
+ const baselinePaths = typeof slug === 'string' && slug !== '' && SLUG_RE.test(slug)
1377
+ ? writeScopeBaselinePaths(path.join(TEAM_ROOT, '.write-scope', slug))
1378
+ : null;
1379
+ const liveCount = liveSlugs().length;
1380
+ let scopeBasis = 'none';
1381
+ let scopeHash = null;
1382
+ if (baselinePaths !== null) {
1383
+ scopeBasis = 'write-scope';
1384
+ const spec = ['--', ...baselinePaths];
1385
+ const scopedStatus = git(['status', '--porcelain=v1', ...spec]) || '';
1386
+ const scopedDiff = git(['diff', '--binary', 'HEAD', ...spec]) || '';
1387
+ const scopedUntracked = git(['ls-files', '--others', '--exclude-standard', ...spec]) || '';
1388
+ scopeHash = crypto.createHash('sha256').update(`${scopedStatus}\u0000${scopedDiff}\u0000${scopedUntracked}`).digest('hex');
1389
+ } else if (liveCount <= 1) {
1390
+ scopeBasis = 'whole-tree';
1391
+ }
1219
1392
  return {
1220
1393
  head: head.trim(),
1221
1394
  branch: branch === null ? null : branch.trim(),
1222
1395
  dirtyFiles: statusText === '' ? 0 : statusText.split('\n').filter((line) => line !== '').length,
1223
- worktreeHash: crypto.createHash('sha256').update(`${statusText}\u0000${diffText}\u0000${untracked}`).digest('hex'),
1396
+ environmentHash: crypto.createHash('sha256').update(`${statusText}\u0000${diffText}\u0000${untracked}`).digest('hex'),
1397
+ scopeBasis,
1398
+ scopePaths: baselinePaths === null ? 0 : baselinePaths.length,
1399
+ scopeHash,
1224
1400
  capturedAt: now,
1225
1401
  };
1226
1402
  }
@@ -1309,7 +1485,7 @@ function ensureVerificationSnapshot(dir, agent) {
1309
1485
  fs.writeFileSync(temporary, JSON.stringify(verification, null, 2) + '\n');
1310
1486
  fs.renameSync(temporary, file);
1311
1487
  });
1312
- appendMetric({ type: 'verification_recorded', at: now, kind: 'snapshot-only', agent: agent || null, head: snapshot.head, worktreeHash: snapshot.worktreeHash, source: 'hook', attributionConfidence: 'high' });
1488
+ appendMetric({ type: 'verification_recorded', at: now, kind: 'snapshot-only', agent: agent || null, head: snapshot.head, environmentHash: snapshot.environmentHash, source: 'hook', attributionConfidence: 'high' });
1313
1489
  }
1314
1490
 
1315
1491
  function verificationFreshness(dir) {
@@ -1324,15 +1500,34 @@ function verificationFreshness(dir) {
1324
1500
  // Judge the report the gate judges: its `tree:` header, not the wider worktree
1325
1501
  // hash. A later edit inside the same report generation moved the hash while the
1326
1502
  // gate still accepted the report, so the same fresh evidence warned twice.
1503
+ // The head comparison stays global (HEAD is shared across live slugs); the
1504
+ // dirty/hash dimension binds to the task's `scopeHash` when the evidence was
1505
+ // captured on a `write-scope` basis — the header's dirty count is a whole-tree
1506
+ // number and is not comparable to a scoped one, so the scoped hash is the
1507
+ // binding check for that basis, and a scope that can no longer be recomputed
1508
+ // reports `scope-unbound` (loud not-fresh, never a false fresh). Legacy
1509
+ // snapshots (no `scopeBasis`) and `whole-tree` snapshots keep today's
1510
+ // whole-tree comparison, reading the renamed field as
1511
+ // `environmentHash ?? worktreeHash`.
1327
1512
  const found = evidenceReportText(dir);
1328
1513
  const header = found === null ? null : found.text.match(REPORT_TREE_RE);
1329
1514
  const reasons = [];
1330
1515
  if (header) {
1331
1516
  if (!current.head.startsWith(header[1])) reasons.push('head-changed');
1332
- if (Number(header[2]) !== current.dirtyFiles) reasons.push('worktree-changed');
1333
1517
  } else {
1334
1518
  if (current.head !== snapshot.head) reasons.push('head-changed');
1335
- if (current.worktreeHash !== snapshot.worktreeHash) reasons.push('worktree-changed');
1519
+ }
1520
+ const basis = typeof snapshot.scopeBasis === 'string' ? snapshot.scopeBasis : 'legacy';
1521
+ if (basis === 'write-scope') {
1522
+ if (current.scopeBasis !== 'write-scope') reasons.push('scope-unbound');
1523
+ else if (current.scopeHash !== snapshot.scopeHash) reasons.push('worktree-changed');
1524
+ } else if (basis === 'none') {
1525
+ reasons.push('scope-unbound');
1526
+ } else if (header) {
1527
+ if (Number(header[2]) !== current.dirtyFiles) reasons.push('worktree-changed');
1528
+ } else {
1529
+ const recorded = typeof snapshot.environmentHash === 'string' ? snapshot.environmentHash : snapshot.worktreeHash;
1530
+ if (current.environmentHash !== recorded) reasons.push('worktree-changed');
1336
1531
  }
1337
1532
  return { present: true, fresh: reasons.length === 0, reasons };
1338
1533
  }
@@ -1351,10 +1546,32 @@ function noteVerificationFreshness(dir, agent) {
1351
1546
 
1352
1547
  function finishActiveAttempt(forced) {
1353
1548
  const resolved = forced || resolvedAttempt(); if (!resolved) return null;
1354
- const durationMs = Date.parse(now) - Date.parse(resolved.entry.startedAt);
1549
+ const startedAtMs = Date.parse(resolved.entry.startedAt);
1550
+ const endedAtMs = Date.parse(now);
1551
+ const wallMs = Number.isFinite(startedAtMs) && Number.isFinite(endedAtMs) ? Math.max(0, endedAtMs - startedAtMs) : null;
1552
+ // Suspension, a gate or an operator pause inside the attempt is not work.
1553
+ const nonWorkMs = wallMs === null ? null : attemptIdleMs(startedAtMs, endedAtMs, readMetricsEvents());
1554
+ // `idleMs` is the remainder, not only the proven intervals: wall = active + idle.
1555
+ const activeMs = wallMs === null ? null : Math.min(Math.max(0, wallMs - nonWorkMs), attemptMaxMs());
1556
+ const idleMs = wallMs === null ? null : Math.max(0, wallMs - (activeMs ?? 0));
1355
1557
  const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
1356
1558
  const usage = sanitizeUsage(hookInput.usage);
1357
- appendMetric({ type: 'attempt_finished', at: now, attemptId: resolved.attemptId, outcome, durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : null, retryAfterFix: status.retryAfterFix || null, source: resolved.source || 'hook', attributionConfidence: resolved.confidence, ...(usage ? { usage } : {}) });
1559
+ appendMetric({
1560
+ type: 'attempt_finished',
1561
+ at: now,
1562
+ attemptId: resolved.attemptId,
1563
+ stepIndex: typeof resolved.entry.stepIndex === 'number' ? resolved.entry.stepIndex : null,
1564
+ agent: resolved.entry.agent || null,
1565
+ outcome,
1566
+ durationMs: wallMs,
1567
+ wallMs,
1568
+ activeMs,
1569
+ idleMs,
1570
+ retryAfterFix: status.retryAfterFix || null,
1571
+ source: resolved.source || 'hook',
1572
+ attributionConfidence: resolved.confidence,
1573
+ ...(usage ? { usage } : {}),
1574
+ });
1358
1575
  if (resolved.entry && resolved.entry.agent === 'build-verifier') { ensureVerificationSnapshot(taskDir, resolved.entry.agent); noteVerificationFreshness(taskDir, resolved.entry.agent); }
1359
1576
  const active = { ...(status.activeAttempts || {}) }; delete active[resolved.attemptId]; status.activeAttempts = active; status.lastCompletedAttempt = { attemptId: resolved.attemptId, completedAt: now }; return { ...resolved, outcome };
1360
1577
  }
@@ -1431,10 +1648,38 @@ function completePipeline(statusPatch) {
1431
1648
  out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);
1432
1649
  process.exit(0);
1433
1650
  }
1434
- function beginHumanGate() { const eventId = `${status.metricsRunId || slug}:gate:${Date.now()}`; appendMetric({ eventId, type: 'human_gate_started', at: now, source: 'hook', attributionConfidence: 'high' }); status.activeHumanGateEventId = eventId; }
1651
+ function beginHumanGate() {
1652
+ // A second stop for the same gate must not open a parallel one: the wait
1653
+ // would be counted twice and the pairing lost.
1654
+ if (status.activeHumanGateEventId && status.awaitingHumanGate) return;
1655
+ const eventId = `${status.metricsRunId || slug}:gate:${Date.now()}`;
1656
+ appendMetric({
1657
+ eventId,
1658
+ type: 'human_gate_started',
1659
+ at: now,
1660
+ stepIndex: typeof status.pipelineIndex === 'number' ? status.pipelineIndex : null,
1661
+ agent: status.currentAgent || null,
1662
+ source: 'hook',
1663
+ attributionConfidence: 'high',
1664
+ });
1665
+ status.activeHumanGateEventId = eventId;
1666
+ }
1435
1667
  function endHumanGateIfResumed() {
1436
1668
  if (!status.activeHumanGateEventId || status.awaitingHumanGate || status.state === 'awaiting_approval') return;
1437
- appendMetric({ type: 'human_gate_ended', at: now, gateStartedEventId: status.activeHumanGateEventId, source: 'hook', attributionConfidence: 'high' });
1669
+ const events = readMetricsEvents();
1670
+ const started = events.find((event) => event && event.type === 'human_gate_started' && event.eventId === status.activeHumanGateEventId);
1671
+ const startedAt = started ? Date.parse(started.at) : NaN;
1672
+ // The gate ends when work resumed, not when a later stop noticed it.
1673
+ const resumed = Number.isFinite(startedAt)
1674
+ ? events.find((event) => event && event.type === 'attempt_started' && Date.parse(event.at) > startedAt)
1675
+ : null;
1676
+ appendMetric({
1677
+ type: 'human_gate_ended',
1678
+ at: resumed ? resumed.at : now,
1679
+ gateStartedEventId: status.activeHumanGateEventId,
1680
+ source: 'hook',
1681
+ attributionConfidence: 'high',
1682
+ });
1438
1683
  delete status.activeHumanGateEventId;
1439
1684
  }
1440
1685
  function completeTaskMetrics() {
@@ -1799,21 +2044,22 @@ function writeStatus(next) {
1799
2044
  // attempt is finished before this check runs. An empty or unreadable file still
1800
2045
  // counts as engaged (fail safe).
1801
2046
  const PAUSE_SENTINELS = [
1802
- path.join(process.cwd(), '.ai.local', 'STOP'),
1803
- path.join(process.cwd(), '.ai.local', 'ESTOP'),
2047
+ { file: path.join(process.cwd(), '.ai.local', 'STOP'), scope: 'repo' },
2048
+ { file: path.join(process.cwd(), '.ai.local', 'ESTOP'), scope: 'repo-emergency' },
1804
2049
  ];
1805
2050
  function readPauseSentinel() {
1806
2051
  const sentinels = [...PAUSE_SENTINELS];
1807
2052
  if (typeof slug === 'string' && slug !== '') {
1808
- sentinels.push(path.join(process.cwd(), '.ai.local', 'team', 'tasks', slug, 'STOP'));
2053
+ sentinels.push({ file: path.join(process.cwd(), '.ai.local', 'team', 'tasks', slug, 'STOP'), scope: 'task' });
1809
2054
  }
1810
- for (const file of sentinels) {
2055
+ for (const sentinel of sentinels) {
2056
+ const file = sentinel.file;
1811
2057
  let stat = null;
1812
2058
  try { stat = fs.statSync(file); } catch (error) {
1813
2059
  if (error && error.code === 'ENOENT') continue;
1814
2060
  // A permission or I/O error is not proof of absence: fail safe and say so.
1815
2061
  process.stderr.write(`WARNING: ${slug}: cannot stat pause sentinel ${path.relative(process.cwd(), file).split(path.sep).join('/')} (${error && error.message ? error.message : String(error)}); treating it as engaged.\n`);
1816
- return { engaged: true, file: path.relative(process.cwd(), file).split(path.sep).join('/'), reason: 'sentinel stat failed' };
2062
+ return { engaged: true, file: path.relative(process.cwd(), file).split(path.sep).join('/'), scope: sentinel.scope, at: null, reason: 'sentinel stat failed' };
1817
2063
  }
1818
2064
  if (!stat || !stat.isFile()) continue;
1819
2065
  let reason = '';
@@ -1831,19 +2077,52 @@ function readPauseSentinel() {
1831
2077
  return {
1832
2078
  engaged: true,
1833
2079
  file: path.relative(process.cwd(), file).split(path.sep).join('/'),
2080
+ scope: sentinel.scope,
2081
+ // The pause started when the sentinel was written, not when a hook noticed it.
2082
+ at: new Date(stat.mtimeMs).toISOString(),
1834
2083
  reason: reason.replace(/\s+/g, ' ').slice(0, 160),
1835
2084
  };
1836
2085
  }
1837
- return { engaged: false, file: null, reason: '' };
2086
+ return { engaged: false, file: null, scope: null, at: null, reason: '' };
1838
2087
  }
1839
2088
  function pausedNotice(pause) {
1840
2089
  const where = pause && pause.file ? pause.file : '.ai.local/STOP';
1841
2090
  const because = pause && pause.reason ? ` (${pause.reason})` : '';
1842
2091
  return `[chain-team-phases] ${slug}: paused — operator sentinel ${where} is engaged${because}. No step advanced and no handoff was emitted. Remove the sentinel and run /task-continue ${slug}.`;
1843
2092
  }
2093
+ // A pause is a duration in the ledger, not only a file. One `task_paused` per
2094
+ // engagement and one `task_resumed` when the sentinel is gone.
2095
+ function recordPauseEngaged(pause) {
2096
+ if (openPauseIndex(readMetricsEvents()) !== -1) return;
2097
+ appendMetric({
2098
+ type: 'task_paused',
2099
+ at: pause.at || now,
2100
+ scope: pause.scope || 'repo',
2101
+ file: pause.file || null,
2102
+ reason: pause.reason || null,
2103
+ source: 'hook',
2104
+ attributionConfidence: 'high',
2105
+ });
2106
+ }
2107
+ function recordPauseResumed() {
2108
+ const events = readMetricsEvents();
2109
+ const index = openPauseIndex(events);
2110
+ if (index === -1) return;
2111
+ appendMetric({
2112
+ type: 'task_resumed',
2113
+ at: now,
2114
+ pausedSince: events[index].at || null,
2115
+ source: 'hook',
2116
+ attributionConfidence: 'high',
2117
+ });
2118
+ }
1844
2119
  function pauseBlocksAdvance() {
1845
2120
  const pause = readPauseSentinel();
1846
- if (!pause.engaged) return null;
2121
+ if (!pause.engaged) {
2122
+ recordPauseResumed();
2123
+ return null;
2124
+ }
2125
+ recordPauseEngaged(pause);
1847
2126
  writeStatus({ state: 'paused', phase: 'paused' });
1848
2127
  out(pausedNotice(pause));
1849
2128
  return pause;
@@ -2224,6 +2503,96 @@ function countDebugImplementationRetries() {
2224
2503
  return 0;
2225
2504
  }
2226
2505
  }
2506
+ function replanDecisionCount() {
2507
+ try {
2508
+ const text = fs.readFileSync(path.join(taskDir, '.memlog.md'), 'utf8');
2509
+ const matches = text.match(/replan rev\s+\d+\s*(?:→|->)\s*\d+/g);
2510
+ return matches ? matches.length : 0;
2511
+ } catch {
2512
+ return 0;
2513
+ }
2514
+ }
2515
+ function changesRequestedCount(agent) {
2516
+ if (typeof agent !== 'string' || agent === '') return 0;
2517
+ try {
2518
+ const metrics = JSON.parse(fs.readFileSync(METRICS_PATH, 'utf8'));
2519
+ const events = Array.isArray(metrics.events) ? metrics.events : [];
2520
+ const needle = `:${agent}:`;
2521
+ return events.filter((event) => event && event.type === 'attempt_finished' && event.outcome === 'changes_requested' && typeof event.attemptId === 'string' && event.attemptId.includes(needle)).length;
2522
+ } catch {
2523
+ return 0;
2524
+ }
2525
+ }
2526
+ function holdDesignEscalation(agent, mode, reviewerStepIndex) {
2527
+ if (changesRequestedCount(agent) < 2) return false;
2528
+ beginHumanGate();
2529
+ writeStatus({
2530
+ awaitingHumanGate: true,
2531
+ state: 'awaiting_approval',
2532
+ currentAgent: agent,
2533
+ phase: 'human_gate',
2534
+ designEscalation: {
2535
+ agent,
2536
+ mode,
2537
+ reviewerStepIndex: Number.isInteger(reviewerStepIndex) ? reviewerStepIndex : null,
2538
+ priorReplanCount: replanDecisionCount(),
2539
+ },
2540
+ parallelCompleted: [],
2541
+ parallelOutcomes: {},
2542
+ waveSteps: [],
2543
+ waveId: null,
2544
+ retryAfterFix: null,
2545
+ retryAfterFixStepIndex: null,
2546
+ });
2547
+ out(`${agent} requested changes for slug "${slug}" a second time in this task. Append a \`.memlog.md\` line \`decision: replan rev N → N+1\` that changes the model, then resume via /task-continue. The next attempt is not dispatched until that line exists.`);
2548
+ process.exit(0);
2549
+ }
2550
+ function resumeDesignEscalation(escalation, resumeSteps) {
2551
+ steps = resumeSteps;
2552
+ const reviewer = escalation.agent;
2553
+ const reviewerStepIndex = Number.isInteger(escalation.reviewerStepIndex)
2554
+ ? escalation.reviewerStepIndex
2555
+ : (typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0);
2556
+ status.pipelineIndex = reviewerStepIndex;
2557
+ delete status.designEscalation;
2558
+ if (escalation.mode === 'graph') {
2559
+ const producerIndex = resolveProducerStepIndex('feature-developer', reviewerStepIndex);
2560
+ if (producerIndex < 0) {
2561
+ out(`${reviewer} requested changes for slug "${slug}" but no graph ancestor authors fixes. Read the review artifact. Resume only via /task-continue.`);
2562
+ process.exit(0);
2563
+ }
2564
+ appendMetric({ type: 'retry_scheduled', at: now, attemptId: status.lastCompletedAttempt?.attemptId || null, nextAgent: 'feature-developer', retryAfterFix: reviewer, source: 'hook', attributionConfidence: 'high' });
2565
+ invalidateFrom(producerIndex, reviewerStepIndex);
2566
+ writeStatus({ state: 'in_progress', phase: 'executing', awaitingHumanGate: false, waveSteps: [], waveId: null, retryAfterFix: null, retryAfterFixStepIndex: null, parallelCompleted: [], parallelOutcomes: {} });
2567
+ if (!dispatchReadyWave(`Design escalation for ${reviewer} accepted; re-dispatching unsatisfied steps.`)) out(noProgressNotice());
2568
+ process.exit(0);
2569
+ }
2570
+ let verifierStepIndex = -1;
2571
+ for (let index = reviewerStepIndex - 1; index >= 0; index -= 1) {
2572
+ if (getStepAgents(steps[index]).includes('build-verifier')) {
2573
+ verifierStepIndex = index;
2574
+ break;
2575
+ }
2576
+ }
2577
+ const retryGate = verifierStepIndex >= 0 ? 'build-verifier' : reviewer;
2578
+ const retryAfterFixStepIndex = verifierStepIndex >= 0 ? verifierStepIndex : reviewerStepIndex;
2579
+ const developerIndex = scheduleRetry('feature-developer', reviewer, status.lastCompletedAttempt);
2580
+ if (developerIndex < 0) {
2581
+ out(`${reviewer} requested changes for slug "${slug}" but this pipeline has no feature-developer step. Read the review artifact. Resume only via /task-continue.`);
2582
+ process.exit(0);
2583
+ }
2584
+ writeStatus({
2585
+ pipelineIndex: developerIndex,
2586
+ currentAgent: 'feature-developer',
2587
+ state: 'in_progress',
2588
+ phase: 'executing',
2589
+ awaitingHumanGate: false,
2590
+ retryAfterFix: retryGate,
2591
+ retryAfterFixStepIndex,
2592
+ });
2593
+ out(handoffForAgent('feature-developer', steps[developerIndex]?.scope, steps[developerIndex]) + ` After fixes, re-run ${retryGate}.`);
2594
+ process.exit(0);
2595
+ }
2227
2596
  function featureDeveloperAlreadyStarted() {
2228
2597
  try {
2229
2598
  const metrics = JSON.parse(fs.readFileSync(METRICS_PATH, 'utf8'));
@@ -2592,6 +2961,19 @@ if (hookInput.action === 'bootstrap') {
2592
2961
  function readMetricsLedger() {
2593
2962
  try { return JSON.parse(fs.readFileSync(METRICS_PATH, 'utf8')); } catch { return null; }
2594
2963
  }
2964
+ function readMetricsEvents() {
2965
+ const ledger = readMetricsLedger();
2966
+ return ledger && Array.isArray(ledger.events) ? ledger.events : [];
2967
+ }
2968
+ /** Index of the `task_paused` that no `task_resumed` closed, or -1. */
2969
+ function openPauseIndex(events) {
2970
+ for (let index = events.length - 1; index >= 0; index -= 1) {
2971
+ const type = events[index] && events[index].type;
2972
+ if (type === 'task_resumed') return -1;
2973
+ if (type === 'task_paused') return index;
2974
+ }
2975
+ return -1;
2976
+ }
2595
2977
 
2596
2978
  if (hookInput.action === 'out_of_band_start') {
2597
2979
  if (pauseBlocksAdvance()) process.exit(0);
@@ -2658,6 +3040,11 @@ if (hookInput.action === 'out_of_band_end') {
2658
3040
 
2659
3041
  if (hookInput.action === 'end_human_gate') {
2660
3042
  if (pauseBlocksAdvance()) process.exit(0);
3043
+ const designEscalation = status.designEscalation && typeof status.designEscalation === 'object' ? status.designEscalation : null;
3044
+ if (designEscalation && replanDecisionCount() <= (Number(designEscalation.priorReplanCount) || 0)) {
3045
+ out(`Design escalation for slug "${slug}" is still open. Append a \`.memlog.md\` line \`decision: replan rev N → N+1\` that changes the model, then resume via /task-continue.`);
3046
+ process.exit(0);
3047
+ }
2661
3048
  // Only advance when a gate was actually open. A duplicate or retried
2662
3049
  // end_human_gate must be a no-op, not a silent pipeline skip.
2663
3050
  const gateWasOpen = Boolean(status.activeHumanGateEventId) || status.awaitingHumanGate === true;
@@ -2689,6 +3076,12 @@ if (hookInput.action === 'end_human_gate') {
2689
3076
  });
2690
3077
  delete status.activeHumanGateEventId;
2691
3078
  }
3079
+ if (designEscalation && hookInput.activateNext && fs.existsSync(pipelinePath)) {
3080
+ let designPipeline = null;
3081
+ try { designPipeline = JSON.parse(fs.readFileSync(pipelinePath, 'utf8')); } catch {}
3082
+ const designSteps = designPipeline && Array.isArray(designPipeline.steps) ? designPipeline.steps : [];
3083
+ resumeDesignEscalation(designEscalation, designSteps);
3084
+ }
2692
3085
  if (gateWasOpen && hookInput.activateNext && fs.existsSync(pipelinePath)) {
2693
3086
  let resumePipeline = null;
2694
3087
  try { resumePipeline = JSON.parse(fs.readFileSync(pipelinePath, 'utf8')); } catch {}
@@ -2828,10 +3221,12 @@ if (status.state === 'awaiting_artifact_receipt') {
2828
3221
  const pause = readPauseSentinel();
2829
3222
  if (pause.engaged) {
2830
3223
  if (artifactStallMessage) process.stderr.write(artifactStallMessage + '\n');
3224
+ recordPauseEngaged(pause);
2831
3225
  writeStatus({ state: 'paused', phase: 'paused' });
2832
3226
  out(pausedNotice(pause));
2833
3227
  process.exit(0);
2834
3228
  }
3229
+ recordPauseResumed();
2835
3230
  writeStatus({});
2836
3231
  emitArtifactStall(artifactStallMessage, !wasWaitingForReceipt);
2837
3232
  process.exit(0);
@@ -3055,6 +3450,7 @@ if (waveIndexes) {
3055
3450
  out(`${retryReviewer} requested changes for slug "${slug}" but no graph ancestor authors fixes. Read the review artifact. Resume only via /task-continue.`);
3056
3451
  process.exit(0);
3057
3452
  }
3453
+ holdDesignEscalation(retryReviewer, 'graph', reviewerStepIndex);
3058
3454
  const graphPredecessor = outcomes[retryReviewer]
3059
3455
  ? { attemptId: outcomes[retryReviewer].attemptId, confidence: outcomes[retryReviewer].confidence }
3060
3456
  : finishedAttempt;
@@ -3067,6 +3463,7 @@ if (waveIndexes) {
3067
3463
  if (!dispatchReadyWave(`Step ${reviewerStepIndex} (${retryReviewer}) requested changes; re-dispatching unsatisfied steps.`)) out(noProgressNotice());
3068
3464
  process.exit(0);
3069
3465
  }
3466
+ holdDesignEscalation(retryReviewer, 'linear', idx);
3070
3467
  const retryAfterFixStepIndex = idx;
3071
3468
  const predecessor = outcomes[retryReviewer]
3072
3469
  ? {
@@ -3166,6 +3563,7 @@ if (status.state === 'changes_requested') {
3166
3563
  process.exit(0);
3167
3564
  }
3168
3565
  const reviewerStepIndex = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
3566
+ holdDesignEscalation(reviewer, 'linear', reviewerStepIndex);
3169
3567
  let verifierStepIndex = -1;
3170
3568
  for (let index = reviewerStepIndex - 1; index >= 0; index -= 1) {
3171
3569
  if (getStepAgents(steps[index]).includes('build-verifier')) {
@@ -3299,26 +3697,21 @@ const fs = require('fs');
3299
3697
  const path = require('path');
3300
3698
  const { spawnSync } = require('child_process');
3301
3699
 
3700
+ // Slug binding for the seams below is inside the projection markers. The
3701
+ // dualwrite harness executes that region alone, so the resolver has to live
3702
+ // there or a fresh store is never created.
3703
+
3302
3704
  // Dev-server cleanup: terminal task state only. `processes.mjs` proves
3303
3705
  // ownership from `.ai.local/.processes/leases/<name>.json` before any signal,
3304
3706
  // so a foreign process is never touched. A refusal or timeout is a warning,
3305
- // never a hook failure.
3707
+ // never a hook failure. The slug is the env binding only — no pointer
3708
+ // fallback: cleanup matters only on terminal state, and the main hook always
3709
+ // knows the slug it resolved.
3306
3710
  function stopOwnedDevServers() {
3307
3711
  const processes = path.join(process.cwd(), '.ai.local', 'scripts', 'processes.mjs');
3308
3712
  if (!fs.existsSync(processes)) return;
3309
- const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3310
- let slug = typeof process.env.TEAM_TASK_SLUG === 'string' ? process.env.TEAM_TASK_SLUG : '';
3311
- if (!slug) {
3312
- try {
3313
- const active = JSON.parse(
3314
- fs.readFileSync(path.join(process.cwd(), '.ai.local', 'team', 'active-task.json'), 'utf8'),
3315
- );
3316
- slug = typeof active.slug === 'string' ? active.slug : '';
3317
- } catch {
3318
- return;
3319
- }
3320
- }
3321
- if (slug.length === 0 || slug.length > 48 || !SLUG_RE.test(slug)) return;
3713
+ const slug = typeof process.env.TEAM_TASK_SLUG === 'string' ? process.env.TEAM_TASK_SLUG : '';
3714
+ if (slug.length === 0 || slug.length > 48 || !POSTFLIGHT_SLUG_RE.test(slug)) return;
3322
3715
  let state = '';
3323
3716
  try {
3324
3717
  const status = JSON.parse(
@@ -3546,6 +3939,95 @@ if (!input || input.status !== 'completed') {
3546
3939
  // This is a plain region marker, not a `hook-slot`: the block is identical in
3547
3940
  // all 40 rendered bodies and needs no per-stack fragment.
3548
3941
  // <<<team-db-projection>>>
3942
+ // Postflight slug binding, shared by the seams below: the env slug first,
3943
+ // then the per-session lease (the same file the main hook and the OpenCode
3944
+ // task-status plugin write), and the active-task.json projection only as a
3945
+ // last resort. Containment comes from validating every derivation point with
3946
+ // the slug grammar (the same pattern as the hook's SLUG_RE), so `tasks/<slug>`
3947
+ // cannot escape the tree on any postflight path. This region is extracted and
3948
+ // executed alone by the dualwrite harness, so the resolver stays inside the
3949
+ // markers.
3950
+ const TERMINAL_STATES = new Set(['completed', 'blocked', 'changes_requested', 'validation_failed']);
3951
+ const POSTFLIGHT_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3952
+ function postflightLiveSlugs() {
3953
+ const tasksDir = path.join(process.cwd(), '.ai.local', 'team', 'tasks');
3954
+ let entries;
3955
+ try {
3956
+ entries = fs.readdirSync(tasksDir, { withFileTypes: true });
3957
+ } catch (error) {
3958
+ return [];
3959
+ }
3960
+ const live = [];
3961
+ for (const entry of entries) {
3962
+ if (!entry.isDirectory()) continue;
3963
+ try {
3964
+ const status = JSON.parse(fs.readFileSync(path.join(tasksDir, entry.name, 'status.json'), 'utf8'));
3965
+ if (status && typeof status.state === 'string' && !TERMINAL_STATES.has(status.state)) live.push(entry.name);
3966
+ } catch (error) {
3967
+ /* an unreadable status is not a live slug */
3968
+ }
3969
+ }
3970
+ return live.sort();
3971
+ }
3972
+ function postflightPointerSlug() {
3973
+ // Last-resort read of the UI projection; both the projection shape
3974
+ // `{"slugs": [...]}` and the legacy single-slot `{"slug"}` are accepted
3975
+ // forever. A multi-slug projection resolves to its first entry; the
3976
+ // live-scan guard in postflightResolveSlug decides whether that
3977
+ // resolution is safe to act on.
3978
+ try {
3979
+ const active = JSON.parse(
3980
+ fs.readFileSync(path.join(process.cwd(), '.ai.local', 'team', 'active-task.json'), 'utf8'),
3981
+ );
3982
+ const slugs = Array.isArray(active.slugs)
3983
+ ? active.slugs
3984
+ : (typeof active.slug === 'string' && active.slug ? [active.slug] : []);
3985
+ const candidate = typeof slugs[0] === 'string' ? slugs[0] : '';
3986
+ if (candidate.length > 48 || !POSTFLIGHT_SLUG_RE.test(candidate)) return '';
3987
+ return candidate;
3988
+ } catch (error) {
3989
+ return '';
3990
+ }
3991
+ }
3992
+ function postflightSessionId() {
3993
+ const raw = process.env.OPENCODE_SESSION_ID || process.env.AI_RULES_SESSION_ID || '';
3994
+ return /^[A-Za-z0-9_-]{1,128}$/.test(raw) ? raw : '';
3995
+ }
3996
+ function postflightLeaseSlug() {
3997
+ // Same file and TTL as the main hook. A pointer fallback must not win while
3998
+ // this session already has a pin.
3999
+ const id = postflightSessionId();
4000
+ if (!id) return '';
4001
+ try {
4002
+ const file = path.join(process.cwd(), '.ai.local', 'team', '.session-leases', `${id}.json`);
4003
+ if (Date.now() - fs.statSync(file).mtimeMs > 7 * 24 * 60 * 60 * 1000) return '';
4004
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
4005
+ const slug = parsed && typeof parsed.slug === 'string' ? parsed.slug : '';
4006
+ if (slug.length > 48 || !POSTFLIGHT_SLUG_RE.test(slug)) return '';
4007
+ return slug;
4008
+ } catch (error) {
4009
+ return '';
4010
+ }
4011
+ }
4012
+ function postflightResolveSlug() {
4013
+ // An env slug present but invalid is a stop, not a fallback: the projection
4014
+ // must never route around a bad explicit binding.
4015
+ const envSlug = typeof process.env.TEAM_TASK_SLUG === 'string' ? process.env.TEAM_TASK_SLUG : '';
4016
+ if (envSlug !== '') {
4017
+ if (envSlug.length <= 48 && POSTFLIGHT_SLUG_RE.test(envSlug)) return { slug: envSlug };
4018
+ return { slug: '' };
4019
+ }
4020
+ const leaseSlug = postflightLeaseSlug();
4021
+ if (leaseSlug) return { slug: leaseSlug };
4022
+ const pointerSlug = postflightPointerSlug();
4023
+ if (!pointerSlug) return { slug: '' };
4024
+ const live = postflightLiveSlugs();
4025
+ for (let index = 0; index < live.length; index += 1) {
4026
+ if (live[index] !== pointerSlug) return { slug: '', pointerLiveSlugs: live.length };
4027
+ }
4028
+ return { slug: pointerSlug };
4029
+ }
4030
+
3549
4031
  function teamDbTruthy(value) {
3550
4032
  if (typeof value !== 'string') return false;
3551
4033
  const normalized = value.trim().toLowerCase();
@@ -3602,17 +4084,17 @@ function teamDbProject() {
3602
4084
  try {
3603
4085
  const env = process.env;
3604
4086
  if (teamDbTruthy(env.AI_RULES_TEAM_DB_DISABLE)) return;
3605
- // Same pattern as POSTFLIGHT_SLUG_RE above: the slug is re-derived from
3606
- // `active-task.json` on this path too, so it cannot escape the tree.
3607
- const slugPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3608
- let slug = '';
3609
- try {
3610
- const active = JSON.parse(fs.readFileSync(path.join(process.cwd(), '.ai.local', 'team', 'active-task.json'), 'utf8'));
3611
- slug = typeof active.slug === 'string' ? active.slug : '';
3612
- } catch (error) {
4087
+ const resolved = postflightResolveSlug();
4088
+ if (resolved.pointerLiveSlugs) {
4089
+ // A pointer-resolved projection under other live slugs cannot say
4090
+ // which task this stop belongs to. Skipping is safe: the projection
4091
+ // converges on the next `team-db sync`, and the files stay
4092
+ // authoritative.
4093
+ process.stderr.write(`WARNING: pointer-resolved projection skipped; ${resolved.pointerLiveSlugs} live slugs\n`);
3613
4094
  return;
3614
4095
  }
3615
- if (!slug || slug.length > 48 || !slugPattern.test(slug)) return;
4096
+ const slug = resolved.slug;
4097
+ if (!slug) return;
3616
4098
  const taskDir = path.join(process.cwd(), '.ai.local', 'team', 'tasks', slug);
3617
4099
  if (!fs.existsSync(path.join(taskDir, 'status.json'))) return;
3618
4100
  const script = path.join(process.cwd(), '.ai.local', 'scripts', 'team-db.mjs');
@@ -3758,13 +4240,11 @@ teamDbTrackerDrain();
3758
4240
  let pipeline = null;
3759
4241
  try {
3760
4242
  const teamRoot = path.join(process.cwd(), '.ai.local', 'team');
3761
- const active = JSON.parse(fs.readFileSync(path.join(teamRoot, 'active-task.json'), 'utf8'));
3762
- const pipelineSlug = typeof active.slug === 'string' ? active.slug : '';
3763
- // Same pattern as `SLUG_RE` at the top of this file: `tasks/<slug>` is
3764
- // re-derived from `active-task.json` here too, so an unchecked slug could
3765
- // escape the tree on this path exactly as it could there.
3766
- const POSTFLIGHT_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3767
- if (pipelineSlug.length <= 48 && POSTFLIGHT_SLUG_RE.test(pipelineSlug)) {
4243
+ // Same binding as the seams above: env slug first, projection last resort.
4244
+ // A pointer resolution refused by the live-scan guard is a silent policy
4245
+ // skip here — the ratchet is already silent-by-design for light/spike.
4246
+ const pipelineSlug = postflightResolveSlug().slug;
4247
+ if (pipelineSlug) {
3768
4248
  pipeline = JSON.parse(fs.readFileSync(path.join(teamRoot, 'tasks', pipelineSlug, 'pipeline.json'), 'utf8'));
3769
4249
  }
3770
4250
  } catch {