@bonesofspring/ai-rules 0.2.64 → 0.2.65

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 (293) hide show
  1. package/CHANGELOG.md +46 -11
  2. package/README.md +6 -6
  3. package/bin/lib/engine-scripts.js +14 -5
  4. package/bin/lib/seed-ai-local-team.js +7 -0
  5. package/docs/PRESET-CONTRIBUTION.md +41 -0
  6. package/docs/TEAM-DB.md +193 -52
  7. package/docs/openapi/team-db.v1.json +1238 -377
  8. package/mcp/defectdojo-mcp.mjs +7 -5
  9. package/mcp/lib/defectdojo.mjs +26 -14
  10. package/package.json +26 -20
  11. package/presets/_shared/ai-local/scripts/process-lease.mjs +576 -0
  12. package/presets/_shared/ai-local/scripts/processes.mjs +1618 -0
  13. package/presets/_shared/ai-local/scripts/run.mjs +5 -5
  14. package/presets/_shared/ai-local/scripts/team-db-api.mjs +465 -152
  15. package/presets/_shared/ai-local/scripts/team-db-dashboard.mjs +235 -10
  16. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +416 -176
  17. package/presets/_shared/ai-local/scripts/team-db-project.mjs +171 -62
  18. package/presets/_shared/ai-local/scripts/team-db-scheduler.mjs +4 -0
  19. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +143 -5
  20. package/presets/_shared/ai-local/scripts/team-db-task-runner.mjs +567 -0
  21. package/presets/_shared/ai-local/scripts/{team-db-backlog.mjs → team-db-tracker.mjs} +900 -197
  22. package/presets/_shared/ai-local/scripts/team-db-ui.mjs +750 -0
  23. package/presets/_shared/ai-local/scripts/team-db.mjs +104 -23
  24. package/presets/_shared/core/agent-team/agent-team-orchestrator.md +1 -1
  25. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +105 -17
  26. package/presets/_shared/hooks/guard-shell-command.mjs.tmpl +40 -2
  27. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +105 -17
  28. package/presets/claude/android-kotlin/hooks/guard-shell-command.mjs +41 -2
  29. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  30. package/presets/claude/android-kotlin/settings.json +6 -1
  31. package/presets/claude/go/hooks/chain-team-phases.sh +105 -17
  32. package/presets/claude/go/hooks/guard-shell-command.mjs +41 -2
  33. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  34. package/presets/claude/go/settings.json +6 -1
  35. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +105 -17
  36. package/presets/claude/ios-swift/hooks/guard-shell-command.mjs +41 -2
  37. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  38. package/presets/claude/ios-swift/settings.json +6 -1
  39. package/presets/claude/java/hooks/chain-team-phases.sh +105 -17
  40. package/presets/claude/java/hooks/guard-shell-command.mjs +41 -2
  41. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  42. package/presets/claude/java/settings.json +6 -1
  43. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +105 -17
  44. package/presets/claude/mcp-ts/hooks/guard-shell-command.mjs +41 -2
  45. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  46. package/presets/claude/mcp-ts/settings.json +6 -1
  47. package/presets/claude/mol/hooks/chain-team-phases.sh +105 -17
  48. package/presets/claude/mol/hooks/guard-shell-command.mjs +41 -2
  49. package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  50. package/presets/claude/mol/settings.json +6 -1
  51. package/presets/claude/next/MCP.md +2 -0
  52. package/presets/claude/next/REPO_AGENTS.md +2 -0
  53. package/presets/claude/next/agents/build-verifier.md +1 -1
  54. package/presets/claude/next/agents/ci-investigator.md +3 -0
  55. package/presets/claude/next/agents/debugger.md +3 -0
  56. package/presets/claude/next/agents/feature-developer.md +3 -0
  57. package/presets/claude/next/agents/mockup-reviewer.md +2 -0
  58. package/presets/claude/next/agents/performance-auditor.md +2 -0
  59. package/presets/claude/next/agents/playwright-test-generator.md +3 -0
  60. package/presets/claude/next/agents/playwright-test-healer.md +3 -0
  61. package/presets/claude/next/agents/playwright-test-planner.md +3 -0
  62. package/presets/claude/next/agents/qa-tester.md +3 -0
  63. package/presets/claude/next/commands/README.md +6 -0
  64. package/presets/claude/next/commands/ui-start.md +78 -0
  65. package/presets/claude/next/commands/ui-stop.md +71 -0
  66. package/presets/claude/next/hooks/chain-team-phases.sh +105 -17
  67. package/presets/claude/next/hooks/guard-shell-command.mjs +41 -2
  68. package/presets/claude/next/rules/README.md +2 -1
  69. package/presets/claude/next/rules/stack/next-app-core.md +1 -0
  70. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  71. package/presets/claude/next/rules/tooling-and-review/dev-process-lifecycle.md +43 -0
  72. package/presets/claude/next/settings.json +6 -1
  73. package/presets/claude/nuxt/hooks/chain-team-phases.sh +105 -17
  74. package/presets/claude/nuxt/hooks/guard-shell-command.mjs +41 -2
  75. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  76. package/presets/claude/nuxt/settings.json +6 -1
  77. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +105 -17
  78. package/presets/claude/php-hexagonal/hooks/guard-shell-command.mjs +41 -2
  79. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  80. package/presets/claude/php-hexagonal/settings.json +6 -1
  81. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +106 -18
  82. package/presets/claude/php-laravel/hooks/guard-shell-command.mjs +41 -2
  83. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  84. package/presets/claude/php-laravel/settings.json +6 -1
  85. package/presets/claude/svelte/hooks/chain-team-phases.sh +105 -17
  86. package/presets/claude/svelte/hooks/guard-shell-command.mjs +41 -2
  87. package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +1 -1
  88. package/presets/claude/svelte/settings.json +6 -1
  89. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +105 -17
  90. package/presets/cursor/android-kotlin/hooks/guard-shell-command.mjs +41 -2
  91. package/presets/cursor/go/hooks/chain-team-phases.sh +105 -17
  92. package/presets/cursor/go/hooks/guard-shell-command.mjs +41 -2
  93. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +105 -17
  94. package/presets/cursor/ios-swift/hooks/guard-shell-command.mjs +41 -2
  95. package/presets/cursor/java/hooks/chain-team-phases.sh +105 -17
  96. package/presets/cursor/java/hooks/guard-shell-command.mjs +41 -2
  97. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +105 -17
  98. package/presets/cursor/mcp-ts/hooks/guard-shell-command.mjs +41 -2
  99. package/presets/cursor/mol/hooks/chain-team-phases.sh +105 -17
  100. package/presets/cursor/mol/hooks/guard-shell-command.mjs +41 -2
  101. package/presets/cursor/next/MCP.md +2 -0
  102. package/presets/cursor/next/REPO_AGENTS.md +2 -0
  103. package/presets/cursor/next/agents/build-verifier.md +1 -1
  104. package/presets/cursor/next/agents/ci-investigator.md +2 -0
  105. package/presets/cursor/next/agents/debugger.md +2 -0
  106. package/presets/cursor/next/agents/feature-developer.md +2 -0
  107. package/presets/cursor/next/agents/mockup-reviewer.md +2 -0
  108. package/presets/cursor/next/agents/performance-auditor.md +2 -0
  109. package/presets/cursor/next/agents/playwright-test-generator.md +2 -0
  110. package/presets/cursor/next/agents/playwright-test-healer.md +2 -0
  111. package/presets/cursor/next/agents/playwright-test-planner.md +2 -0
  112. package/presets/cursor/next/agents/qa-tester.md +2 -0
  113. package/presets/cursor/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -1
  114. package/presets/cursor/next/commands/README.md +6 -0
  115. package/presets/cursor/next/commands/ui-start.md +78 -0
  116. package/presets/cursor/next/commands/ui-stop.md +71 -0
  117. package/presets/cursor/next/hooks/chain-team-phases.sh +105 -17
  118. package/presets/cursor/next/hooks/guard-shell-command.mjs +41 -2
  119. package/presets/cursor/next/rules/README.md +2 -1
  120. package/presets/cursor/next/rules/dev-process-lifecycle.mdc +43 -0
  121. package/presets/cursor/next/rules/next-app-core.mdc +1 -0
  122. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +105 -17
  123. package/presets/cursor/nuxt/hooks/guard-shell-command.mjs +41 -2
  124. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +105 -17
  125. package/presets/cursor/php-hexagonal/hooks/guard-shell-command.mjs +41 -2
  126. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +106 -18
  127. package/presets/cursor/php-laravel/hooks/guard-shell-command.mjs +41 -2
  128. package/presets/cursor/svelte/hooks/chain-team-phases.sh +105 -17
  129. package/presets/cursor/svelte/hooks/guard-shell-command.mjs +41 -2
  130. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  131. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +105 -17
  132. package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +1 -1
  133. package/presets/mavis/go/adapter-map.json +1 -1
  134. package/presets/mavis/go/hooks/chain-team-phases.sh +105 -17
  135. package/presets/mavis/go/rules/agent-team-orchestrator.md +1 -1
  136. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  137. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +105 -17
  138. package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +1 -1
  139. package/presets/mavis/java/adapter-map.json +1 -1
  140. package/presets/mavis/java/hooks/chain-team-phases.sh +105 -17
  141. package/presets/mavis/java/rules/agent-team-orchestrator.md +1 -1
  142. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  143. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +105 -17
  144. package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +1 -1
  145. package/presets/mavis/mol/adapter-map.json +1 -1
  146. package/presets/mavis/mol/hooks/chain-team-phases.sh +105 -17
  147. package/presets/mavis/mol/rules/agent-team-orchestrator.md +1 -1
  148. package/presets/mavis/next/MCP.md +2 -0
  149. package/presets/mavis/next/REPO_AGENTS.md +2 -0
  150. package/presets/mavis/next/adapter-map.json +25 -1
  151. package/presets/mavis/next/agents/build-verifier.md +1 -1
  152. package/presets/mavis/next/agents/ci-investigator.md +3 -0
  153. package/presets/mavis/next/agents/debugger.md +3 -0
  154. package/presets/mavis/next/agents/feature-developer.md +3 -0
  155. package/presets/mavis/next/agents/mockup-reviewer.md +2 -0
  156. package/presets/mavis/next/agents/performance-auditor.md +2 -0
  157. package/presets/mavis/next/agents/playwright-test-generator.md +3 -0
  158. package/presets/mavis/next/agents/playwright-test-healer.md +3 -0
  159. package/presets/mavis/next/agents/playwright-test-planner.md +3 -0
  160. package/presets/mavis/next/agents/qa-tester.md +3 -0
  161. package/presets/mavis/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -1
  162. package/presets/mavis/next/commands/README.md +6 -0
  163. package/presets/mavis/next/commands/ui-start.md +73 -0
  164. package/presets/mavis/next/commands/ui-stop.md +66 -0
  165. package/presets/mavis/next/hooks/chain-team-phases.sh +105 -17
  166. package/presets/mavis/next/rules/agent-team-orchestrator.md +1 -1
  167. package/presets/mavis/next/rules/dev-process-lifecycle.md +38 -0
  168. package/presets/mavis/next/rules/next-app-core.md +1 -0
  169. package/presets/mavis/nuxt/adapter-map.json +1 -1
  170. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +105 -17
  171. package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +1 -1
  172. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  173. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +105 -17
  174. package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +1 -1
  175. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  176. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +106 -18
  177. package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +1 -1
  178. package/presets/mavis/svelte/adapter-map.json +1 -1
  179. package/presets/mavis/svelte/hooks/chain-team-phases.sh +105 -17
  180. package/presets/mavis/svelte/rules/agent-team-orchestrator.md +1 -1
  181. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  182. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +105 -17
  183. package/presets/opencode/android-kotlin/opencode.json +5 -1
  184. package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +1 -1
  185. package/presets/opencode/go/adapter-map.json +1 -1
  186. package/presets/opencode/go/hooks/chain-team-phases.sh +105 -17
  187. package/presets/opencode/go/opencode.json +5 -1
  188. package/presets/opencode/go/rules/agent-team-orchestrator.md +1 -1
  189. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  190. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +105 -17
  191. package/presets/opencode/ios-swift/opencode.json +5 -1
  192. package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +1 -1
  193. package/presets/opencode/java/adapter-map.json +1 -1
  194. package/presets/opencode/java/hooks/chain-team-phases.sh +105 -17
  195. package/presets/opencode/java/opencode.json +5 -1
  196. package/presets/opencode/java/rules/agent-team-orchestrator.md +1 -1
  197. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  198. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +105 -17
  199. package/presets/opencode/mcp-ts/opencode.json +5 -1
  200. package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +1 -1
  201. package/presets/opencode/mol/adapter-map.json +1 -1
  202. package/presets/opencode/mol/hooks/chain-team-phases.sh +105 -17
  203. package/presets/opencode/mol/opencode.json +4 -0
  204. package/presets/opencode/mol/rules/agent-team-orchestrator.md +1 -1
  205. package/presets/opencode/next/MCP.md +2 -0
  206. package/presets/opencode/next/REPO_AGENTS.md +2 -0
  207. package/presets/opencode/next/adapter-map.json +25 -1
  208. package/presets/opencode/next/agents/build-verifier.md +1 -1
  209. package/presets/opencode/next/agents/ci-investigator.md +3 -0
  210. package/presets/opencode/next/agents/debugger.md +3 -0
  211. package/presets/opencode/next/agents/feature-developer.md +3 -0
  212. package/presets/opencode/next/agents/mockup-reviewer.md +2 -0
  213. package/presets/opencode/next/agents/performance-auditor.md +2 -0
  214. package/presets/opencode/next/agents/playwright-test-generator.md +3 -0
  215. package/presets/opencode/next/agents/playwright-test-healer.md +3 -0
  216. package/presets/opencode/next/agents/playwright-test-planner.md +3 -0
  217. package/presets/opencode/next/agents/qa-tester.md +3 -0
  218. package/presets/opencode/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -1
  219. package/presets/opencode/next/commands/README.md +6 -0
  220. package/presets/opencode/next/commands/ui-start.md +81 -0
  221. package/presets/opencode/next/commands/ui-stop.md +74 -0
  222. package/presets/opencode/next/hooks/chain-team-phases.sh +105 -17
  223. package/presets/opencode/next/opencode.json +4 -0
  224. package/presets/opencode/next/rules/agent-team-orchestrator.md +1 -1
  225. package/presets/opencode/next/rules/dev-process-lifecycle.md +38 -0
  226. package/presets/opencode/next/rules/next-app-core.md +1 -0
  227. package/presets/opencode/nuxt/adapter-map.json +1 -1
  228. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +105 -17
  229. package/presets/opencode/nuxt/opencode.json +4 -0
  230. package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +1 -1
  231. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  232. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +105 -17
  233. package/presets/opencode/php-hexagonal/opencode.json +5 -1
  234. package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +1 -1
  235. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  236. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +106 -18
  237. package/presets/opencode/php-laravel/opencode.json +5 -1
  238. package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +1 -1
  239. package/presets/opencode/svelte/adapter-map.json +1 -1
  240. package/presets/opencode/svelte/hooks/chain-team-phases.sh +105 -17
  241. package/presets/opencode/svelte/opencode.json +4 -0
  242. package/presets/opencode/svelte/rules/agent-team-orchestrator.md +1 -1
  243. package/presets/zcode/android-kotlin/adapter-map.json +1 -1
  244. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +105 -17
  245. package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +1 -1
  246. package/presets/zcode/go/adapter-map.json +1 -1
  247. package/presets/zcode/go/hooks/chain-team-phases.sh +105 -17
  248. package/presets/zcode/go/rules/agent-team-orchestrator.md +1 -1
  249. package/presets/zcode/ios-swift/adapter-map.json +1 -1
  250. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +105 -17
  251. package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +1 -1
  252. package/presets/zcode/java/adapter-map.json +1 -1
  253. package/presets/zcode/java/hooks/chain-team-phases.sh +105 -17
  254. package/presets/zcode/java/rules/agent-team-orchestrator.md +1 -1
  255. package/presets/zcode/mcp-ts/adapter-map.json +1 -1
  256. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +105 -17
  257. package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +1 -1
  258. package/presets/zcode/mol/adapter-map.json +1 -1
  259. package/presets/zcode/mol/hooks/chain-team-phases.sh +105 -17
  260. package/presets/zcode/mol/rules/agent-team-orchestrator.md +1 -1
  261. package/presets/zcode/next/MCP.md +2 -0
  262. package/presets/zcode/next/REPO_AGENTS.md +2 -0
  263. package/presets/zcode/next/adapter-map.json +25 -1
  264. package/presets/zcode/next/agents/build-verifier.md +1 -1
  265. package/presets/zcode/next/agents/ci-investigator.md +3 -0
  266. package/presets/zcode/next/agents/debugger.md +3 -0
  267. package/presets/zcode/next/agents/feature-developer.md +3 -0
  268. package/presets/zcode/next/agents/mockup-reviewer.md +2 -0
  269. package/presets/zcode/next/agents/performance-auditor.md +2 -0
  270. package/presets/zcode/next/agents/playwright-test-generator.md +3 -0
  271. package/presets/zcode/next/agents/playwright-test-healer.md +3 -0
  272. package/presets/zcode/next/agents/playwright-test-planner.md +3 -0
  273. package/presets/zcode/next/agents/qa-tester.md +3 -0
  274. package/presets/zcode/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -1
  275. package/presets/zcode/next/commands/README.md +6 -0
  276. package/presets/zcode/next/commands/ui-start.md +81 -0
  277. package/presets/zcode/next/commands/ui-stop.md +74 -0
  278. package/presets/zcode/next/hooks/chain-team-phases.sh +105 -17
  279. package/presets/zcode/next/rules/agent-team-orchestrator.md +1 -1
  280. package/presets/zcode/next/rules/dev-process-lifecycle.md +38 -0
  281. package/presets/zcode/next/rules/next-app-core.md +1 -0
  282. package/presets/zcode/nuxt/adapter-map.json +1 -1
  283. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +105 -17
  284. package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +1 -1
  285. package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
  286. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +105 -17
  287. package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +1 -1
  288. package/presets/zcode/php-laravel/adapter-map.json +1 -1
  289. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +106 -18
  290. package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +1 -1
  291. package/presets/zcode/svelte/adapter-map.json +1 -1
  292. package/presets/zcode/svelte/hooks/chain-team-phases.sh +105 -17
  293. package/presets/zcode/svelte/rules/agent-team-orchestrator.md +1 -1
@@ -0,0 +1,567 @@
1
+ /**
2
+ * Opt-in task runner for tracker links.
3
+ *
4
+ * The web UI never accepts a command from a request. It starts the one
5
+ * committed `team/runner.json` argv template, with a generated prompt file and
6
+ * the validated task slug. The runner is a supervisor child: it writes a run
7
+ * manifest, spawns the agent in its own process group, caps stdout/stderr,
8
+ * enforces the timeout, and records the terminal state. Without
9
+ * `team/runner.json` the verb refuses with `E_RUNNER_OFFLINE` and the UI
10
+ * disables Continue.
11
+ *
12
+ * Files are authoritative; nothing here writes `status.json` or `metrics.json`.
13
+ * The only task-side write is the per-task `STOP` request sentinel, which the
14
+ * chain hook reads before it advances a step.
15
+ */
16
+
17
+ import crypto from 'node:crypto';
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { spawn, spawnSync } from 'node:child_process';
21
+ import { fileURLToPath } from 'node:url';
22
+
23
+ import { DEFAULT_TEAM_ROOT, TeamDbError, isKillSwitchSet, teamDbFail } from './team-db-schema.mjs';
24
+ import { acquireLock, releaseLock } from './lock.mjs';
25
+ import { CappedLogWriter } from './team-db-scheduler.mjs';
26
+
27
+ export const RUNNER_FILE = 'runner.json';
28
+ export const RUNNER_SCHEMA_VERSION = 1;
29
+ export const TASK_RUNS_DIR = 'task-runs';
30
+ export const RUN_MANIFEST_FILE = 'run.json';
31
+ export const RUN_PROMPT_FILE = 'prompt.md';
32
+ export const RUN_STDOUT_FILE = 'stdout.log';
33
+ export const RUN_STDERR_FILE = 'stderr.log';
34
+ export const RUN_STATES = ['claimed', 'running', 'succeeded', 'failed', 'timeout', 'interrupted'];
35
+ export const ACTIVE_RUN_STATES = ['claimed', 'running'];
36
+ export const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
37
+ export const MIN_TIMEOUT_MS = 1000;
38
+ export const MAX_TIMEOUT_MS = 12 * 60 * 60 * 1000;
39
+ export const MAX_ARGV_ELEMENTS = 32;
40
+ export const MAX_ARGV_ELEMENT_LENGTH = 4096;
41
+ export const MAX_ENV_NAMES = 24;
42
+ export const MAX_PROMPT_BYTES = 64 * 1024;
43
+ export const MAX_RUN_LOG_BYTES = 1024 * 1024;
44
+ export const STOP_GRACE_MS = 5000;
45
+ export const START_LOCK_TIMEOUT_MS = 5000;
46
+ export const CLAIMED_GRACE_MS = 15_000;
47
+ export const RUN_ID_RE = /^[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}$/;
48
+ export const ENV_NAME_RE = /^[A-Z_][A-Z0-9_]{0,63}$/;
49
+ export const TASK_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
50
+ export const RUNNER_TOKENS = ['{promptFile}', '{taskSlug}', '{teamRoot}'];
51
+ /**
52
+ * The seeded runner: the OpenCode CLI the shipped app runs next to. It is
53
+ * written only when `team/runner.json` is absent; an operator config always
54
+ * wins. The prompt file is generated, but the command itself is the message.
55
+ */
56
+ export const DEFAULT_RUNNER = [
57
+ 'opencode',
58
+ 'run',
59
+ '--format',
60
+ 'json',
61
+ '/task-continue',
62
+ '{taskSlug}',
63
+ ];
64
+ const BASE_ENV_NAMES = ['PATH', 'HOME', 'TMPDIR', 'LANG', 'TZ'];
65
+
66
+ const moduleDirectory = path.dirname(fileURLToPath(import.meta.url));
67
+
68
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
69
+ const reject = (code, message) => teamDbFail(code, message, 1);
70
+ const nowIso = () => new Date().toISOString();
71
+
72
+ export const newRunId = () => {
73
+ const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z');
74
+ return `${stamp}-${crypto.randomBytes(4).toString('hex')}`;
75
+ };
76
+
77
+ export const runnerConfigPath = (teamRoot) => path.join(teamRoot, RUNNER_FILE);
78
+ export const taskRunsRoot = (teamRoot) => path.join(teamRoot, TASK_RUNS_DIR);
79
+ export const taskRunDir = (teamRoot, taskSlug, runId) => path.join(taskRunsRoot(teamRoot), taskSlug, runId);
80
+ export const taskRunManifestPath = (teamRoot, taskSlug, runId) => path.join(taskRunDir(teamRoot, taskSlug, runId), RUN_MANIFEST_FILE);
81
+ export const taskStopPath = (teamRoot, taskSlug) => path.join(teamRoot, 'tasks', taskSlug, 'STOP');
82
+
83
+ const validateArgv = (value, label) => {
84
+ if (!Array.isArray(value) || value.length === 0 || value.length > MAX_ARGV_ELEMENTS) {
85
+ reject('E_VALIDATION', `${label} must be an array of 1-${MAX_ARGV_ELEMENTS} strings`);
86
+ }
87
+ for (const element of value) {
88
+ if (typeof element !== 'string' || element.length === 0 || element.length > MAX_ARGV_ELEMENT_LENGTH) {
89
+ reject('E_VALIDATION', `${label} elements must be 1-${MAX_ARGV_ELEMENT_LENGTH} characters`);
90
+ }
91
+ }
92
+ const tokens = value.filter((element) => RUNNER_TOKENS.some((token) => element.includes(token)));
93
+ if (tokens.length === 0) reject('E_VALIDATION', `${label} needs {promptFile}, {taskSlug} or {teamRoot}`);
94
+ return [...value];
95
+ };
96
+
97
+ export function validateRunnerConfig(config) {
98
+ if (!isRecord(config)) reject('E_VALIDATION', 'runner.json must be an object');
99
+ if (config.schemaVersion !== RUNNER_SCHEMA_VERSION) {
100
+ reject('E_VALIDATION', `runner.json: schemaVersion must be ${RUNNER_SCHEMA_VERSION}`);
101
+ }
102
+ const runner = validateArgv(config.runner, 'runner.json runner');
103
+ const cwd = config.cwd === undefined ? '../..' : config.cwd;
104
+ if (typeof cwd !== 'string' || cwd === '' || cwd.includes('\0')) reject('E_VALIDATION', 'runner.json: cwd must be a path');
105
+ const timeoutMs = config.timeoutMs === undefined ? DEFAULT_TIMEOUT_MS : config.timeoutMs;
106
+ if (!Number.isInteger(timeoutMs) || timeoutMs < MIN_TIMEOUT_MS || timeoutMs > MAX_TIMEOUT_MS) {
107
+ reject('E_VALIDATION', `runner.json: timeoutMs must be ${MIN_TIMEOUT_MS}..${MAX_TIMEOUT_MS}`);
108
+ }
109
+ const envPassthrough = config.envPassthrough === undefined ? [] : config.envPassthrough;
110
+ if (!Array.isArray(envPassthrough) || envPassthrough.length > MAX_ENV_NAMES) {
111
+ reject('E_VALIDATION', `runner.json: envPassthrough must be an array of at most ${MAX_ENV_NAMES} names`);
112
+ }
113
+ for (const name of envPassthrough) {
114
+ if (typeof name !== 'string' || !ENV_NAME_RE.test(name) || name.startsWith('AI_RULES_TEAM_DB_')) {
115
+ reject('E_VALIDATION', `runner.json: envPassthrough name "${String(name)}" is not allowed`);
116
+ }
117
+ }
118
+ return { schemaVersion: RUNNER_SCHEMA_VERSION, runner, cwd, timeoutMs, envPassthrough: [...envPassthrough] };
119
+ }
120
+
121
+ export function readRunnerConfig(teamRoot) {
122
+ const file = runnerConfigPath(teamRoot);
123
+ if (!fs.existsSync(file)) return null;
124
+ let parsed;
125
+ try {
126
+ parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
127
+ } catch (error) {
128
+ reject('E_VALIDATION', `runner.json is not valid JSON: ${error.message}`);
129
+ }
130
+ return validateRunnerConfig(parsed);
131
+ }
132
+
133
+ /**
134
+ * Seed the default runner when the operator has not written one. The file is
135
+ * created once and never overwritten; `team-db.mjs task-run ensure` calls it, so
136
+ * Continue works without a manual setup step. The `ui` verbs never write it.
137
+ * The kill switch turns the write off like every other projection write.
138
+ */
139
+ export function ensureRunnerConfig(teamRoot) {
140
+ const file = runnerConfigPath(teamRoot);
141
+ if (isKillSwitchSet(process.env)) return { created: false, path: file, config: null, skipped: true };
142
+ if (fs.existsSync(file)) return { created: false, path: file, config: readRunnerConfig(teamRoot) };
143
+ const config = validateRunnerConfig({
144
+ schemaVersion: RUNNER_SCHEMA_VERSION,
145
+ runner: DEFAULT_RUNNER,
146
+ cwd: '../..',
147
+ timeoutMs: DEFAULT_TIMEOUT_MS,
148
+ envPassthrough: [],
149
+ });
150
+ fs.mkdirSync(teamRoot, { recursive: true });
151
+ const temporary = `${file}.tmp`;
152
+ fs.writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
153
+ fs.renameSync(temporary, file);
154
+ return { created: true, path: file, config };
155
+ }
156
+
157
+ const repoRootOf = (teamRoot) => path.resolve(teamRoot, '..', '..');
158
+
159
+ const resolveConfigCwd = (teamRoot, config) => {
160
+ const root = repoRootOf(teamRoot);
161
+ const resolved = path.isAbsolute(config.cwd) ? config.cwd : path.resolve(root, config.cwd);
162
+ const relative = path.relative(root, resolved);
163
+ if (relative.startsWith('..') || path.isAbsolute(relative)) {
164
+ reject('E_VALIDATION', 'runner.json: cwd must stay inside the repository root');
165
+ }
166
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {
167
+ reject('E_VALIDATION', 'runner.json: cwd does not exist');
168
+ }
169
+ return resolved;
170
+ };
171
+
172
+ const childEnvironment = (config, source = process.env) => {
173
+ const env = {};
174
+ for (const name of [...BASE_ENV_NAMES, ...config.envPassthrough]) {
175
+ if (typeof source[name] === 'string') env[name] = source[name];
176
+ }
177
+ return env;
178
+ };
179
+
180
+ export function readRunManifest(teamRoot, taskSlug, runId) {
181
+ try {
182
+ return JSON.parse(fs.readFileSync(taskRunManifestPath(teamRoot, taskSlug, runId), 'utf8'));
183
+ } catch (error) {
184
+ if (error.code === 'ENOENT') return null;
185
+ reject('E_SCHEMA', `task run ${runId} is unreadable: ${error.message}`);
186
+ }
187
+ return null;
188
+ }
189
+
190
+ export function writeRunManifest(teamRoot, taskSlug, runId, manifest) {
191
+ const dir = taskRunDir(teamRoot, taskSlug, runId);
192
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
193
+ const temporary = path.join(dir, `${RUN_MANIFEST_FILE}.tmp`);
194
+ fs.writeFileSync(temporary, `${JSON.stringify(manifest, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
195
+ fs.renameSync(temporary, path.join(dir, RUN_MANIFEST_FILE));
196
+ }
197
+
198
+ export function listTaskRuns(teamRoot, taskSlug) {
199
+ const dir = path.join(taskRunsRoot(teamRoot), taskSlug);
200
+ if (!fs.existsSync(dir)) return [];
201
+ return fs
202
+ .readdirSync(dir, { withFileTypes: true })
203
+ .filter((entry) => entry.isDirectory() && RUN_ID_RE.test(entry.name))
204
+ .map((entry) => readRunManifest(teamRoot, taskSlug, entry.name))
205
+ .filter((manifest) => manifest !== null)
206
+ .sort((left, right) => right.createdAt.localeCompare(left.createdAt));
207
+ }
208
+
209
+ const pidIsAlive = (pid) => {
210
+ if (!Number.isInteger(pid) || pid <= 0) return false;
211
+ try {
212
+ process.kill(pid, 0);
213
+ return true;
214
+ } catch (error) {
215
+ return error.code === 'EPERM';
216
+ }
217
+ };
218
+
219
+ const isStaleRun = (run) => {
220
+ if (!ACTIVE_RUN_STATES.includes(run.state)) return false;
221
+ const age = Date.now() - Date.parse(run.startedAt ?? run.createdAt);
222
+ if (!Number.isFinite(age)) return true;
223
+ if (run.pid === null || run.pid === undefined) return age > CLAIMED_GRACE_MS;
224
+ if (!pidIsAlive(run.pid)) return true;
225
+ return run.state === 'running' && !ownedRunProcess(run.pid, run.taskSlug);
226
+ };
227
+
228
+ /** Mark abandoned manifests as interrupted before a new start or a stop. */
229
+ export function interruptStaleRuns(teamRoot, taskSlug) {
230
+ for (const run of listTaskRuns(teamRoot, taskSlug)) {
231
+ if (!isStaleRun(run)) continue;
232
+ writeRunManifest(teamRoot, taskSlug, run.runId, {
233
+ ...run,
234
+ state: 'interrupted',
235
+ finishedAt: nowIso(),
236
+ error: 'supervisor is no longer alive',
237
+ });
238
+ }
239
+ }
240
+
241
+ export function activeTaskRun(teamRoot, taskSlug) {
242
+ return listTaskRuns(teamRoot, taskSlug).find((run) => ACTIVE_RUN_STATES.includes(run.state) && !isStaleRun(run)) ?? null;
243
+ }
244
+
245
+ const ownedRunProcess = (pid, taskSlug) => {
246
+ if (!pidIsAlive(pid)) return false;
247
+ const result = spawnSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8' });
248
+ if (result.status !== 0) return false;
249
+ const command = result.stdout.trim();
250
+ return /team-db\.mjs\s+task-run\s+supervise\b/.test(command) && command.includes(taskSlug);
251
+ };
252
+
253
+ const linkLanguage = (teamRoot, linkId) => {
254
+ if (typeof linkId !== 'string' || linkId === '') return '';
255
+ try {
256
+ const link = JSON.parse(fs.readFileSync(path.join(teamRoot, 'tracker', 'links', `${linkId}.json`), 'utf8'));
257
+ return typeof link.language === 'string' ? link.language : '';
258
+ } catch {
259
+ return '';
260
+ }
261
+ };
262
+
263
+ const renderPrompt = (taskSlug, language) =>
264
+ `${language === '' ? '' : `<!-- language: ${language} -->\n\n`}/task-continue ${taskSlug}\n`;
265
+
266
+ const spawnSupervisor = (teamRoot, taskSlug, runId) => {
267
+ const script = path.join(moduleDirectory, 'team-db.mjs');
268
+ const child = spawn(
269
+ process.execPath,
270
+ [script, 'task-run', 'supervise', '--run', runId, '--task', taskSlug, '--root', teamRoot],
271
+ {
272
+ cwd: repoRootOf(teamRoot),
273
+ env: process.env,
274
+ detached: true,
275
+ stdio: 'ignore',
276
+ },
277
+ );
278
+ child.unref();
279
+ };
280
+
281
+ const withTaskRunLock = (teamRoot, taskSlug, run) => {
282
+ fs.mkdirSync(taskRunsRoot(teamRoot), { recursive: true, mode: 0o700 });
283
+ const lockPath = path.join(taskRunsRoot(teamRoot), taskSlug, '.start.lock');
284
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true, mode: 0o700 });
285
+ let token = null;
286
+ try {
287
+ token = acquireLock(lockPath, { timeoutMs: START_LOCK_TIMEOUT_MS });
288
+ } catch (error) {
289
+ reject('E_RUNNER_BUSY', `could not claim the task runner lock for ${taskSlug}: ${error.message}`);
290
+ }
291
+ try {
292
+ return run();
293
+ } finally {
294
+ releaseLock(lockPath, token);
295
+ }
296
+ };
297
+
298
+ export function startTaskRun(teamRoot, options = {}) {
299
+ const { taskSlug } = options;
300
+ if (typeof taskSlug !== 'string' || !TASK_SLUG_RE.test(taskSlug) || taskSlug.length > 48) {
301
+ reject('E_VALIDATION', 'taskSlug must match the slug grammar');
302
+ }
303
+ return withTaskRunLock(teamRoot, taskSlug, () => {
304
+ interruptStaleRuns(teamRoot, taskSlug);
305
+ return startTaskRunLocked(teamRoot, options);
306
+ });
307
+ }
308
+
309
+ const startTaskRunLocked = (teamRoot, { taskSlug, itemId = null, linkId = null } = {}) => {
310
+ if (typeof taskSlug !== 'string' || !TASK_SLUG_RE.test(taskSlug) || taskSlug.length > 48) {
311
+ reject('E_VALIDATION', 'taskSlug must match the slug grammar');
312
+ }
313
+ const config = readRunnerConfig(teamRoot);
314
+ if (config === null) reject('E_RUNNER_OFFLINE', 'team/runner.json is absent; configure a runner to continue a task');
315
+ const taskDir = path.join(teamRoot, 'tasks', taskSlug);
316
+ if (!fs.existsSync(taskDir)) reject('E_NOT_FOUND', `task ${taskSlug} does not exist`);
317
+ const active = activeTaskRun(teamRoot, taskSlug);
318
+ if (active !== null) reject('E_RUNNER_RUNNING', `task ${taskSlug} already has an active run ${active.runId}`);
319
+ const runId = newRunId();
320
+ const dir = taskRunDir(teamRoot, taskSlug, runId);
321
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
322
+ const prompt = renderPrompt(taskSlug, linkLanguage(teamRoot, linkId));
323
+ if (Buffer.byteLength(prompt, 'utf8') > MAX_PROMPT_BYTES) reject('E_VALIDATION', 'the rendered prompt is too large');
324
+ const promptPath = path.join(dir, RUN_PROMPT_FILE);
325
+ fs.writeFileSync(promptPath, prompt, { encoding: 'utf8', mode: 0o600 });
326
+ const cwd = resolveConfigCwd(teamRoot, config);
327
+ const argv = config.runner.map((element) =>
328
+ element
329
+ .replaceAll('{promptFile}', promptPath)
330
+ .replaceAll('{taskSlug}', taskSlug)
331
+ .replaceAll('{teamRoot}', teamRoot),
332
+ );
333
+ const manifest = {
334
+ schemaVersion: 1,
335
+ runId,
336
+ taskSlug,
337
+ itemId,
338
+ linkId,
339
+ trigger: 'continue',
340
+ state: 'claimed',
341
+ createdAt: nowIso(),
342
+ startedAt: null,
343
+ finishedAt: null,
344
+ pid: null,
345
+ exitCode: null,
346
+ signal: null,
347
+ argv,
348
+ cwd,
349
+ timeoutMs: config.timeoutMs,
350
+ promptPath: path.relative(teamRoot, promptPath),
351
+ logs: {
352
+ stdout: { path: path.relative(teamRoot, path.join(dir, RUN_STDOUT_FILE)), bytes: 0, truncated: false },
353
+ stderr: { path: path.relative(teamRoot, path.join(dir, RUN_STDERR_FILE)), bytes: 0, truncated: false },
354
+ },
355
+ error: null,
356
+ };
357
+ writeRunManifest(teamRoot, taskSlug, runId, manifest);
358
+ try {
359
+ fs.rmSync(taskStopPath(teamRoot, taskSlug), { force: true });
360
+ } catch {}
361
+ spawnSupervisor(teamRoot, taskSlug, runId);
362
+ return { runId, taskSlug, state: 'claimed', promptPath: manifest.promptPath };
363
+ }
364
+
365
+ const finishRun = (teamRoot, taskSlug, runId, manifest, extra) => {
366
+ const finishedAt = nowIso();
367
+ const next = {
368
+ ...manifest,
369
+ ...extra,
370
+ finishedAt,
371
+ durationMs: Math.max(0, Date.parse(finishedAt) - Date.parse(manifest.startedAt ?? manifest.createdAt)),
372
+ };
373
+ writeRunManifest(teamRoot, taskSlug, runId, next);
374
+ return next;
375
+ };
376
+
377
+ export async function superviseTaskRun(teamRoot, taskSlug, runId) {
378
+ const manifest = readRunManifest(teamRoot, taskSlug, runId);
379
+ if (manifest === null) reject('E_NOT_FOUND', `no task run ${runId}`);
380
+ if (manifest.state !== 'claimed') return manifest;
381
+ const config = readRunnerConfig(teamRoot);
382
+ if (config === null) return finishRun(teamRoot, taskSlug, runId, manifest, { state: 'failed', error: 'E_RUNNER_OFFLINE' });
383
+ const dir = taskRunDir(teamRoot, taskSlug, runId);
384
+ const promptPath = path.join(teamRoot, manifest.promptPath);
385
+ const cwd = resolveConfigCwd(teamRoot, config);
386
+ const argv = config.runner.map((element) =>
387
+ element
388
+ .replaceAll('{promptFile}', promptPath)
389
+ .replaceAll('{taskSlug}', taskSlug)
390
+ .replaceAll('{teamRoot}', teamRoot),
391
+ );
392
+ const stdout = new CappedLogWriter(path.join(dir, RUN_STDOUT_FILE), MAX_RUN_LOG_BYTES);
393
+ const stderr = new CappedLogWriter(path.join(dir, RUN_STDERR_FILE), MAX_RUN_LOG_BYTES);
394
+ const env = childEnvironment(config);
395
+ const startedAt = nowIso();
396
+ let child;
397
+ try {
398
+ child = spawn(argv[0], argv.slice(1), {
399
+ cwd,
400
+ env,
401
+ detached: true,
402
+ stdio: ['ignore', 'pipe', 'pipe'],
403
+ });
404
+ } catch (error) {
405
+ stdout.end();
406
+ stderr.end();
407
+ return finishRun(teamRoot, taskSlug, runId, manifest, { state: 'failed', error: `spawn: ${error.message}` });
408
+ }
409
+ child.stdout.pipe(stdout);
410
+ child.stderr.pipe(stderr);
411
+ const running = {
412
+ ...manifest,
413
+ state: 'running',
414
+ startedAt,
415
+ pid: child.pid ?? null,
416
+ argv,
417
+ cwd,
418
+ };
419
+ writeRunManifest(teamRoot, taskSlug, runId, running);
420
+ let timedOut = false;
421
+ const timer = setTimeout(() => {
422
+ timedOut = true;
423
+ try {
424
+ process.kill(-child.pid, 'SIGTERM');
425
+ } catch {
426
+ try { child.kill('SIGTERM'); } catch {}
427
+ }
428
+ setTimeout(() => {
429
+ try { process.kill(-child.pid, 'SIGKILL'); } catch {}
430
+ }, STOP_GRACE_MS).unref();
431
+ }, config.timeoutMs);
432
+ timer.unref();
433
+ const result = await new Promise((resolve) => {
434
+ child.on('error', (error) => resolve({ code: null, signal: null, error }));
435
+ child.on('close', (code, signal) => resolve({ code, signal, error: null }));
436
+ });
437
+ clearTimeout(timer);
438
+ await Promise.all([
439
+ new Promise((resolve) => (stdout.finalized ? resolve() : stdout.once('finish', resolve))),
440
+ new Promise((resolve) => (stderr.finalized ? resolve() : stderr.once('finish', resolve))),
441
+ ]);
442
+ const state = timedOut ? 'timeout' : result.error || result.code !== 0 ? 'failed' : 'succeeded';
443
+ return finishRun(teamRoot, taskSlug, runId, running, {
444
+ state,
445
+ exitCode: result.code,
446
+ signal: result.signal,
447
+ error: result.error ? result.error.message : null,
448
+ logs: {
449
+ stdout: { path: manifest.logs.stdout.path, bytes: stdout.bytes, truncated: stdout.truncated },
450
+ stderr: { path: manifest.logs.stderr.path, bytes: stderr.bytes, truncated: stderr.truncated },
451
+ },
452
+ });
453
+ }
454
+
455
+ export function stopTaskRun(teamRoot, taskSlug) {
456
+ if (typeof taskSlug !== 'string' || !TASK_SLUG_RE.test(taskSlug)) {
457
+ reject('E_VALIDATION', 'taskSlug must match the slug grammar');
458
+ }
459
+ const rawActive = listTaskRuns(teamRoot, taskSlug).find((run) => ACTIVE_RUN_STATES.includes(run.state));
460
+ if (rawActive && typeof rawActive.pid === 'number' && pidIsAlive(rawActive.pid) && !ownedRunProcess(rawActive.pid, taskSlug)) {
461
+ return {
462
+ ok: false,
463
+ code: 'E_RUNNER_PID_MISMATCH',
464
+ message: `run ${rawActive.runId} pid ${rawActive.pid} is no longer the supervisor for ${taskSlug}`,
465
+ stopped: false,
466
+ sentinel: false,
467
+ runId: rawActive.runId,
468
+ };
469
+ }
470
+ interruptStaleRuns(teamRoot, taskSlug);
471
+ const taskDir = path.join(teamRoot, 'tasks', taskSlug);
472
+ if (fs.existsSync(taskDir)) {
473
+ fs.writeFileSync(taskStopPath(teamRoot, taskSlug), `${JSON.stringify({ at: nowIso(), reason: 'operator stop' })}\n`);
474
+ }
475
+ const active = activeTaskRun(teamRoot, taskSlug);
476
+ if (active === null) return { ok: true, stopped: false, sentinel: fs.existsSync(path.join(taskDir, 'STOP')), runId: null };
477
+ if (active.pid === null || active.pid === undefined) {
478
+ writeRunManifest(teamRoot, taskSlug, active.runId, {
479
+ ...active,
480
+ state: 'interrupted',
481
+ finishedAt: nowIso(),
482
+ error: 'stopped before the supervisor claimed a pid',
483
+ });
484
+ return { ok: true, stopped: true, sentinel: true, runId: active.runId };
485
+ }
486
+ if (!ownedRunProcess(active.pid, taskSlug)) {
487
+ return {
488
+ ok: false,
489
+ code: 'E_RUNNER_PID_MISMATCH',
490
+ message: `run ${active.runId} pid ${active.pid} is no longer the supervisor for ${taskSlug}`,
491
+ stopped: false,
492
+ sentinel: true,
493
+ runId: active.runId,
494
+ };
495
+ }
496
+ if (typeof active.pid === 'number') {
497
+ try {
498
+ process.kill(-active.pid, 'SIGTERM');
499
+ } catch {
500
+ try { process.kill(active.pid, 'SIGTERM'); } catch {}
501
+ }
502
+ setTimeout(() => {
503
+ try { process.kill(-active.pid, 'SIGKILL'); } catch {}
504
+ }, STOP_GRACE_MS).unref();
505
+ }
506
+ return { ok: true, stopped: true, sentinel: true, runId: active.runId };
507
+ }
508
+
509
+ export function runnerStatus(teamRoot) {
510
+ const config = readRunnerConfig(teamRoot);
511
+ return config === null ? { configured: false } : { configured: true, cwd: config.cwd, timeoutMs: config.timeoutMs };
512
+ }
513
+
514
+ export function runTaskRunnerCommand(subcommand, options = {}) {
515
+ const teamRoot = path.resolve(options.root || DEFAULT_TEAM_ROOT);
516
+ const json = Boolean(options.json);
517
+ if (subcommand === 'start') {
518
+ const run = startTaskRun(teamRoot, {
519
+ taskSlug: options.task,
520
+ itemId: options.item ?? null,
521
+ linkId: options.link ?? null,
522
+ });
523
+ return { output: json ? `${JSON.stringify({ ok: true, run })}\n` : '', exitCode: 0 };
524
+ }
525
+ if (subcommand === 'stop') {
526
+ const result = stopTaskRun(teamRoot, options.task);
527
+ return {
528
+ output: json ? `${JSON.stringify(result)}\n` : result.ok ? '' : `${result.code}: ${result.message}\n`,
529
+ exitCode: result.ok ? 0 : 1,
530
+ };
531
+ }
532
+ if (subcommand === 'supervise') {
533
+ // The detached supervisor is the one caller that waits for the agent.
534
+ return superviseTaskRun(teamRoot, options.task, options.run).then((manifest) => ({
535
+ output: json ? `${JSON.stringify({ ok: true, run: manifest })}\n` : '',
536
+ exitCode: 0,
537
+ }));
538
+ }
539
+ if (subcommand === 'list') {
540
+ const runs = listTaskRuns(teamRoot, options.task);
541
+ return { output: json ? `${JSON.stringify({ ok: true, runs })}\n` : '', exitCode: 0 };
542
+ }
543
+ if (subcommand === 'show') {
544
+ const run = readRunManifest(teamRoot, options.task, options.run);
545
+ if (run === null) reject('E_NOT_FOUND', `no task run ${options.run}`);
546
+ return { output: json ? `${JSON.stringify({ ok: true, run })}\n` : '', exitCode: 0 };
547
+ }
548
+ if (subcommand === 'status') {
549
+ return { output: json ? `${JSON.stringify({ ok: true, ...runnerStatus(teamRoot) })}\n` : '', exitCode: 0 };
550
+ }
551
+ if (subcommand === 'ensure') {
552
+ const result = ensureRunnerConfig(teamRoot);
553
+ return {
554
+ output: json
555
+ ? `${JSON.stringify({ ok: true, ...result })}\n`
556
+ : result.skipped
557
+ ? 'task-run: seeding skipped (AI_RULES_TEAM_DB_DISABLE)\n'
558
+ : result.created
559
+ ? `task-run: seeded ${result.path}\n`
560
+ : result.config !== null
561
+ ? `task-run: ${result.path} already exists\n`
562
+ : `task-run: not seeded (${result.reason ?? 'runner is disabled'})\n`,
563
+ exitCode: 0,
564
+ };
565
+ }
566
+ throw new TeamDbError('E_USAGE', `unknown task-run subcommand "${subcommand}"`, 3);
567
+ }