@bonesofspring/ai-rules 0.2.60 → 0.2.61

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 (433) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +59 -26
  3. package/bin/cli.js +368 -59
  4. package/bin/lib/ai-local-drift.js +18 -0
  5. package/bin/lib/engine-scripts.js +22 -5
  6. package/bin/lib/engine-upgrade.js +279 -0
  7. package/bin/lib/mcp/catalog.js +66 -5
  8. package/bin/lib/mcp/clients.js +4 -4
  9. package/bin/lib/mcp/credentials.js +88 -0
  10. package/bin/lib/mcp/doctor.js +100 -8
  11. package/bin/lib/mcp/npx.js +17 -0
  12. package/bin/lib/mcp/registry.js +2 -0
  13. package/bin/lib/merged-config.js +38 -0
  14. package/bin/lib/seed-ai-local-team.js +29 -14
  15. package/docs/MCP-CATALOG.md +30 -2
  16. package/docs/MCP-SETUP.md +30 -6
  17. package/docs/OPENCODE.md +22 -2
  18. package/docs/PLATFORMS.md +38 -0
  19. package/docs/PRESET-CONTRIBUTION.md +11 -1
  20. package/docs/TEAM-DB.md +187 -20
  21. package/docs/openapi/team-db.v1.json +4443 -2083
  22. package/mcp/defectdojo-mcp.mjs +353 -0
  23. package/mcp/gitlab.mjs +5 -1
  24. package/mcp/lib/defectdojo.mjs +249 -0
  25. package/mcp/lib/yandex.mjs +39 -15
  26. package/package.json +9 -3
  27. package/presets/_shared/ai-local/scripts/lock.mjs +139 -19
  28. package/presets/_shared/ai-local/scripts/signals.mjs +17 -1
  29. package/presets/_shared/ai-local/scripts/team-db-api.mjs +496 -67
  30. package/presets/_shared/ai-local/scripts/team-db-dashboard.mjs +816 -5
  31. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +761 -6
  32. package/presets/_shared/ai-local/scripts/team-db-project.mjs +10 -0
  33. package/presets/_shared/ai-local/scripts/team-db-scheduler.mjs +2360 -0
  34. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +87 -0
  35. package/presets/_shared/ai-local/scripts/team-db.mjs +151 -9
  36. package/presets/_shared/ai-local/scripts/upstream-research.mjs +2961 -0
  37. package/presets/_shared/core/agent-team/agent-artifact-contracts.md +13 -0
  38. package/presets/_shared/hooks/README.md +23 -3
  39. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +57 -3
  40. package/presets/{claude/nuxt/hooks/guard-shell-command.sh → _shared/hooks/guard-shell-command.mjs.tmpl} +29 -35
  41. package/presets/_shared/hooks/run-hook.mjs +102 -0
  42. package/presets/claude/android-kotlin/hooks/README.md +4 -3
  43. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +57 -3
  44. package/presets/claude/android-kotlin/hooks/examples/README.md +2 -2
  45. package/presets/claude/android-kotlin/hooks/guard-shell-command.mjs +96 -0
  46. package/presets/claude/android-kotlin/hooks/run-hook.mjs +102 -0
  47. package/presets/claude/android-kotlin/settings.json +2 -2
  48. package/presets/claude/android-kotlin/team/README.md +5 -0
  49. package/presets/claude/go/hooks/README.md +4 -3
  50. package/presets/claude/go/hooks/chain-team-phases.sh +57 -3
  51. package/presets/claude/go/hooks/examples/README.md +2 -2
  52. package/presets/claude/go/hooks/guard-shell-command.mjs +95 -0
  53. package/presets/claude/go/hooks/run-hook.mjs +102 -0
  54. package/presets/claude/go/settings.json +2 -2
  55. package/presets/claude/go/team/README.md +5 -0
  56. package/presets/claude/ios-swift/hooks/README.md +4 -3
  57. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +57 -3
  58. package/presets/claude/ios-swift/hooks/examples/README.md +2 -2
  59. package/presets/claude/ios-swift/hooks/guard-shell-command.mjs +95 -0
  60. package/presets/claude/ios-swift/hooks/run-hook.mjs +102 -0
  61. package/presets/claude/ios-swift/settings.json +2 -2
  62. package/presets/claude/ios-swift/team/README.md +5 -0
  63. package/presets/claude/java/hooks/README.md +4 -3
  64. package/presets/claude/java/hooks/chain-team-phases.sh +57 -3
  65. package/presets/claude/java/hooks/examples/README.md +2 -2
  66. package/presets/claude/java/hooks/{guard-shell-command.sh → guard-shell-command.mjs} +31 -38
  67. package/presets/claude/java/hooks/run-hook.mjs +102 -0
  68. package/presets/claude/java/settings.json +2 -2
  69. package/presets/claude/java/team/README.md +5 -0
  70. package/presets/claude/mcp-ts/hooks/README.md +4 -3
  71. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +57 -3
  72. package/presets/claude/mcp-ts/hooks/examples/README.md +1 -1
  73. package/presets/claude/mcp-ts/hooks/guard-shell-command.mjs +95 -0
  74. package/presets/claude/mcp-ts/hooks/run-hook.mjs +102 -0
  75. package/presets/claude/mcp-ts/settings.json +2 -2
  76. package/presets/claude/mcp-ts/team/README.md +5 -0
  77. package/presets/claude/mol/hooks/README.md +20 -0
  78. package/presets/claude/mol/hooks/chain-team-phases.sh +57 -3
  79. package/presets/claude/{svelte/hooks/guard-shell-command.sh → mol/hooks/guard-shell-command.mjs} +29 -35
  80. package/presets/claude/mol/hooks/run-hook.mjs +102 -0
  81. package/presets/claude/mol/settings.json +2 -2
  82. package/presets/claude/mol/team/README.md +5 -0
  83. package/presets/claude/next/agents/build-verifier.md +2 -0
  84. package/presets/claude/next/agents/code-reviewer.md +2 -0
  85. package/presets/claude/next/agents/feature-developer.md +1 -0
  86. package/presets/claude/next/agents/task-analyst.md +4 -0
  87. package/presets/claude/next/agents/task-router.md +5 -3
  88. package/presets/claude/next/commands/README.md +1 -0
  89. package/presets/claude/next/commands/task-continue.md +1 -1
  90. package/presets/claude/next/commands/upstream-research.md +23 -0
  91. package/presets/claude/next/hooks/README.md +4 -3
  92. package/presets/claude/next/hooks/chain-team-phases.sh +57 -3
  93. package/presets/claude/next/hooks/examples/README.md +2 -2
  94. package/presets/claude/next/hooks/guard-shell-command.mjs +94 -0
  95. package/presets/claude/next/hooks/run-hook.mjs +102 -0
  96. package/presets/claude/next/settings.json +2 -2
  97. package/presets/claude/next/team/README.md +23 -0
  98. package/presets/claude/next/team/upstream/config.json +31 -0
  99. package/presets/claude/next/team/upstream/digest-template.md +55 -0
  100. package/presets/claude/next/team/upstream/opencode.json +34 -0
  101. package/presets/claude/next/team/upstream/projects.json +4 -0
  102. package/presets/claude/next/team/upstream/prompt.md +77 -0
  103. package/presets/claude/next/team/upstream/signatures.json +9 -0
  104. package/presets/claude/nuxt/hooks/README.md +4 -3
  105. package/presets/claude/nuxt/hooks/chain-team-phases.sh +57 -3
  106. package/presets/claude/nuxt/hooks/examples/README.md +2 -2
  107. package/presets/claude/{ios-swift/hooks/guard-shell-command.sh → nuxt/hooks/guard-shell-command.mjs} +29 -37
  108. package/presets/claude/nuxt/hooks/run-hook.mjs +102 -0
  109. package/presets/claude/nuxt/settings.json +2 -2
  110. package/presets/claude/nuxt/team/README.md +5 -0
  111. package/presets/claude/php-hexagonal/hooks/README.md +4 -3
  112. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +57 -3
  113. package/presets/claude/php-hexagonal/hooks/examples/README.md +2 -2
  114. package/presets/claude/php-hexagonal/hooks/guard-shell-command.mjs +96 -0
  115. package/presets/claude/php-hexagonal/hooks/run-hook.mjs +102 -0
  116. package/presets/claude/php-hexagonal/settings.json +2 -2
  117. package/presets/claude/php-hexagonal/team/README.md +5 -0
  118. package/presets/claude/php-laravel/hooks/README.md +4 -3
  119. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +57 -3
  120. package/presets/claude/php-laravel/hooks/examples/README.md +2 -2
  121. package/presets/claude/php-laravel/hooks/guard-shell-command.mjs +96 -0
  122. package/presets/claude/php-laravel/hooks/run-hook.mjs +102 -0
  123. package/presets/claude/php-laravel/settings.json +2 -2
  124. package/presets/claude/php-laravel/team/README.md +5 -0
  125. package/presets/claude/svelte/hooks/README.md +4 -3
  126. package/presets/claude/svelte/hooks/chain-team-phases.sh +57 -3
  127. package/presets/claude/svelte/hooks/examples/README.md +2 -2
  128. package/presets/claude/svelte/hooks/guard-shell-command.mjs +94 -0
  129. package/presets/claude/svelte/hooks/run-hook.mjs +102 -0
  130. package/presets/claude/svelte/settings.json +2 -2
  131. package/presets/claude/svelte/team/README.md +5 -0
  132. package/presets/cursor/android-kotlin/hooks/README.md +2 -1
  133. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +57 -3
  134. package/presets/cursor/android-kotlin/hooks/examples/README.md +1 -1
  135. package/presets/cursor/android-kotlin/hooks/guard-shell-command.mjs +96 -0
  136. package/presets/cursor/android-kotlin/hooks/run-hook.mjs +102 -0
  137. package/presets/cursor/android-kotlin/hooks.json +2 -2
  138. package/presets/cursor/android-kotlin/team/README.md +5 -0
  139. package/presets/cursor/go/hooks/README.md +2 -1
  140. package/presets/cursor/go/hooks/chain-team-phases.sh +57 -3
  141. package/presets/cursor/go/hooks/examples/README.md +1 -1
  142. package/presets/cursor/go/hooks/guard-shell-command.mjs +95 -0
  143. package/presets/cursor/go/hooks/run-hook.mjs +102 -0
  144. package/presets/cursor/go/hooks.json +2 -2
  145. package/presets/cursor/go/team/README.md +5 -0
  146. package/presets/cursor/ios-swift/hooks/README.md +2 -1
  147. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +57 -3
  148. package/presets/cursor/ios-swift/hooks/examples/README.md +1 -1
  149. package/presets/cursor/ios-swift/hooks/guard-shell-command.mjs +95 -0
  150. package/presets/cursor/ios-swift/hooks/run-hook.mjs +102 -0
  151. package/presets/cursor/ios-swift/hooks.json +2 -2
  152. package/presets/cursor/ios-swift/team/README.md +5 -0
  153. package/presets/cursor/java/hooks/README.md +2 -1
  154. package/presets/cursor/java/hooks/chain-team-phases.sh +57 -3
  155. package/presets/cursor/java/hooks/examples/README.md +1 -1
  156. package/presets/cursor/java/hooks/guard-shell-command.mjs +96 -0
  157. package/presets/cursor/java/hooks/run-hook.mjs +102 -0
  158. package/presets/cursor/java/hooks.json +2 -2
  159. package/presets/cursor/java/team/README.md +5 -0
  160. package/presets/cursor/mcp-ts/hooks/README.md +2 -1
  161. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +57 -3
  162. package/presets/cursor/mcp-ts/hooks/guard-shell-command.mjs +95 -0
  163. package/presets/cursor/mcp-ts/hooks/run-hook.mjs +102 -0
  164. package/presets/cursor/mcp-ts/hooks.json +2 -2
  165. package/presets/cursor/mcp-ts/team/README.md +5 -0
  166. package/presets/cursor/mol/hooks/README.md +2 -1
  167. package/presets/cursor/mol/hooks/chain-team-phases.sh +57 -3
  168. package/presets/cursor/mol/hooks/examples/README.md +1 -1
  169. package/presets/{claude/next/hooks/guard-shell-command.sh → cursor/mol/hooks/guard-shell-command.mjs} +29 -35
  170. package/presets/cursor/mol/hooks/run-hook.mjs +102 -0
  171. package/presets/cursor/mol/hooks.json +2 -2
  172. package/presets/cursor/mol/team/README.md +5 -0
  173. package/presets/cursor/next/agents/build-verifier.md +2 -0
  174. package/presets/cursor/next/agents/code-reviewer.md +2 -0
  175. package/presets/cursor/next/agents/feature-developer.md +1 -0
  176. package/presets/cursor/next/agents/task-analyst.md +4 -0
  177. package/presets/cursor/next/agents/task-router.md +5 -3
  178. package/presets/cursor/next/commands/README.md +1 -0
  179. package/presets/cursor/next/commands/task-continue.md +1 -1
  180. package/presets/cursor/next/commands/upstream-research.md +23 -0
  181. package/presets/cursor/next/hooks/README.md +2 -1
  182. package/presets/cursor/next/hooks/chain-team-phases.sh +57 -3
  183. package/presets/cursor/next/hooks/examples/README.md +1 -1
  184. package/presets/cursor/next/hooks/guard-shell-command.mjs +94 -0
  185. package/presets/cursor/next/hooks/run-hook.mjs +102 -0
  186. package/presets/cursor/next/hooks.json +2 -2
  187. package/presets/cursor/next/team/README.md +23 -0
  188. package/presets/cursor/next/team/upstream/config.json +31 -0
  189. package/presets/cursor/next/team/upstream/digest-template.md +55 -0
  190. package/presets/cursor/next/team/upstream/opencode.json +34 -0
  191. package/presets/cursor/next/team/upstream/projects.json +4 -0
  192. package/presets/cursor/next/team/upstream/prompt.md +77 -0
  193. package/presets/cursor/next/team/upstream/signatures.json +9 -0
  194. package/presets/cursor/nuxt/hooks/README.md +2 -1
  195. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +57 -3
  196. package/presets/cursor/nuxt/hooks/examples/README.md +1 -1
  197. package/presets/cursor/nuxt/hooks/guard-shell-command.mjs +94 -0
  198. package/presets/cursor/nuxt/hooks/run-hook.mjs +102 -0
  199. package/presets/cursor/nuxt/hooks.json +2 -2
  200. package/presets/cursor/nuxt/team/README.md +5 -0
  201. package/presets/cursor/php-hexagonal/hooks/README.md +2 -1
  202. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +57 -3
  203. package/presets/cursor/php-hexagonal/hooks/examples/README.md +1 -1
  204. package/presets/cursor/php-hexagonal/hooks/guard-shell-command.mjs +96 -0
  205. package/presets/cursor/php-hexagonal/hooks/run-hook.mjs +102 -0
  206. package/presets/cursor/php-hexagonal/hooks.json +2 -2
  207. package/presets/cursor/php-hexagonal/team/README.md +5 -0
  208. package/presets/cursor/php-laravel/hooks/README.md +2 -1
  209. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +57 -3
  210. package/presets/cursor/php-laravel/hooks/examples/README.md +1 -1
  211. package/presets/cursor/php-laravel/hooks/guard-shell-command.mjs +96 -0
  212. package/presets/cursor/php-laravel/hooks/run-hook.mjs +102 -0
  213. package/presets/cursor/php-laravel/hooks.json +2 -2
  214. package/presets/cursor/php-laravel/team/README.md +5 -0
  215. package/presets/cursor/svelte/hooks/README.md +2 -1
  216. package/presets/cursor/svelte/hooks/chain-team-phases.sh +57 -3
  217. package/presets/cursor/svelte/hooks/examples/README.md +1 -1
  218. package/presets/cursor/svelte/hooks/guard-shell-command.mjs +94 -0
  219. package/presets/cursor/svelte/hooks/run-hook.mjs +102 -0
  220. package/presets/cursor/svelte/hooks.json +2 -2
  221. package/presets/cursor/svelte/team/README.md +5 -0
  222. package/presets/mavis/android-kotlin/adapter-map.json +11 -3
  223. package/presets/mavis/android-kotlin/hooks/README.md +2 -1
  224. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +57 -3
  225. package/presets/mavis/android-kotlin/team/README.md +5 -0
  226. package/presets/mavis/go/adapter-map.json +11 -3
  227. package/presets/mavis/go/hooks/README.md +2 -1
  228. package/presets/mavis/go/hooks/chain-team-phases.sh +57 -3
  229. package/presets/mavis/go/team/README.md +5 -0
  230. package/presets/mavis/ios-swift/adapter-map.json +11 -3
  231. package/presets/mavis/ios-swift/hooks/README.md +2 -1
  232. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +57 -3
  233. package/presets/mavis/ios-swift/team/README.md +5 -0
  234. package/presets/mavis/java/adapter-map.json +11 -3
  235. package/presets/mavis/java/hooks/README.md +2 -1
  236. package/presets/mavis/java/hooks/chain-team-phases.sh +57 -3
  237. package/presets/mavis/java/team/README.md +5 -0
  238. package/presets/mavis/mcp-ts/adapter-map.json +11 -3
  239. package/presets/mavis/mcp-ts/hooks/README.md +2 -1
  240. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +57 -3
  241. package/presets/mavis/mcp-ts/team/README.md +5 -0
  242. package/presets/mavis/mol/adapter-map.json +11 -3
  243. package/presets/mavis/mol/hooks/README.md +2 -1
  244. package/presets/mavis/mol/hooks/chain-team-phases.sh +57 -3
  245. package/presets/mavis/mol/team/README.md +5 -0
  246. package/presets/mavis/next/adapter-map.json +67 -3
  247. package/presets/mavis/next/agents/build-verifier.md +2 -0
  248. package/presets/mavis/next/agents/code-reviewer.md +2 -0
  249. package/presets/mavis/next/agents/feature-developer.md +1 -0
  250. package/presets/mavis/next/agents/task-analyst.md +4 -0
  251. package/presets/mavis/next/agents/task-router.md +5 -3
  252. package/presets/mavis/next/commands/README.md +1 -0
  253. package/presets/mavis/next/commands/task-continue.md +1 -1
  254. package/presets/mavis/next/commands/upstream-research.md +18 -0
  255. package/presets/mavis/next/hooks/README.md +2 -1
  256. package/presets/mavis/next/hooks/chain-team-phases.sh +57 -3
  257. package/presets/mavis/next/team/README.md +23 -0
  258. package/presets/mavis/next/team/upstream/config.json +31 -0
  259. package/presets/mavis/next/team/upstream/digest-template.md +55 -0
  260. package/presets/mavis/next/team/upstream/opencode.json +34 -0
  261. package/presets/mavis/next/team/upstream/projects.json +4 -0
  262. package/presets/mavis/next/team/upstream/prompt.md +77 -0
  263. package/presets/mavis/next/team/upstream/signatures.json +9 -0
  264. package/presets/mavis/nuxt/adapter-map.json +11 -3
  265. package/presets/mavis/nuxt/hooks/README.md +2 -1
  266. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +57 -3
  267. package/presets/mavis/nuxt/team/README.md +5 -0
  268. package/presets/mavis/php-hexagonal/adapter-map.json +11 -3
  269. package/presets/mavis/php-hexagonal/hooks/README.md +2 -1
  270. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +57 -3
  271. package/presets/mavis/php-hexagonal/team/README.md +5 -0
  272. package/presets/mavis/php-laravel/adapter-map.json +11 -3
  273. package/presets/mavis/php-laravel/hooks/README.md +2 -1
  274. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +57 -3
  275. package/presets/mavis/php-laravel/team/README.md +5 -0
  276. package/presets/mavis/svelte/adapter-map.json +11 -3
  277. package/presets/mavis/svelte/hooks/README.md +2 -1
  278. package/presets/mavis/svelte/hooks/chain-team-phases.sh +57 -3
  279. package/presets/mavis/svelte/team/README.md +5 -0
  280. package/presets/opencode/android-kotlin/OPENCODE.md +1 -1
  281. package/presets/opencode/android-kotlin/README.md +1 -1
  282. package/presets/opencode/android-kotlin/adapter-map.json +11 -3
  283. package/presets/opencode/android-kotlin/hooks/README.md +3 -2
  284. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +57 -3
  285. package/presets/opencode/android-kotlin/team/README.md +5 -0
  286. package/presets/opencode/go/OPENCODE.md +1 -1
  287. package/presets/opencode/go/README.md +1 -1
  288. package/presets/opencode/go/adapter-map.json +11 -3
  289. package/presets/opencode/go/hooks/README.md +3 -2
  290. package/presets/opencode/go/hooks/chain-team-phases.sh +57 -3
  291. package/presets/opencode/go/team/README.md +5 -0
  292. package/presets/opencode/ios-swift/OPENCODE.md +1 -1
  293. package/presets/opencode/ios-swift/README.md +1 -1
  294. package/presets/opencode/ios-swift/adapter-map.json +11 -3
  295. package/presets/opencode/ios-swift/hooks/README.md +3 -2
  296. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +57 -3
  297. package/presets/opencode/ios-swift/team/README.md +5 -0
  298. package/presets/opencode/java/OPENCODE.md +1 -1
  299. package/presets/opencode/java/README.md +1 -1
  300. package/presets/opencode/java/adapter-map.json +11 -3
  301. package/presets/opencode/java/hooks/README.md +3 -2
  302. package/presets/opencode/java/hooks/chain-team-phases.sh +57 -3
  303. package/presets/opencode/java/team/README.md +5 -0
  304. package/presets/opencode/mcp-ts/OPENCODE.md +1 -1
  305. package/presets/opencode/mcp-ts/README.md +1 -1
  306. package/presets/opencode/mcp-ts/adapter-map.json +11 -3
  307. package/presets/opencode/mcp-ts/hooks/README.md +3 -2
  308. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +57 -3
  309. package/presets/opencode/mcp-ts/team/README.md +5 -0
  310. package/presets/opencode/mol/OPENCODE.md +1 -1
  311. package/presets/opencode/mol/README.md +1 -1
  312. package/presets/opencode/mol/adapter-map.json +11 -3
  313. package/presets/opencode/mol/hooks/README.md +3 -2
  314. package/presets/opencode/mol/hooks/chain-team-phases.sh +57 -3
  315. package/presets/opencode/mol/team/README.md +5 -0
  316. package/presets/opencode/next/OPENCODE.md +1 -1
  317. package/presets/opencode/next/README.md +1 -1
  318. package/presets/opencode/next/adapter-map.json +67 -3
  319. package/presets/opencode/next/agents/build-verifier.md +2 -0
  320. package/presets/opencode/next/agents/code-reviewer.md +2 -0
  321. package/presets/opencode/next/agents/feature-developer.md +1 -0
  322. package/presets/opencode/next/agents/task-analyst.md +4 -0
  323. package/presets/opencode/next/agents/task-router.md +5 -3
  324. package/presets/opencode/next/commands/README.md +1 -0
  325. package/presets/opencode/next/commands/task-continue.md +1 -1
  326. package/presets/opencode/next/commands/upstream-research.md +26 -0
  327. package/presets/opencode/next/hooks/README.md +3 -2
  328. package/presets/opencode/next/hooks/chain-team-phases.sh +57 -3
  329. package/presets/opencode/next/team/README.md +23 -0
  330. package/presets/opencode/next/team/upstream/config.json +31 -0
  331. package/presets/opencode/next/team/upstream/digest-template.md +55 -0
  332. package/presets/opencode/next/team/upstream/opencode.json +34 -0
  333. package/presets/opencode/next/team/upstream/projects.json +4 -0
  334. package/presets/opencode/next/team/upstream/prompt.md +77 -0
  335. package/presets/opencode/next/team/upstream/signatures.json +9 -0
  336. package/presets/opencode/nuxt/OPENCODE.md +1 -1
  337. package/presets/opencode/nuxt/README.md +1 -1
  338. package/presets/opencode/nuxt/adapter-map.json +11 -3
  339. package/presets/opencode/nuxt/hooks/README.md +3 -2
  340. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +57 -3
  341. package/presets/opencode/nuxt/team/README.md +5 -0
  342. package/presets/opencode/php-hexagonal/OPENCODE.md +1 -1
  343. package/presets/opencode/php-hexagonal/README.md +1 -1
  344. package/presets/opencode/php-hexagonal/adapter-map.json +11 -3
  345. package/presets/opencode/php-hexagonal/hooks/README.md +3 -2
  346. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +57 -3
  347. package/presets/opencode/php-hexagonal/team/README.md +5 -0
  348. package/presets/opencode/php-laravel/OPENCODE.md +1 -1
  349. package/presets/opencode/php-laravel/README.md +1 -1
  350. package/presets/opencode/php-laravel/adapter-map.json +11 -3
  351. package/presets/opencode/php-laravel/hooks/README.md +3 -2
  352. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +57 -3
  353. package/presets/opencode/php-laravel/team/README.md +5 -0
  354. package/presets/opencode/svelte/OPENCODE.md +1 -1
  355. package/presets/opencode/svelte/README.md +1 -1
  356. package/presets/opencode/svelte/adapter-map.json +11 -3
  357. package/presets/opencode/svelte/hooks/README.md +3 -2
  358. package/presets/opencode/svelte/hooks/chain-team-phases.sh +57 -3
  359. package/presets/opencode/svelte/team/README.md +5 -0
  360. package/presets/zcode/android-kotlin/adapter-map.json +11 -3
  361. package/presets/zcode/android-kotlin/hooks/README.md +2 -1
  362. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +57 -3
  363. package/presets/zcode/android-kotlin/team/README.md +5 -0
  364. package/presets/zcode/go/adapter-map.json +11 -3
  365. package/presets/zcode/go/hooks/README.md +2 -1
  366. package/presets/zcode/go/hooks/chain-team-phases.sh +57 -3
  367. package/presets/zcode/go/team/README.md +5 -0
  368. package/presets/zcode/ios-swift/adapter-map.json +11 -3
  369. package/presets/zcode/ios-swift/hooks/README.md +2 -1
  370. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +57 -3
  371. package/presets/zcode/ios-swift/team/README.md +5 -0
  372. package/presets/zcode/java/adapter-map.json +11 -3
  373. package/presets/zcode/java/hooks/README.md +2 -1
  374. package/presets/zcode/java/hooks/chain-team-phases.sh +57 -3
  375. package/presets/zcode/java/team/README.md +5 -0
  376. package/presets/zcode/mcp-ts/adapter-map.json +11 -3
  377. package/presets/zcode/mcp-ts/hooks/README.md +2 -1
  378. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +57 -3
  379. package/presets/zcode/mcp-ts/team/README.md +5 -0
  380. package/presets/zcode/mol/adapter-map.json +11 -3
  381. package/presets/zcode/mol/hooks/README.md +2 -1
  382. package/presets/zcode/mol/hooks/chain-team-phases.sh +57 -3
  383. package/presets/zcode/mol/team/README.md +5 -0
  384. package/presets/zcode/next/adapter-map.json +67 -3
  385. package/presets/zcode/next/agents/build-verifier.md +2 -0
  386. package/presets/zcode/next/agents/code-reviewer.md +2 -0
  387. package/presets/zcode/next/agents/feature-developer.md +1 -0
  388. package/presets/zcode/next/agents/task-analyst.md +4 -0
  389. package/presets/zcode/next/agents/task-router.md +5 -3
  390. package/presets/zcode/next/commands/README.md +1 -0
  391. package/presets/zcode/next/commands/task-continue.md +1 -1
  392. package/presets/zcode/next/commands/upstream-research.md +26 -0
  393. package/presets/zcode/next/hooks/README.md +2 -1
  394. package/presets/zcode/next/hooks/chain-team-phases.sh +57 -3
  395. package/presets/zcode/next/team/README.md +23 -0
  396. package/presets/zcode/next/team/upstream/config.json +31 -0
  397. package/presets/zcode/next/team/upstream/digest-template.md +55 -0
  398. package/presets/zcode/next/team/upstream/opencode.json +34 -0
  399. package/presets/zcode/next/team/upstream/projects.json +4 -0
  400. package/presets/zcode/next/team/upstream/prompt.md +77 -0
  401. package/presets/zcode/next/team/upstream/signatures.json +9 -0
  402. package/presets/zcode/nuxt/adapter-map.json +11 -3
  403. package/presets/zcode/nuxt/hooks/README.md +2 -1
  404. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +57 -3
  405. package/presets/zcode/nuxt/team/README.md +5 -0
  406. package/presets/zcode/php-hexagonal/adapter-map.json +11 -3
  407. package/presets/zcode/php-hexagonal/hooks/README.md +2 -1
  408. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +57 -3
  409. package/presets/zcode/php-hexagonal/team/README.md +5 -0
  410. package/presets/zcode/php-laravel/adapter-map.json +11 -3
  411. package/presets/zcode/php-laravel/hooks/README.md +2 -1
  412. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +57 -3
  413. package/presets/zcode/php-laravel/team/README.md +5 -0
  414. package/presets/zcode/svelte/adapter-map.json +11 -3
  415. package/presets/zcode/svelte/hooks/README.md +2 -1
  416. package/presets/zcode/svelte/hooks/chain-team-phases.sh +57 -3
  417. package/presets/zcode/svelte/team/README.md +5 -0
  418. package/presets/claude/android-kotlin/hooks/guard-shell-command.sh +0 -103
  419. package/presets/claude/go/hooks/guard-shell-command.sh +0 -102
  420. package/presets/claude/mcp-ts/hooks/guard-shell-command.sh +0 -102
  421. package/presets/claude/php-hexagonal/hooks/guard-shell-command.sh +0 -103
  422. package/presets/claude/php-laravel/hooks/guard-shell-command.sh +0 -103
  423. package/presets/cursor/android-kotlin/hooks/guard-shell-command.sh +0 -80
  424. package/presets/cursor/go/hooks/guard-shell-command.sh +0 -79
  425. package/presets/cursor/ios-swift/hooks/guard-shell-command.sh +0 -79
  426. package/presets/cursor/java/hooks/guard-shell-command.sh +0 -80
  427. package/presets/cursor/mcp-ts/hooks/guard-shell-command.sh +0 -79
  428. package/presets/cursor/mol/hooks/guard-shell-command.sh +0 -77
  429. package/presets/cursor/next/hooks/guard-shell-command.sh +0 -77
  430. package/presets/cursor/nuxt/hooks/guard-shell-command.sh +0 -77
  431. package/presets/cursor/php-hexagonal/hooks/guard-shell-command.sh +0 -80
  432. package/presets/cursor/php-laravel/hooks/guard-shell-command.sh +0 -80
  433. package/presets/cursor/svelte/hooks/guard-shell-command.sh +0 -77
@@ -0,0 +1,2360 @@
1
+ /**
2
+ * Scheduled jobs for the `.ai.local/team` projection: the job model, a
3
+ * dependency-free cron/interval parser, the file-authoritative store, the
4
+ * projection of jobs and runs, and the `schedule` runtime.
5
+ *
6
+ * Files stay authoritative (D-4): `scheduler/jobs.json` is committed and holds
7
+ * the definitions, `scheduler/runs/<job>/<run-id>/run.json` holds the run
8
+ * manifests, and `scheduler/state.json` holds ignored runtime state. The three
9
+ * tables are projections rebuilt from those files, so a fingerprint rebuild
10
+ * loses nothing an operator authored.
11
+ *
12
+ * The module performs no I/O at import time, so `serve` may import the pure
13
+ * cron and validation helpers without opening a connection or a file.
14
+ *
15
+ * Exit codes used by the CLI verbs: 0 ok, 1 refused (`E_VALIDATION`,
16
+ * `E_CONFLICT`, `E_NOT_FOUND`, `E_JOBS_PARSE`, `E_DISABLED`), 2 database-level,
17
+ * 3 usage, 4 a live lease (`E_BUSY`, `E_SCHEDULER_RUNNING`).
18
+ */
19
+
20
+ import crypto from 'node:crypto';
21
+ import fs from 'node:fs';
22
+ import os from 'node:os';
23
+ import path from 'node:path';
24
+ import { spawn } from 'node:child_process';
25
+ import { Writable } from 'node:stream';
26
+
27
+ import {
28
+ DEFAULT_TEAM_ROOT,
29
+ INDEX_UNAVAILABLE_LINE,
30
+ TeamDbError,
31
+ integrityCheck,
32
+ isKillSwitchSet,
33
+ isSqliteAvailable,
34
+ openTeamDb,
35
+ teamDbFail,
36
+ } from './team-db-schema.mjs';
37
+
38
+ /* --------------------------------- constants ------------------------------- */
39
+
40
+ export const SCHEDULER_DIR = 'scheduler';
41
+ export const JOBS_FILE = 'jobs.json';
42
+ export const STATE_FILE = 'state.json';
43
+ export const LOCK_FILE = 'scheduler.lock';
44
+ export const RUNS_DIR = 'runs';
45
+ export const PROMPTS_DIR = 'prompts';
46
+ export const RUN_MANIFEST_FILE = 'run.json';
47
+ export const STDOUT_FILE = 'stdout.log';
48
+ export const STDERR_FILE = 'stderr.log';
49
+ export const PROMPT_FILE = 'prompt.md';
50
+
51
+ export const JOB_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
52
+ export const RUN_ID_RE = /^[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}$/;
53
+ export const ENV_NAME_RE = /^[A-Z_][A-Z0-9_]{0,63}$/;
54
+
55
+ export const SCHEDULE_KINDS = ['cron', 'interval'];
56
+ export const PAYLOAD_KINDS = ['command', 'pipeline'];
57
+ export const CONCURRENCY_POLICIES = ['skip', 'queue', 'allow'];
58
+ export const MISFIRE_POLICIES = ['skip', 'run-once', 'catch-up'];
59
+ export const RUN_STATES = [
60
+ 'claimed',
61
+ 'running',
62
+ 'succeeded',
63
+ 'failed',
64
+ 'timeout',
65
+ 'skipped',
66
+ 'interrupted',
67
+ ];
68
+ export const ACTIVE_RUN_STATES = ['claimed', 'running'];
69
+ export const TERMINAL_RUN_STATES = RUN_STATES.filter((state) => !ACTIVE_RUN_STATES.includes(state));
70
+ export const TRIGGERS = ['schedule', 'manual', 'catch-up'];
71
+
72
+ export const MAX_JOBS = 100;
73
+ export const MAX_JOB_ID_LENGTH = 64;
74
+ export const MAX_TITLE_LENGTH = 120;
75
+ export const MAX_ARGV_ELEMENTS = 32;
76
+ export const MAX_ARGV_ELEMENT_LENGTH = 4096;
77
+ export const MAX_ARGV_BYTES = 16 * 1024;
78
+ export const MAX_ENV_NAMES = 24;
79
+ export const MAX_PROMPT_BYTES = 64 * 1024;
80
+ export const MIN_TIMEOUT_MS = 1000;
81
+ export const MAX_TIMEOUT_MS = 12 * 60 * 60 * 1000;
82
+ export const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000;
83
+ export const MIN_INTERVAL_SECONDS = 60;
84
+ export const MAX_INTERVAL_SECONDS = 30 * 24 * 60 * 60;
85
+ export const MAX_CATCH_UP = 5;
86
+
87
+ export const MAX_RUN_LOG_BYTES = 1024 * 1024;
88
+ export const JOB_RUN_RETENTION = 200;
89
+ export const JOB_RUN_RETENTION_DAYS = 30;
90
+ export const MAX_RUN_STORE_BYTES = 2 * 1024 * 1024 * 1024;
91
+ export const TRUNCATION_MARKER = (cap) => `[ai-rules team-db: output truncated at ${cap} bytes]`;
92
+
93
+ export const DEFAULT_LOG_LIMIT = 65536;
94
+ export const MAX_LOG_LIMIT = 262144;
95
+ export const MIN_LOG_LIMIT = 1;
96
+ export const LOG_STREAMS = ['stdout', 'stderr'];
97
+
98
+ export const LEASE_STALE_MS = 90 * 1000;
99
+ /** The lease is read with this bound; a larger file is corrupt, never a lease. */
100
+ export const LEASE_MAX_BYTES = 4096;
101
+ export const DEFAULT_TICK_MS = 1000;
102
+ export const DEFAULT_GRACE_MS = 5000;
103
+ export const DEFAULT_DRAIN_MS = 30 * 1000;
104
+
105
+ /** The six names a job child never inherits: a child must not see a switch. */
106
+ export const BLOCKED_ENV_PREFIX = 'AI_RULES_TEAM_DB_';
107
+ export const BASE_ENV_NAMES = ['PATH', 'HOME', 'TMPDIR', 'LANG', 'TZ'];
108
+
109
+ /** Windows children lose SystemRoot/ComSpec/PATHEXT and the temp/profile dirs without these. */
110
+ export function windowsBaseEnvNames() {
111
+ return [
112
+ ...BASE_ENV_NAMES,
113
+ 'SystemRoot',
114
+ 'SystemDrive',
115
+ 'windir',
116
+ 'ComSpec',
117
+ 'PATHEXT',
118
+ 'USERPROFILE',
119
+ 'APPDATA',
120
+ 'LOCALAPPDATA',
121
+ 'TEMP',
122
+ 'TMP',
123
+ ];
124
+ }
125
+
126
+ export const JOBS_FILE_VERSION = 1;
127
+ export const RUN_MANIFEST_VERSION = 1;
128
+ export const STATE_FILE_VERSION = 1;
129
+ export const LEASE_VERSION = 1;
130
+
131
+ /**
132
+ * A missing cwd or template is a runtime reason, never a crash. `E_TIMEOUT`
133
+ * is fixed; a lost child contributes the parameterised families
134
+ * `E_EXIT_<code>` and `E_SIGNAL_<signal>`, which no flat list can enumerate.
135
+ */
136
+ export const REASON_CODES = [
137
+ 'E_CWD_MISSING',
138
+ 'E_PROMPT_MISSING',
139
+ 'E_PROMPT_TOO_LARGE',
140
+ 'E_CONCURRENCY_SKIP',
141
+ 'E_ORPHANED',
142
+ 'E_TIMEOUT',
143
+ 'E_SPAWN_FAILED',
144
+ ];
145
+
146
+ /* --------------------------------- helpers --------------------------------- */
147
+
148
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
149
+ const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
150
+
151
+ /**
152
+ * Canonical JSON local to the scheduler: sorted keys at every depth, arrays
153
+ * preserved. Re-projecting equal input is byte-identical even when the source
154
+ * key order differs.
155
+ */
156
+ export function canonicalJson(value) {
157
+ const walk = (node) => {
158
+ if (node === null || typeof node !== 'object') {
159
+ if (typeof node === 'number' && !Number.isFinite(node)) {
160
+ throw new Error('canonical JSON cannot represent a non-finite number');
161
+ }
162
+ return node;
163
+ }
164
+ if (Array.isArray(node)) return node.map(walk);
165
+ const sorted = {};
166
+ for (const key of Object.keys(node).sort()) {
167
+ if (node[key] === undefined) continue;
168
+ sorted[key] = walk(node[key]);
169
+ }
170
+ return sorted;
171
+ };
172
+ const serialized = JSON.stringify(walk(value));
173
+ return serialized === undefined ? 'null' : serialized;
174
+ }
175
+
176
+ export const resolveTeamRoot = (teamRoot) =>
177
+ path.resolve(teamRoot || process.env.AI_RULES_TEAM_DB_ROOT || DEFAULT_TEAM_ROOT);
178
+
179
+ /** Every path the scheduler owns under one team root. */
180
+ export function schedulerPaths(teamRoot) {
181
+ const root = path.join(resolveTeamRoot(teamRoot), SCHEDULER_DIR);
182
+ return {
183
+ root,
184
+ jobs: path.join(root, JOBS_FILE),
185
+ state: path.join(root, STATE_FILE),
186
+ lock: path.join(root, LOCK_FILE),
187
+ runs: path.join(root, RUNS_DIR),
188
+ prompts: path.join(root, PROMPTS_DIR),
189
+ runDir: (jobId, runId) => path.join(root, RUNS_DIR, jobId, runId),
190
+ };
191
+ }
192
+
193
+ const writeAtomic = (filePath, content) => {
194
+ fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
195
+ const temporary = `${filePath}.tmp`;
196
+ fs.writeFileSync(temporary, content, { encoding: 'utf8', mode: 0o600 });
197
+ fs.renameSync(temporary, filePath);
198
+ };
199
+
200
+ const writeAtomicIfChanged = (filePath, content) => {
201
+ try {
202
+ if (fs.readFileSync(filePath, 'utf8') === content) return false;
203
+ } catch {
204
+ /* absent or unreadable: write it */
205
+ }
206
+ writeAtomic(filePath, content);
207
+ return true;
208
+ };
209
+
210
+ /* ------------------------------- time zones -------------------------------- */
211
+
212
+ const formatterCache = new Map();
213
+
214
+ const zonedFormatter = (timeZone) => {
215
+ const cached = formatterCache.get(timeZone);
216
+ if (cached) return cached;
217
+ const formatter = new Intl.DateTimeFormat('en-US', {
218
+ timeZone,
219
+ hourCycle: 'h23',
220
+ year: 'numeric',
221
+ month: '2-digit',
222
+ day: '2-digit',
223
+ hour: '2-digit',
224
+ minute: '2-digit',
225
+ second: '2-digit',
226
+ });
227
+ formatterCache.set(timeZone, formatter);
228
+ return formatter;
229
+ };
230
+
231
+ /** True when the zone constructs; the only portability check the design asks. */
232
+ export function isValidTimeZone(timeZone) {
233
+ if (typeof timeZone !== 'string' || timeZone.length < 1 || timeZone.length > 64) return false;
234
+ try {
235
+ zonedFormatter(timeZone);
236
+ return true;
237
+ } catch {
238
+ return false;
239
+ }
240
+ }
241
+
242
+ const defaultTimeZone = () => {
243
+ try {
244
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
245
+ } catch {
246
+ return 'UTC';
247
+ }
248
+ };
249
+
250
+ /** Wall-clock fields of one instant in one zone. */
251
+ export function localFields(timeZone, instantMs) {
252
+ const parts = zonedFormatter(timeZone).formatToParts(new Date(instantMs));
253
+ const read = (type) => Number(parts.find((part) => part.type === type)?.value);
254
+ const hour = read('hour');
255
+ return {
256
+ year: read('year'),
257
+ month: read('month'),
258
+ day: read('day'),
259
+ hour: hour === 24 ? 0 : hour,
260
+ minute: read('minute'),
261
+ second: read('second'),
262
+ };
263
+ }
264
+
265
+ const wallMsOf = (fields) =>
266
+ Date.UTC(fields.year, fields.month - 1, fields.day, fields.hour, fields.minute, fields.second || 0);
267
+
268
+ const fieldsOfWallMs = (wallMs) => {
269
+ const date = new Date(wallMs);
270
+ return {
271
+ year: date.getUTCFullYear(),
272
+ month: date.getUTCMonth() + 1,
273
+ day: date.getUTCDate(),
274
+ hour: date.getUTCHours(),
275
+ minute: date.getUTCMinutes(),
276
+ second: date.getUTCSeconds(),
277
+ };
278
+ };
279
+
280
+ /** offset = local wall clock − UTC instant, in milliseconds. */
281
+ const zoneOffsetMs = (timeZone, instantMs) => {
282
+ const flooredSecond = Math.floor(instantMs / 1000) * 1000;
283
+ return wallMsOf(localFields(timeZone, flooredSecond)) - flooredSecond;
284
+ };
285
+
286
+ /**
287
+ * Every UTC instant whose local wall clock reads exactly `fields`, earliest
288
+ * first. Empty inside a spring-forward gap; two entries inside a fall-back
289
+ * overlap. Sampling the offsets one day either side is enough for a single
290
+ * transition, which is the only shape a civil zone has.
291
+ */
292
+ export function instantsForLocal(timeZone, fields) {
293
+ const wallMs = wallMsOf(fields);
294
+ const offsets = new Set([
295
+ zoneOffsetMs(timeZone, wallMs - 86400000),
296
+ zoneOffsetMs(timeZone, wallMs + 86400000),
297
+ zoneOffsetMs(timeZone, wallMs),
298
+ ]);
299
+ const matches = [];
300
+ for (const offset of offsets) {
301
+ const candidate = wallMs - offset;
302
+ const local = localFields(timeZone, candidate);
303
+ if (
304
+ local.year === fields.year &&
305
+ local.month === fields.month &&
306
+ local.day === fields.day &&
307
+ local.hour === fields.hour &&
308
+ local.minute === fields.minute
309
+ ) {
310
+ matches.push(candidate);
311
+ }
312
+ }
313
+ return [...new Set(matches)].sort((left, right) => left - right);
314
+ }
315
+
316
+ /* ------------------------------- cron parser ------------------------------- */
317
+
318
+ const CRON_FIELDS = [
319
+ { key: 'minute', min: 0, max: 59 },
320
+ { key: 'hour', min: 0, max: 23 },
321
+ { key: 'dom', min: 1, max: 31 },
322
+ { key: 'month', min: 1, max: 12 },
323
+ { key: 'dow', min: 0, max: 7 },
324
+ ];
325
+
326
+ const invalidCron = (detail) => failField('schedule.expression', detail);
327
+
328
+ const parseCronField = (raw, spec) => {
329
+ const values = new Set();
330
+ for (const token of raw.split(',')) {
331
+ if (token === '') invalidCron(`empty list element in "${raw}"`);
332
+ const [rangePart, stepPart, ...rest] = token.split('/');
333
+ if (rest.length > 0) invalidCron(`too many "/" in "${token}"`);
334
+ let step = 1;
335
+ if (stepPart !== undefined) {
336
+ if (!/^\d+$/.test(stepPart)) invalidCron(`step "${stepPart}" is not a number`);
337
+ step = Number(stepPart);
338
+ if (step < 1) invalidCron(`step of "${token}" must be at least 1`);
339
+ }
340
+ let start;
341
+ let end;
342
+ if (rangePart === '*') {
343
+ start = spec.min;
344
+ end = spec.max;
345
+ } else if (/^\d+$/.test(rangePart)) {
346
+ start = Number(rangePart);
347
+ end = stepPart === undefined ? start : spec.max;
348
+ } else if (/^\d+-\d+$/.test(rangePart)) {
349
+ const [from, to] = rangePart.split('-').map(Number);
350
+ start = from;
351
+ end = to;
352
+ } else {
353
+ invalidCron(`"${rangePart}" is not *, a number, a range or a step in "${token}"`);
354
+ }
355
+ if (start < spec.min || end > spec.max || start > end) {
356
+ invalidCron(`"${token}" is outside ${spec.min}-${spec.max}`);
357
+ }
358
+ for (let value = start; value <= end; value += step) values.add(value);
359
+ }
360
+ return values;
361
+ };
362
+
363
+ /**
364
+ * Parse a five-field expression. Macros such as `@daily` are refused: they are
365
+ * a second grammar with no extra expressive power, and silently expanding one
366
+ * would hide a typo.
367
+ */
368
+ export function parseCronExpression(expression) {
369
+ if (typeof expression !== 'string') invalidCron('must be a string');
370
+ const trimmed = expression.trim();
371
+ if (/^@/.test(trimmed)) invalidCron('macros such as "@daily" are not accepted; use five fields');
372
+ if (trimmed.length < 9 || trimmed.length > 120) invalidCron('must be 9-120 characters');
373
+ const fields = trimmed.split(/\s+/);
374
+ if (fields.length !== 5) invalidCron(`must have five fields, got ${fields.length}`);
375
+ const parsed = {};
376
+ CRON_FIELDS.forEach((spec, index) => {
377
+ parsed[spec.key] = parseCronField(fields[index], spec);
378
+ });
379
+ // `dow` accepts 0-7 with 0 and 7 both Sunday.
380
+ if (parsed.dow.has(7)) {
381
+ parsed.dow.delete(7);
382
+ parsed.dow.add(0);
383
+ }
384
+ parsed.domRestricted = fields[2] !== '*';
385
+ parsed.dowRestricted = fields[4] !== '*';
386
+ parsed.expression = trimmed;
387
+ return parsed;
388
+ }
389
+
390
+ const cronDayMatches = (parsed, fields) => {
391
+ const domOk = parsed.dom.has(fields.day);
392
+ const dowOk = parsed.dow.has(new Date(wallMsOf({ ...fields, second: 0 })).getUTCDay());
393
+ if (parsed.domRestricted && parsed.dowRestricted) return domOk || dowOk;
394
+ if (parsed.domRestricted) return domOk;
395
+ if (parsed.dowRestricted) return dowOk;
396
+ return true;
397
+ };
398
+
399
+ const MAX_CRON_SEARCH_DAYS = 366 * 8;
400
+
401
+ /**
402
+ * The first instant strictly after `fromMs` whose local wall clock matches.
403
+ * Iteration happens in **local** minutes, so a nonexistent local minute is
404
+ * skipped and a repeated one fires once, at its first UTC occurrence.
405
+ */
406
+ export function nextCronInstant(parsed, timeZone, fromMs) {
407
+ const startInstant = (Math.floor(fromMs / 60000) + 1) * 60000;
408
+ const startLocal = localFields(timeZone, startInstant);
409
+ let wallMs = wallMsOf(startLocal);
410
+ const limit = startInstant + MAX_CRON_SEARCH_DAYS * 86400000;
411
+ while (wallMs < limit) {
412
+ const fields = fieldsOfWallMs(wallMs);
413
+ if (!parsed.month.has(fields.month)) {
414
+ wallMs = Date.UTC(fields.year, fields.month - 1, fields.day, 0, 0, 0) + 86400000;
415
+ continue;
416
+ }
417
+ if (!cronDayMatches(parsed, fields)) {
418
+ wallMs = Date.UTC(fields.year, fields.month - 1, fields.day, 0, 0, 0) + 86400000;
419
+ continue;
420
+ }
421
+ if (!parsed.hour.has(fields.hour)) {
422
+ wallMs = Date.UTC(fields.year, fields.month - 1, fields.day, fields.hour, 0, 0) + 3600000;
423
+ continue;
424
+ }
425
+ if (!parsed.minute.has(fields.minute)) {
426
+ wallMs += 60000;
427
+ continue;
428
+ }
429
+ const instants = instantsForLocal(timeZone, fields);
430
+ const chosen = instants.find((instant) => instant > fromMs);
431
+ if (chosen !== undefined) return chosen;
432
+ wallMs += 60000;
433
+ }
434
+ return null;
435
+ }
436
+
437
+ /* ------------------------------ next-fire math ----------------------------- */
438
+
439
+ const lastFireOf = (state, jobId) => {
440
+ const raw = state?.lastFireAt?.[jobId];
441
+ if (typeof raw !== 'string') return null;
442
+ const parsed = Date.parse(raw);
443
+ return Number.isNaN(parsed) ? null : parsed;
444
+ };
445
+
446
+ /**
447
+ * The first scheduled instant strictly after `now`.
448
+ *
449
+ * `cron` is pure in the definition and `now`. `interval` anchors on the last
450
+ * fire recorded in `state.json` when it exists, so a paused-then-resumed or an
451
+ * overdue interval lists the same instant the scheduler would claim next.
452
+ */
453
+ export function nextFireAt(job, options = {}) {
454
+ const now = options.now === undefined ? Date.now() : Number(options.now);
455
+ const { schedule } = job;
456
+ if (schedule.kind === 'cron') {
457
+ const instant = nextCronInstant(parseCronExpression(schedule.expression), schedule.timezone, now);
458
+ return instant === null ? null : new Date(instant).toISOString();
459
+ }
460
+ const every = schedule.everySeconds * 1000;
461
+ const last = options.lastFireAt === undefined ? null : options.lastFireAt;
462
+ if (last === null) return new Date(now + every).toISOString();
463
+ const missed = Math.floor((now - last) / every) + 1;
464
+ return new Date(last + Math.max(missed, 1) * every).toISOString();
465
+ }
466
+
467
+ /** The next `count` fire instants, for `jobs get`. */
468
+ export function nextFireInstants(job, options = {}) {
469
+ const count = Math.max(1, Math.min(Number(options.count ?? 3), 10));
470
+ const now = options.now === undefined ? Date.now() : Number(options.now);
471
+ const instants = [];
472
+ let cursor = now;
473
+ for (let index = 0; index < count; index += 1) {
474
+ const next = nextFireAt(job, { now: cursor, lastFireAt: index === 0 ? options.lastFireAt ?? null : null });
475
+ if (next === null) break;
476
+ instants.push(next);
477
+ cursor = Date.parse(next);
478
+ }
479
+ return instants;
480
+ }
481
+
482
+ /* -------------------------------- validation ------------------------------- */
483
+
484
+ const failField = (parameter, detail) => {
485
+ const error = new TeamDbError('E_VALIDATION', `parameter "${parameter}": ${detail}`, 3);
486
+ // The API maps `details.parameter` straight from this field, so a client
487
+ // learns which field it got wrong without parsing prose.
488
+ error.parameter = parameter;
489
+ throw error;
490
+ };
491
+
492
+ const DECLARED_JOB_KEYS = [
493
+ 'id',
494
+ 'title',
495
+ 'enabled',
496
+ 'schedule',
497
+ 'payload',
498
+ 'cwd',
499
+ 'envPassthrough',
500
+ 'timeoutMs',
501
+ 'concurrency',
502
+ 'misfire',
503
+ 'createdAt',
504
+ 'updatedAt',
505
+ 'revision',
506
+ ];
507
+
508
+ const assertKnownKeys = (record, allowed, prefix) => {
509
+ for (const key of Object.keys(record)) {
510
+ if (!allowed.includes(key)) failField(`${prefix}${key}`, 'unknown key');
511
+ }
512
+ };
513
+
514
+ const validateArgv = (argv, parameter) => {
515
+ if (!Array.isArray(argv)) failField(parameter, 'must be an array of strings');
516
+ if (argv.length < 1 || argv.length > MAX_ARGV_ELEMENTS) {
517
+ failField(parameter, `must have 1-${MAX_ARGV_ELEMENTS} elements`);
518
+ }
519
+ let total = 0;
520
+ for (const element of argv) {
521
+ if (typeof element !== 'string') failField(parameter, 'every element must be a string');
522
+ if (element.length < 1 || element.length > MAX_ARGV_ELEMENT_LENGTH) {
523
+ failField(parameter, `every element must be 1-${MAX_ARGV_ELEMENT_LENGTH} characters`);
524
+ }
525
+ // A tab is legal in a line-oriented argv editor; every other C0/C1 control
526
+ // character is refused, so a newline or an escape sequence can never reach
527
+ // `jobs.json`, a run manifest, or a terminal that tails them.
528
+ if (/[\u0000-\u0008\u000a-\u001f\u007f-\u009f]/u.test(element)) {
529
+ failField(parameter, 'an element contains a control character (tab is allowed)');
530
+ }
531
+ total += Buffer.byteLength(element, 'utf8');
532
+ }
533
+ if (total > MAX_ARGV_BYTES) failField(parameter, `elements total ${total} bytes, above ${MAX_ARGV_BYTES}`);
534
+ return [...argv];
535
+ };
536
+
537
+ const validateEnvPassthrough = (names) => {
538
+ if (!Array.isArray(names)) failField('envPassthrough', 'must be an array of names');
539
+ if (names.length > MAX_ENV_NAMES) failField('envPassthrough', `at most ${MAX_ENV_NAMES} names`);
540
+ const seen = new Set();
541
+ for (const name of names) {
542
+ if (typeof name !== 'string' || !ENV_NAME_RE.test(name)) {
543
+ failField('envPassthrough', `"${String(name)}" is not an environment variable name`);
544
+ }
545
+ if (seen.has(name)) failField('envPassthrough', `"${name}" is listed twice`);
546
+ seen.add(name);
547
+ }
548
+ return [...names];
549
+ };
550
+
551
+ const validateTimeout = (value) => {
552
+ if (value === undefined) return DEFAULT_TIMEOUT_MS;
553
+ if (!Number.isInteger(value) || value < MIN_TIMEOUT_MS || value > MAX_TIMEOUT_MS) {
554
+ failField('timeoutMs', `must be an integer between ${MIN_TIMEOUT_MS} and ${MAX_TIMEOUT_MS}`);
555
+ }
556
+ return value;
557
+ };
558
+
559
+ const requireEnum = (value, allowed, parameter, fallback) => {
560
+ const chosen = value === undefined ? fallback : value;
561
+ if (!allowed.includes(chosen)) failField(parameter, `must be one of ${allowed.join(', ')}`);
562
+ return chosen;
563
+ };
564
+
565
+ const realRootOf = (teamRoot) => {
566
+ try {
567
+ return fs.realpathSync(teamRoot);
568
+ } catch {
569
+ return path.resolve(teamRoot);
570
+ }
571
+ };
572
+
573
+ /**
574
+ * A team-root-relative path, refused when it resolves outside the root. The
575
+ * comparison runs on real paths because a temp root commonly sits behind a
576
+ * symlink (`/var` -> `/private/var` on macOS).
577
+ */
578
+ const resolveUnderRoot = (value, teamRoot, parameter) => {
579
+ if (typeof value !== 'string' || value.trim() === '') failField(parameter, 'must be a non-empty string');
580
+ const root = realRootOf(teamRoot);
581
+ const resolved = path.isAbsolute(value) ? path.resolve(value) : path.resolve(root, value);
582
+ let real = resolved;
583
+ try {
584
+ real = fs.realpathSync(resolved);
585
+ } catch {
586
+ /* a path that does not exist yet is compared lexically */
587
+ }
588
+ if (real !== root && !real.startsWith(root + path.sep)) {
589
+ failField(parameter, 'must resolve under the team root');
590
+ }
591
+ return { value, resolved };
592
+ };
593
+
594
+ const ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
595
+
596
+ const validateIso = (value, parameter) => {
597
+ if (typeof value !== 'string' || !ISO_RE.test(value) || Number.isNaN(Date.parse(value))) {
598
+ failField(parameter, 'must be an ISO 8601 UTC timestamp');
599
+ }
600
+ return value;
601
+ };
602
+
603
+ /**
604
+ * Validate one job and return it normalized into the declared key order.
605
+ *
606
+ * Strict by design: an unknown key, a wrong bound or a duplicate is a refusal
607
+ * with the parameter name, and the caller writes nothing.
608
+ */
609
+ export function validateJob(input, options = {}) {
610
+ const teamRoot = resolveTeamRoot(options.teamRoot);
611
+ if (!isRecord(input)) failField('job', 'must be an object');
612
+ assertKnownKeys(input, DECLARED_JOB_KEYS, '');
613
+
614
+ const id = input.id;
615
+ if (typeof id !== 'string' || !JOB_ID_RE.test(id) || id.length > MAX_JOB_ID_LENGTH) {
616
+ failField('id', `must match ${JOB_ID_RE.source} and be at most ${MAX_JOB_ID_LENGTH} characters`);
617
+ }
618
+ const title = input.title === undefined ? id : input.title;
619
+ if (typeof title !== 'string' || title.length < 1 || title.length > MAX_TITLE_LENGTH) {
620
+ failField('title', `must be 1-${MAX_TITLE_LENGTH} characters`);
621
+ }
622
+ if (/[\u0000-\u001f\u007f]/.test(title)) failField('title', 'must not contain control characters');
623
+ const enabled = input.enabled === undefined ? true : input.enabled;
624
+ if (typeof enabled !== 'boolean') failField('enabled', 'must be a boolean');
625
+
626
+ const schedule = input.schedule === undefined ? { kind: 'cron' } : input.schedule;
627
+ if (!isRecord(schedule)) failField('schedule', 'must be an object');
628
+ const scheduleKind = requireEnum(schedule.kind, SCHEDULE_KINDS, 'schedule.kind', 'cron');
629
+ const timezoneRaw = schedule.timezone === undefined ? defaultTimeZone() : schedule.timezone;
630
+ if (!isValidTimeZone(timezoneRaw)) {
631
+ // The value is deliberately not echoed: a body field may hold anything.
632
+ failField('schedule.timezone', 'is not an IANA zone this runtime knows');
633
+ }
634
+ let expression;
635
+ let everySeconds;
636
+ if (scheduleKind === 'cron') {
637
+ assertKnownKeys(schedule, ['kind', 'expression', 'timezone'], 'schedule.');
638
+ if (schedule.expression === undefined) failField('schedule.expression', 'is required for kind "cron"');
639
+ parseCronExpression(schedule.expression);
640
+ expression = String(schedule.expression).trim();
641
+ } else {
642
+ assertKnownKeys(schedule, ['kind', 'everySeconds', 'timezone'], 'schedule.');
643
+ const value = schedule.everySeconds;
644
+ if (!Number.isInteger(value) || value < MIN_INTERVAL_SECONDS || value > MAX_INTERVAL_SECONDS) {
645
+ failField('schedule.everySeconds', `must be an integer between ${MIN_INTERVAL_SECONDS} and ${MAX_INTERVAL_SECONDS}`);
646
+ }
647
+ everySeconds = value;
648
+ }
649
+
650
+ const payload = input.payload === undefined ? {} : input.payload;
651
+ if (!isRecord(payload)) failField('payload', 'must be an object');
652
+ const payloadKind = requireEnum(payload.kind, PAYLOAD_KINDS, 'payload.kind', 'command');
653
+ let argv = null;
654
+ let promptTemplate = null;
655
+ let runner = null;
656
+ if (payloadKind === 'command') {
657
+ assertKnownKeys(payload, ['kind', 'argv'], 'payload.');
658
+ if (payload.argv === undefined) failField('payload.argv', 'is required for kind "command"');
659
+ argv = validateArgv(payload.argv, 'payload.argv');
660
+ } else {
661
+ assertKnownKeys(payload, ['kind', 'promptTemplate', 'runner'], 'payload.');
662
+ if (payload.promptTemplate === undefined) {
663
+ failField('payload.promptTemplate', 'is required for kind "pipeline"');
664
+ }
665
+ const resolved = resolveUnderRoot(payload.promptTemplate, teamRoot, 'payload.promptTemplate');
666
+ if (fs.existsSync(resolved.resolved) && fs.statSync(resolved.resolved).size > MAX_PROMPT_BYTES) {
667
+ failField('payload.promptTemplate', `must be at most ${MAX_PROMPT_BYTES} bytes`);
668
+ }
669
+ promptTemplate = resolved.value;
670
+ if (payload.runner === undefined) {
671
+ failField('payload.runner', 'no runner configured: kind "pipeline" needs payload.runner');
672
+ }
673
+ runner = validateArgv(payload.runner, 'payload.runner');
674
+ const placeholders = runner.filter((element) => element.includes('{promptFile}')).length;
675
+ if (placeholders !== 1) {
676
+ failField('payload.runner', 'exactly one element must contain {promptFile}');
677
+ }
678
+ }
679
+
680
+ const cwdRaw = input.cwd === undefined ? '.' : input.cwd;
681
+ const cwd = resolveUnderRoot(cwdRaw, teamRoot, 'cwd');
682
+
683
+ const timeoutMs = validateTimeout(input.timeoutMs);
684
+ const concurrency = requireEnum(input.concurrency, CONCURRENCY_POLICIES, 'concurrency', 'skip');
685
+ const misfire = requireEnum(input.misfire, MISFIRE_POLICIES, 'misfire', 'run-once');
686
+ const nowIso = new Date().toISOString();
687
+ const createdAt = input.createdAt === undefined ? nowIso : validateIso(input.createdAt, 'createdAt');
688
+ const updatedAt = input.updatedAt === undefined ? createdAt : validateIso(input.updatedAt, 'updatedAt');
689
+ const revision = input.revision === undefined ? 1 : input.revision;
690
+ if (!Number.isInteger(revision) || revision < 1) failField('revision', 'must be an integer of at least 1');
691
+
692
+ const normalized = {
693
+ id,
694
+ title,
695
+ enabled,
696
+ schedule:
697
+ scheduleKind === 'cron'
698
+ ? { kind: 'cron', expression, timezone: timezoneRaw }
699
+ : { kind: 'interval', everySeconds, timezone: timezoneRaw },
700
+ payload:
701
+ payloadKind === 'command'
702
+ ? { kind: 'command', argv }
703
+ : { kind: 'pipeline', promptTemplate, runner },
704
+ cwd: cwd.value,
705
+ envPassthrough: validateEnvPassthrough(input.envPassthrough === undefined ? [] : input.envPassthrough),
706
+ timeoutMs,
707
+ concurrency,
708
+ misfire,
709
+ createdAt,
710
+ updatedAt,
711
+ revision,
712
+ };
713
+ return normalized;
714
+ }
715
+
716
+ /** The stored shape of a job: canonical JSON is the hash input. */
717
+ export const jobContentHash = (job) => sha256(canonicalJson(job));
718
+
719
+ /* ------------------------------ jobs.json file ----------------------------- */
720
+
721
+ const jobsFileFailure = (detail) => teamDbFail('E_JOBS_PARSE', `${detail}`, 1);
722
+
723
+ /**
724
+ * Read `scheduler/jobs.json`. Absent is an empty valid file. A malformed file
725
+ * is a named failure: the caller never writes over it.
726
+ */
727
+ export function readJobsFile(teamRoot) {
728
+ const paths = schedulerPaths(teamRoot);
729
+ let text;
730
+ try {
731
+ text = fs.readFileSync(paths.jobs, 'utf8');
732
+ } catch (error) {
733
+ if (error.code === 'ENOENT') return { version: JOBS_FILE_VERSION, jobs: [], present: false };
734
+ jobsFileFailure(`${paths.jobs}: ${error.message}`);
735
+ }
736
+ let parsed;
737
+ try {
738
+ parsed = JSON.parse(text);
739
+ } catch (error) {
740
+ jobsFileFailure(`${paths.jobs}: not valid JSON (${error.message})`);
741
+ }
742
+ if (!isRecord(parsed)) jobsFileFailure(`${paths.jobs}: top level must be an object`);
743
+ for (const key of Object.keys(parsed)) {
744
+ if (key !== 'version' && key !== 'jobs') jobsFileFailure(`${paths.jobs}: unknown top-level key "${key}"`);
745
+ }
746
+ if (parsed.version !== JOBS_FILE_VERSION) {
747
+ jobsFileFailure(`${paths.jobs}: version must be ${JOBS_FILE_VERSION}, got ${JSON.stringify(parsed.version)}`);
748
+ }
749
+ if (!Array.isArray(parsed.jobs)) jobsFileFailure(`${paths.jobs}: "jobs" must be an array`);
750
+ const seen = new Set();
751
+ const jobs = parsed.jobs.map((entry) => {
752
+ const job = validateJob(entry, { teamRoot });
753
+ if (seen.has(job.id)) jobsFileFailure(`${paths.jobs}: duplicate job id "${job.id}"`);
754
+ seen.add(job.id);
755
+ return job;
756
+ });
757
+ return { version: JOBS_FILE_VERSION, jobs, present: true };
758
+ }
759
+
760
+ /** Deterministic serialization: declared key order, sorted by id, one newline. */
761
+ export function serializeJobsFile(jobs) {
762
+ const ordered = [...jobs]
763
+ .sort((left, right) => (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))
764
+ .map((job) => {
765
+ const output = {};
766
+ for (const key of DECLARED_JOB_KEYS) output[key] = job[key];
767
+ return output;
768
+ });
769
+ return `${JSON.stringify({ version: JOBS_FILE_VERSION, jobs: ordered }, null, 2)}\n`;
770
+ }
771
+
772
+ /**
773
+ * Write `scheduler/jobs.json` atomically. An identical rewrite is a no-op, so a
774
+ * re-save never creates a diff.
775
+ */
776
+ export function writeJobsFile(teamRoot, jobs) {
777
+ const paths = schedulerPaths(teamRoot);
778
+ return writeAtomicIfChanged(paths.jobs, serializeJobsFile(jobs));
779
+ }
780
+
781
+ /* ------------------------------- state.json -------------------------------- */
782
+
783
+ const emptyState = () => ({ version: STATE_FILE_VERSION, lastFireAt: {}, requests: [] });
784
+
785
+ export function readStateFile(teamRoot) {
786
+ const paths = schedulerPaths(teamRoot);
787
+ try {
788
+ const parsed = JSON.parse(fs.readFileSync(paths.state, 'utf8'));
789
+ if (!isRecord(parsed)) return emptyState();
790
+ return {
791
+ version: STATE_FILE_VERSION,
792
+ lastFireAt: isRecord(parsed.lastFireAt) ? { ...parsed.lastFireAt } : {},
793
+ requests: Array.isArray(parsed.requests) ? parsed.requests.filter(isRecord) : [],
794
+ };
795
+ } catch {
796
+ // Losing `state.json` degrades misfire to `run-once`; it is never a reason
797
+ // to refuse a write or a claim.
798
+ return emptyState();
799
+ }
800
+ }
801
+
802
+ export function writeStateFile(teamRoot, state) {
803
+ const paths = schedulerPaths(teamRoot);
804
+ const value = {
805
+ version: STATE_FILE_VERSION,
806
+ lastFireAt: state.lastFireAt ?? {},
807
+ requests: state.requests ?? [],
808
+ };
809
+ writeAtomic(paths.state, `${JSON.stringify(value, null, 2)}\n`);
810
+ return value;
811
+ }
812
+
813
+ /* ---------------------------------- lease ---------------------------------- */
814
+
815
+ /**
816
+ * Read the lease without creating anything. A lease older than
817
+ * `LEASE_STALE_MS` is reported `stale`, never deleted: the next scheduler start
818
+ * overwrites it only after taking its own lock.
819
+ */
820
+ export function readLease(teamRoot, options = {}) {
821
+ const paths = schedulerPaths(teamRoot);
822
+ const now = options.now === undefined ? Date.now() : Number(options.now);
823
+ let raw;
824
+ try {
825
+ const stats = fs.statSync(paths.lock);
826
+ if (!stats.isFile()) return { state: 'stopped', lease: null };
827
+ const buffer = Buffer.alloc(Math.min(LEASE_MAX_BYTES, stats.size));
828
+ const fd = fs.openSync(paths.lock, 'r');
829
+ try {
830
+ const bytes = fs.readSync(fd, buffer, 0, buffer.length, 0);
831
+ raw = buffer.subarray(0, bytes).toString('utf8');
832
+ } finally {
833
+ fs.closeSync(fd);
834
+ }
835
+ } catch {
836
+ return { state: 'stopped', lease: null };
837
+ }
838
+ let lease;
839
+ try {
840
+ lease = JSON.parse(raw);
841
+ } catch {
842
+ return { state: 'stopped', lease: null };
843
+ }
844
+ if (!isRecord(lease)) return { state: 'stopped', lease: null };
845
+ const heartbeat = Date.parse(lease.heartbeatAt || lease.startedAt || '');
846
+ if (Number.isNaN(heartbeat)) return { state: 'stopped', lease: null };
847
+ const age = now - heartbeat;
848
+ return { state: age <= LEASE_STALE_MS ? 'running' : 'stale', lease, ageMs: age };
849
+ }
850
+
851
+ export const isLeaseFresh = (teamRoot, options) => readLease(teamRoot, options).state === 'running';
852
+
853
+ const writeLease = (teamRoot, lease) => {
854
+ const paths = schedulerPaths(teamRoot);
855
+ writeAtomic(paths.lock, `${JSON.stringify(lease, null, 2)}\n`);
856
+ };
857
+
858
+ const releaseLease = (teamRoot, pid) => {
859
+ const paths = schedulerPaths(teamRoot);
860
+ try {
861
+ const current = JSON.parse(fs.readFileSync(paths.lock, 'utf8'));
862
+ if (Number(current?.pid) !== Number(pid)) return;
863
+ fs.rmSync(paths.lock, { force: true });
864
+ } catch {
865
+ /* the lease is advisory: a missing or foreign file is not an error */
866
+ }
867
+ };
868
+
869
+ /* ------------------------------ run manifests ------------------------------ */
870
+
871
+ export const newRunId = () => {
872
+ const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z');
873
+ return `${stamp}-${crypto.randomBytes(4).toString('hex')}`;
874
+ };
875
+
876
+ export const runManifestPath = (teamRoot, jobId, runId) =>
877
+ path.join(schedulerPaths(teamRoot).runs, jobId, runId, RUN_MANIFEST_FILE);
878
+
879
+ export function writeRunManifest(teamRoot, jobId, runId, manifest) {
880
+ const file = runManifestPath(teamRoot, jobId, runId);
881
+ writeAtomic(file, `${JSON.stringify(manifest, null, 2)}\n`);
882
+ }
883
+
884
+ export function readRunManifest(teamRoot, jobId, runId) {
885
+ const file = runManifestPath(teamRoot, jobId, runId);
886
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
887
+ if (!isRecord(parsed)) throw new Error('run.json must be an object');
888
+ return parsed;
889
+ }
890
+
891
+ /**
892
+ * Every run directory of one job (or of every job), newest last. A directory
893
+ * without a readable manifest is reported, so the projection can count it.
894
+ */
895
+ export function listRunDirectories(teamRoot, jobId = null) {
896
+ const paths = schedulerPaths(teamRoot);
897
+ const jobIds = jobId ? [jobId] : safeReaddir(paths.runs);
898
+ const entries = [];
899
+ for (const currentJob of jobIds) {
900
+ for (const runId of safeReaddir(path.join(paths.runs, currentJob))) {
901
+ const dir = path.join(paths.runs, currentJob, runId);
902
+ let stats;
903
+ try {
904
+ stats = fs.statSync(dir);
905
+ } catch {
906
+ continue;
907
+ }
908
+ if (!stats.isDirectory()) continue;
909
+ const manifest = path.join(dir, RUN_MANIFEST_FILE);
910
+ let size = 0;
911
+ for (const file of [STDOUT_FILE, STDERR_FILE, PROMPT_FILE, RUN_MANIFEST_FILE]) {
912
+ try {
913
+ size += fs.statSync(path.join(dir, file)).size;
914
+ } catch {
915
+ /* a run without a log is a run with zero bytes */
916
+ }
917
+ }
918
+ entries.push({ jobId: currentJob, runId, dir, manifest, bytes: size, mtimeMs: stats.mtimeMs });
919
+ }
920
+ }
921
+ return entries.sort((left, right) => (left.runId < right.runId ? -1 : left.runId > right.runId ? 1 : 0));
922
+ }
923
+
924
+ function safeReaddir(dir) {
925
+ try {
926
+ return fs
927
+ .readdirSync(dir, { withFileTypes: true })
928
+ .filter((entry) => entry.isDirectory())
929
+ .map((entry) => entry.name)
930
+ .sort();
931
+ } catch {
932
+ return [];
933
+ }
934
+ }
935
+
936
+ /** A path resolved under `scheduler/runs`, or a named refusal. */
937
+ export function confineRunPath(teamRoot, relativePath) {
938
+ const paths = schedulerPaths(teamRoot);
939
+ const runsRoot = fs.existsSync(paths.runs) ? fs.realpathSync(paths.runs) : path.resolve(paths.runs);
940
+ const resolved = path.resolve(teamRoot, relativePath);
941
+ let real;
942
+ try {
943
+ real = fs.realpathSync(resolved);
944
+ } catch {
945
+ teamDbFail('E_INTERNAL', `${relativePath} does not exist`, 2);
946
+ }
947
+ if (!real.startsWith(runsRoot + path.sep)) {
948
+ teamDbFail('E_INTERNAL', `${relativePath} resolves outside the scheduler runs root`, 2);
949
+ }
950
+ return real;
951
+ }
952
+
953
+ /* -------------------------------- projection ------------------------------- */
954
+
955
+ const UPSERT_JOB_SQL = `
956
+ INSERT INTO scheduled_jobs(
957
+ id, title, enabled, schedule_kind, cron, every_seconds, timezone, payload_kind,
958
+ payload_json, cwd, env_json, timeout_ms, concurrency, misfire, revision,
959
+ created_at, updated_at, content_hash, absent_at, projected_at
960
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)
961
+ ON CONFLICT(id) DO UPDATE SET
962
+ title = excluded.title,
963
+ enabled = excluded.enabled,
964
+ schedule_kind = excluded.schedule_kind,
965
+ cron = excluded.cron,
966
+ every_seconds = excluded.every_seconds,
967
+ timezone = excluded.timezone,
968
+ payload_kind = excluded.payload_kind,
969
+ payload_json = excluded.payload_json,
970
+ cwd = excluded.cwd,
971
+ env_json = excluded.env_json,
972
+ timeout_ms = excluded.timeout_ms,
973
+ concurrency = excluded.concurrency,
974
+ misfire = excluded.misfire,
975
+ revision = excluded.revision,
976
+ created_at = excluded.created_at,
977
+ updated_at = excluded.updated_at,
978
+ content_hash = excluded.content_hash,
979
+ absent_at = NULL,
980
+ projected_at = excluded.projected_at
981
+ `;
982
+
983
+ export function jobToRow(job, now) {
984
+ return [
985
+ job.id,
986
+ job.title,
987
+ job.enabled ? 1 : 0,
988
+ job.schedule.kind,
989
+ job.schedule.kind === 'cron' ? job.schedule.expression : null,
990
+ job.schedule.kind === 'interval' ? job.schedule.everySeconds : null,
991
+ job.schedule.timezone,
992
+ job.payload.kind,
993
+ canonicalJson(job.payload),
994
+ job.cwd,
995
+ canonicalJson(job.envPassthrough),
996
+ job.timeoutMs,
997
+ job.concurrency,
998
+ job.misfire,
999
+ job.revision,
1000
+ job.createdAt,
1001
+ job.updatedAt,
1002
+ jobContentHash(job),
1003
+ now,
1004
+ ];
1005
+ }
1006
+
1007
+ export function projectJobRow(db, job, now) {
1008
+ db.prepare(UPSERT_JOB_SQL).run(...jobToRow(job, now));
1009
+ }
1010
+
1011
+ const UPSERT_RUN_SQL = `
1012
+ INSERT INTO job_runs(
1013
+ run_id, job_id, trigger, state, reason_code, exit_code, signal, pid, host,
1014
+ started_at, finished_at, duration_ms, stdout_path, stderr_path, prompt_path,
1015
+ stdout_bytes, stderr_bytes, stdout_sha256, stderr_sha256, stdout_truncated,
1016
+ stderr_truncated, parse_error, content_hash, projected_at
1017
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1018
+ ON CONFLICT(run_id) DO UPDATE SET
1019
+ job_id = excluded.job_id, trigger = excluded.trigger, state = excluded.state,
1020
+ reason_code = excluded.reason_code, exit_code = excluded.exit_code, signal = excluded.signal,
1021
+ pid = excluded.pid, host = excluded.host, started_at = excluded.started_at,
1022
+ finished_at = excluded.finished_at, duration_ms = excluded.duration_ms,
1023
+ stdout_path = excluded.stdout_path, stderr_path = excluded.stderr_path,
1024
+ prompt_path = excluded.prompt_path, stdout_bytes = excluded.stdout_bytes,
1025
+ stderr_bytes = excluded.stderr_bytes, stdout_sha256 = excluded.stdout_sha256,
1026
+ stderr_sha256 = excluded.stderr_sha256, stdout_truncated = excluded.stdout_truncated,
1027
+ stderr_truncated = excluded.stderr_truncated, parse_error = excluded.parse_error,
1028
+ content_hash = excluded.content_hash, projected_at = excluded.projected_at
1029
+ `;
1030
+
1031
+ /**
1032
+ * Verify every recorded stream hash against its file.
1033
+ *
1034
+ * The manifest hash is authoritative and is never rewritten: a mismatch — or a
1035
+ * missing file — is the spec's `E_LOG_HASH` parse error, so a tampered or
1036
+ * truncated log can never be served as intact. The hash scope is exactly
1037
+ * `entry.bytes`, the bytes written before the truncation marker: the writer
1038
+ * appends the marker after the hashed scope, so hashing the whole file would
1039
+ * report every capped stream as tampered.
1040
+ */
1041
+ const verifyLogHashes = (teamRoot, logs) => {
1042
+ if (!teamRoot) return null;
1043
+ const root = path.resolve(resolveTeamRoot(teamRoot));
1044
+ const runsRoot = path.join(root, SCHEDULER_DIR, RUNS_DIR);
1045
+ for (const stream of LOG_STREAMS) {
1046
+ const entry = isRecord(logs[stream]) ? logs[stream] : null;
1047
+ if (entry === null || typeof entry.path !== 'string' || typeof entry.sha256 !== 'string') continue;
1048
+ const resolved = path.resolve(root, entry.path);
1049
+ if (resolved !== runsRoot && !resolved.startsWith(runsRoot + path.sep)) return 'E_LOG_HASH';
1050
+ const bytes = Number.isInteger(entry.bytes) && entry.bytes >= 0 ? entry.bytes : null;
1051
+ if (bytes === null) return 'E_LOG_HASH';
1052
+ try {
1053
+ const buffer = Buffer.alloc(bytes);
1054
+ const fd = fs.openSync(resolved, 'r');
1055
+ let read = 0;
1056
+ try {
1057
+ read = fs.readSync(fd, buffer, 0, bytes, 0);
1058
+ } finally {
1059
+ fs.closeSync(fd);
1060
+ }
1061
+ if (read !== bytes || sha256(buffer) !== entry.sha256) return 'E_LOG_HASH';
1062
+ } catch {
1063
+ return 'E_LOG_HASH';
1064
+ }
1065
+ }
1066
+ return null;
1067
+ };
1068
+
1069
+ const runRowValues = (manifest, projectedAt, teamRoot) => {
1070
+ const child = isRecord(manifest.child) ? manifest.child : {};
1071
+ const logs = isRecord(manifest.logs) ? manifest.logs : {};
1072
+ const stdout = isRecord(logs.stdout) ? logs.stdout : {};
1073
+ const stderr = isRecord(logs.stderr) ? logs.stderr : {};
1074
+ const hashError = verifyLogHashes(teamRoot, logs);
1075
+ const parseError = typeof manifest.parseError === 'string' ? manifest.parseError : hashError;
1076
+ return [
1077
+ manifest.runId,
1078
+ manifest.jobId,
1079
+ TRIGGERS.includes(manifest.trigger) ? manifest.trigger : 'schedule',
1080
+ RUN_STATES.includes(manifest.state) ? manifest.state : 'failed',
1081
+ manifest.reasonCode ?? null,
1082
+ Number.isInteger(child.exitCode) ? child.exitCode : null,
1083
+ typeof child.signal === 'string' ? child.signal : null,
1084
+ Number.isInteger(child.pid) ? child.pid : null,
1085
+ String(manifest.scheduler?.host ?? 'unknown'),
1086
+ String(child.startedAt ?? manifest.startedAt ?? new Date(0).toISOString()),
1087
+ typeof child.finishedAt === 'string' ? child.finishedAt : null,
1088
+ Number.isInteger(child.durationMs) ? child.durationMs : null,
1089
+ typeof stdout.path === 'string' ? stdout.path : null,
1090
+ typeof stderr.path === 'string' ? stderr.path : null,
1091
+ typeof manifest.prompt?.path === 'string' ? manifest.prompt.path : null,
1092
+ Number.isInteger(stdout.bytes) ? stdout.bytes : 0,
1093
+ Number.isInteger(stderr.bytes) ? stderr.bytes : 0,
1094
+ typeof stdout.sha256 === 'string' ? stdout.sha256 : null,
1095
+ typeof stderr.sha256 === 'string' ? stderr.sha256 : null,
1096
+ stdout.truncated ? 1 : 0,
1097
+ stderr.truncated ? 1 : 0,
1098
+ parseError,
1099
+ sha256(canonicalJson({ ...manifest, projectedAt: undefined })),
1100
+ projectedAt,
1101
+ ];
1102
+ };
1103
+
1104
+ export function projectRunRow(db, manifest, projectedAt, teamRoot = null) {
1105
+ db.prepare(UPSERT_RUN_SQL).run(...runRowValues(manifest, projectedAt, teamRoot));
1106
+ db.prepare('DELETE FROM job_run_events WHERE run_id = ?').run(manifest.runId);
1107
+ const events = Array.isArray(manifest.events) ? manifest.events : [];
1108
+ const insert = db.prepare(
1109
+ 'INSERT INTO job_run_events(run_id, seq, at, state, code, message) VALUES (?, ?, ?, ?, ?, ?)',
1110
+ );
1111
+ events.forEach((event, index) => {
1112
+ insert.run(
1113
+ manifest.runId,
1114
+ Number.isInteger(event.seq) ? event.seq : index + 1,
1115
+ String(event.at ?? manifest.startedAt ?? new Date(0).toISOString()),
1116
+ String(event.state ?? manifest.state ?? 'failed'),
1117
+ event.code ?? null,
1118
+ event.message ?? null,
1119
+ );
1120
+ });
1121
+ }
1122
+
1123
+ /**
1124
+ * Project `jobs.json` and `runs/**` into the three tables.
1125
+ *
1126
+ * Ordering is jobs then runs (the foreign key demands it). A malformed file
1127
+ * tombstones nothing and counts an error; a job id absent from a valid file is
1128
+ * tombstoned and pruned with its runs.
1129
+ */
1130
+ export function projectScheduler(db, options = {}) {
1131
+ const teamRoot = resolveTeamRoot(options.teamRoot);
1132
+ const now = options.now ?? new Date().toISOString();
1133
+ const result = { jobs: 0, runs: 0, absent: 0, pruned: 0, failed: 0, errors: [] };
1134
+
1135
+ let file = null;
1136
+ try {
1137
+ file = readJobsFile(teamRoot);
1138
+ } catch (error) {
1139
+ result.failed += 1;
1140
+ result.errors.push({ path: schedulerPaths(teamRoot).jobs, reason: error.message });
1141
+ }
1142
+
1143
+ if (file) {
1144
+ const seen = new Set();
1145
+ for (const job of file.jobs) {
1146
+ projectJobRow(db, job, now);
1147
+ seen.add(job.id);
1148
+ result.jobs += 1;
1149
+ }
1150
+ const present = db.prepare('SELECT id FROM scheduled_jobs WHERE absent_at IS NULL').all();
1151
+ const update = db.prepare('UPDATE scheduled_jobs SET absent_at = ? WHERE id = ? AND absent_at IS NULL');
1152
+ for (const row of present) {
1153
+ if (seen.has(row.id)) continue;
1154
+ update.run(now, row.id);
1155
+ result.absent += 1;
1156
+ }
1157
+ result.pruned += db.prepare('DELETE FROM scheduled_jobs WHERE absent_at IS NOT NULL').run().changes;
1158
+
1159
+ const knownJobs = new Set(
1160
+ db.prepare('SELECT id FROM scheduled_jobs').all().map((row) => String(row.id)),
1161
+ );
1162
+ const seenRuns = new Set();
1163
+ for (const entry of listRunDirectories(teamRoot)) {
1164
+ if (!knownJobs.has(entry.jobId)) continue;
1165
+ let manifest;
1166
+ try {
1167
+ manifest = JSON.parse(fs.readFileSync(entry.manifest, 'utf8'));
1168
+ if (!isRecord(manifest)) throw new Error('run.json must be an object');
1169
+ } catch (error) {
1170
+ result.failed += 1;
1171
+ result.errors.push({ path: entry.manifest, reason: error.message });
1172
+ continue;
1173
+ }
1174
+ try {
1175
+ projectRunRow(db, manifest, now, teamRoot);
1176
+ seenRuns.add(String(manifest.runId));
1177
+ result.runs += 1;
1178
+ } catch (error) {
1179
+ result.failed += 1;
1180
+ result.errors.push({ path: entry.manifest, reason: error.message });
1181
+ }
1182
+ }
1183
+ // A run whose manifest vanished is pruned, exactly like a tombstoned job.
1184
+ const stale = db.prepare('SELECT run_id FROM job_runs').all();
1185
+ const remove = db.prepare('DELETE FROM job_runs WHERE run_id = ?');
1186
+ for (const row of stale) {
1187
+ if (seenRuns.has(String(row.run_id))) continue;
1188
+ remove.run(row.run_id);
1189
+ result.pruned += 1;
1190
+ }
1191
+ }
1192
+ return result;
1193
+ }
1194
+
1195
+ /** Row retention: newest 200 per job, 30 days, 2 GiB per root, never active. */
1196
+ export function retainRuns(db, options = {}) {
1197
+ const now = options.now === undefined ? Date.now() : Number(options.now);
1198
+ const cutoff = new Date(now - JOB_RUN_RETENTION_DAYS * 86400000).toISOString();
1199
+ let pruned = 0;
1200
+ const active = new Set(ACTIVE_RUN_STATES);
1201
+ const jobs = db.prepare('SELECT DISTINCT job_id FROM job_runs').all().map((row) => String(row.job_id));
1202
+ for (const jobId of jobs) {
1203
+ const rows = db
1204
+ .prepare('SELECT run_id, state FROM job_runs WHERE job_id = ? ORDER BY started_at DESC')
1205
+ .all(jobId);
1206
+ rows.forEach((row, index) => {
1207
+ if (active.has(String(row.state))) return;
1208
+ if (index < JOB_RUN_RETENTION) return;
1209
+ pruned += db.prepare('DELETE FROM job_runs WHERE run_id = ?').run(String(row.run_id)).changes;
1210
+ });
1211
+ }
1212
+ const old = db
1213
+ .prepare('SELECT run_id, state FROM job_runs WHERE started_at < ?')
1214
+ .all(cutoff);
1215
+ for (const row of old) {
1216
+ if (active.has(String(row.state))) continue;
1217
+ pruned += db.prepare('DELETE FROM job_runs WHERE run_id = ?').run(String(row.run_id)).changes;
1218
+ }
1219
+ return pruned;
1220
+ }
1221
+
1222
+ /* --------------------------------- log reads ------------------------------- */
1223
+
1224
+ /**
1225
+ * One bounded chunk of a run log. `offset` counts bytes already rendered;
1226
+ * `limit` is clamped to the declared maximum.
1227
+ */
1228
+ export function readLogChunk(teamRoot, row, options = {}) {
1229
+ const offset = Number(options.offset ?? 0);
1230
+ const limit = Number(options.limit ?? DEFAULT_LOG_LIMIT);
1231
+ if (!Number.isInteger(offset) || offset < 0) teamDbFail('E_VALIDATION', 'parameters "offset": must be a non-negative integer', 3);
1232
+ if (!Number.isInteger(limit) || limit < MIN_LOG_LIMIT || limit > MAX_LOG_LIMIT) {
1233
+ teamDbFail('E_VALIDATION', `parameters "limit": must be between ${MIN_LOG_LIMIT} and ${MAX_LOG_LIMIT}`, 3);
1234
+ }
1235
+ const stream = options.stream === 'stderr' ? 'stderr' : 'stdout';
1236
+ const relative = stream === 'stdout' ? row.stdout_path : row.stderr_path;
1237
+ const totalBytes = Number(stream === 'stdout' ? row.stdout_bytes : row.stderr_bytes ?? 0);
1238
+ const truncated = Boolean(stream === 'stdout' ? row.stdout_truncated : row.stderr_truncated);
1239
+ if (typeof relative !== 'string' || relative === '') {
1240
+ return { stream, offset, limit, totalBytes: 0, truncated: false, text: '' };
1241
+ }
1242
+ if (offset > totalBytes) {
1243
+ teamDbFail('E_RANGE', `offset ${offset} is past the ${totalBytes}-byte log`, 2);
1244
+ }
1245
+ const file = confineRunPath(teamRoot, relative);
1246
+ const readBytes = Math.min(limit + 3, Math.max(0, totalBytes - offset));
1247
+ const buffer = Buffer.alloc(readBytes);
1248
+ const fd = fs.openSync(file, 'r');
1249
+ let bytesRead = 0;
1250
+ try {
1251
+ bytesRead = fs.readSync(fd, buffer, 0, readBytes, offset);
1252
+ } finally {
1253
+ fs.closeSync(fd);
1254
+ }
1255
+ // Return at most `limit` bytes, never a partial code point: the extra three
1256
+ // bytes exist only so a character that starts inside the window can finish.
1257
+ const window = buffer.subarray(0, bytesRead);
1258
+ let end = Math.min(limit, window.length);
1259
+ while (end > 0 && end < window.length && (window[end] & 0xc0) === 0x80) end -= 1;
1260
+ const text = window.subarray(0, end).toString('utf8');
1261
+ return { stream, offset, limit, totalBytes, truncated, text };
1262
+ }
1263
+
1264
+ /** Trim a trailing partial UTF-8 sequence, the document-chunk rule reused. */
1265
+ export function sliceUtf8(buffer) {
1266
+ let end = buffer.length;
1267
+ while (end > 0 && (buffer[end - 1] & 0xc0) === 0x80) end -= 1;
1268
+ if (end > 0) {
1269
+ const lead = buffer[end - 1];
1270
+ if (lead & 0x80) {
1271
+ const need = lead >= 0xf0 ? 4 : lead >= 0xe0 ? 3 : lead >= 0xc0 ? 2 : 0;
1272
+ if (need === 0 || buffer.length - (end - 1) < need) end -= 1;
1273
+ }
1274
+ }
1275
+ return buffer.subarray(0, end).toString('utf8');
1276
+ }
1277
+
1278
+ /* ------------------------------- child capture ----------------------------- */
1279
+
1280
+ /**
1281
+ * A writable log that stops at `cap` bytes, appends exactly one marker and
1282
+ * keeps the sha256 of what it wrote. Output is streamed, never buffered.
1283
+ */
1284
+ export class CappedLogWriter extends Writable {
1285
+ constructor(filePath, cap = MAX_RUN_LOG_BYTES) {
1286
+ super();
1287
+ fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
1288
+ this.fd = fs.openSync(filePath, 'w', 0o600);
1289
+ this.cap = cap;
1290
+ this.bytes = 0;
1291
+ this.truncated = false;
1292
+ this.hash = crypto.createHash('sha256');
1293
+ this.finalized = false;
1294
+ }
1295
+
1296
+ _write(chunk, _encoding, callback) {
1297
+ const remaining = this.cap - this.bytes;
1298
+ if (remaining > 0) {
1299
+ const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk;
1300
+ fs.writeSync(this.fd, slice);
1301
+ this.hash.update(slice);
1302
+ this.bytes += slice.length;
1303
+ }
1304
+ if (chunk.length > remaining) this.truncated = true;
1305
+ callback();
1306
+ }
1307
+
1308
+ _final(callback) {
1309
+ try {
1310
+ if (this.truncated) fs.writeSync(this.fd, `\n${TRUNCATION_MARKER(this.cap)}\n`);
1311
+ } finally {
1312
+ fs.closeSync(this.fd);
1313
+ this.finalized = true;
1314
+ }
1315
+ callback();
1316
+ }
1317
+
1318
+ digest() {
1319
+ return this.hash.digest('hex');
1320
+ }
1321
+ }
1322
+
1323
+ /* ------------------------------ child environment -------------------------- */
1324
+
1325
+ /**
1326
+ * The fixed small base environment plus the declared names. The six
1327
+ * `AI_RULES_TEAM_DB_*` names are never forwarded, so a child that calls
1328
+ * `team-db.mjs` cannot inherit a kill switch or a root override. `win32` adds
1329
+ * the system/temp/profile names a Windows child needs to start at all; the
1330
+ * whole parent environment is never inherited.
1331
+ */
1332
+ export function childEnvironment(job, sourceEnv = process.env, platform = process.platform) {
1333
+ const env = {};
1334
+ const names = platform === 'win32' ? windowsBaseEnvNames() : BASE_ENV_NAMES;
1335
+ for (const name of names) {
1336
+ const value = sourceEnv[name] ?? (name === 'TMPDIR' ? sourceEnv.TEMP : undefined);
1337
+ if (typeof value === 'string' && value !== '') env[name] = value;
1338
+ }
1339
+ for (const name of job.envPassthrough) {
1340
+ if (name.startsWith(BLOCKED_ENV_PREFIX)) continue;
1341
+ const value = sourceEnv[name];
1342
+ if (typeof value === 'string' && value !== '') env[name] = value;
1343
+ }
1344
+ env.TZ = job.schedule.timezone;
1345
+ return env;
1346
+ }
1347
+
1348
+ /** Resolve a declared `cwd` against the team root; a missing one is a reason. */
1349
+ export function resolveJobCwd(job, teamRoot) {
1350
+ const resolved = path.isAbsolute(job.cwd) ? path.resolve(job.cwd) : path.resolve(teamRoot, job.cwd);
1351
+ try {
1352
+ if (fs.statSync(resolved).isDirectory()) return { cwd: resolved, reason: null };
1353
+ } catch {
1354
+ /* reported below */
1355
+ }
1356
+ return { cwd: resolved, reason: 'E_CWD_MISSING' };
1357
+ }
1358
+
1359
+ /* ---------------------------- executable resolution ------------------------ */
1360
+
1361
+ const isExistingFile = (candidate) => {
1362
+ try {
1363
+ return fs.statSync(candidate).isFile();
1364
+ } catch {
1365
+ return false;
1366
+ }
1367
+ };
1368
+
1369
+ const windowsPathEntries = (env) =>
1370
+ String(env.PATH ?? env.Path ?? '')
1371
+ .split(';')
1372
+ .map((entry) => entry.trim().replace(/^"|"$/g, ''))
1373
+ .filter(Boolean);
1374
+
1375
+ const windowsExtensions = (env) =>
1376
+ String(env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD')
1377
+ .split(';')
1378
+ .map((extension) => extension.trim())
1379
+ .filter(Boolean);
1380
+
1381
+ /**
1382
+ * Windows has no shebang: a bare `npx` is the `npx.cmd` shim, and `spawn` does
1383
+ * not apply PATHEXT. Resolve the name here so the executor can pass a concrete
1384
+ * file (and decide whether it needs a shell). POSIX returns the name unchanged.
1385
+ */
1386
+ export function resolveExecutable(command, { platform = process.platform, env = process.env, cwd = process.cwd() } = {}) {
1387
+ if (platform !== 'win32') return command;
1388
+ const hasExtension = path.extname(command) !== '';
1389
+ const absolute = path.isAbsolute(command) || /^[A-Za-z]:[\\/]/.test(command) || command.startsWith('\\\\');
1390
+ const containsSeparator = /[\\/]/.test(command);
1391
+ const candidates = (base) => {
1392
+ if (hasExtension) return [base];
1393
+ const names = [base];
1394
+ for (const extension of windowsExtensions(env)) {
1395
+ // The lower-case spelling is the one npm ships; a case-sensitive volume
1396
+ // still gets the declared PATHEXT spelling as a fallback.
1397
+ const lower = extension.toLowerCase();
1398
+ if (lower !== extension) names.push(`${base}${lower}`);
1399
+ names.push(`${base}${extension}`);
1400
+ }
1401
+ return names;
1402
+ };
1403
+ if (absolute || containsSeparator) {
1404
+ const base = absolute ? command : path.resolve(cwd, command);
1405
+ return candidates(base).find(isExistingFile) ?? command;
1406
+ }
1407
+ for (const entry of windowsPathEntries(env)) {
1408
+ const directory = path.isAbsolute(entry) ? entry : path.resolve(cwd, entry);
1409
+ const found = candidates(path.join(directory, command)).find(isExistingFile);
1410
+ if (found) return found;
1411
+ }
1412
+ return command;
1413
+ }
1414
+
1415
+ /** A `.cmd`/`.bat` runs through `cmd.exe`, which joins argv into one line. */
1416
+ export const quoteWindowsArg = (value) => (/[\s"]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value);
1417
+
1418
+ /* -------------------------------- CLI surface ------------------------------ */
1419
+
1420
+ const renderJson = (value) => `${JSON.stringify(value)}\n`;
1421
+
1422
+ const listRow = (job, context) => ({
1423
+ job,
1424
+ nextFireAt: nextFireAt(job, { now: context.now, lastFireAt: context.lastFireAt?.[job.id] ?? null }),
1425
+ });
1426
+
1427
+ /**
1428
+ * `jobs list|get|put|delete|enable|disable` over the files only. `list` and
1429
+ * `get` never open the database, so they work with it absent.
1430
+ */
1431
+ export function runJobsCommand(subcommand, args, options = {}) {
1432
+ const teamRoot = resolveTeamRoot(options.root);
1433
+ const json = Boolean(options.json);
1434
+ const quiet = Boolean(options.quiet);
1435
+ const id = args[0] ?? options.id ?? null;
1436
+
1437
+ if (subcommand === 'list') {
1438
+ const file = readJobsFile(teamRoot);
1439
+ const state = readStateFile(teamRoot);
1440
+ const jobs = file.jobs
1441
+ .filter((job) => (options.enabled ? job.enabled : true))
1442
+ .map((job) => listRow(job, { now: Date.now(), lastFireAt: state.lastFireAt }));
1443
+ if (json) return { exitCode: 0, output: renderJson({ jobs, total: jobs.length }) };
1444
+ if (quiet) return { exitCode: 0, output: '' };
1445
+ const lines = ['ID ENABLED SCHEDULE NEXT FIRE (UTC)'];
1446
+ for (const row of jobs) {
1447
+ const schedule =
1448
+ row.job.schedule.kind === 'cron'
1449
+ ? `${row.job.schedule.expression} ${row.job.schedule.timezone}`
1450
+ : `every ${row.job.schedule.everySeconds}s ${row.job.schedule.timezone}`;
1451
+ lines.push(`${row.job.id} ${row.job.enabled ? 'yes' : 'no'} ${schedule} ${row.nextFireAt ?? '-'}`);
1452
+ }
1453
+ return { exitCode: 0, output: `${lines.join('\n')}\n` };
1454
+ }
1455
+
1456
+ if (subcommand === 'get') {
1457
+ if (!id) teamDbFail('E_USAGE', 'jobs get needs a job id', 3);
1458
+ const file = readJobsFile(teamRoot);
1459
+ const job = file.jobs.find((entry) => entry.id === id);
1460
+ if (!job) teamDbFail('E_NOT_FOUND', `no job "${id}" in ${schedulerPaths(teamRoot).jobs}`, 1);
1461
+ const state = readStateFile(teamRoot);
1462
+ const next = nextFireInstants(job, { lastFireAt: state.lastFireAt?.[id] ?? null, count: 3 });
1463
+ if (json) return { exitCode: 0, output: renderJson({ job, nextFire: next }) };
1464
+ return {
1465
+ exitCode: 0,
1466
+ output: `${JSON.stringify(job, null, 2)}\nnext fire: ${next.join(', ') || '-'}\n`,
1467
+ };
1468
+ }
1469
+
1470
+ if (subcommand === 'put') {
1471
+ if (isKillSwitchSet(process.env)) teamDbFail('E_DISABLED', 'disabled by AI_RULES_TEAM_DB_DISABLE', 1);
1472
+ const source = options.file;
1473
+ if (typeof source !== 'string' || source === '') teamDbFail('E_USAGE', 'jobs put needs --file <path|->', 3);
1474
+ const text = source === '-' ? fs.readFileSync(0, 'utf8') : fs.readFileSync(source, 'utf8');
1475
+ let input;
1476
+ try {
1477
+ input = JSON.parse(text);
1478
+ } catch (error) {
1479
+ teamDbFail('E_VALIDATION', `parameter "job": the body is not JSON (${error.message})`, 3);
1480
+ }
1481
+ const file = readJobsFile(teamRoot);
1482
+ const existingIndex = file.jobs.findIndex((job) => job.id === input?.id);
1483
+ const existing = existingIndex >= 0 ? file.jobs[existingIndex] : null;
1484
+ if (existing) {
1485
+ // An update is an optimistic lock: the revision is required and must
1486
+ // match. A shape the contract forbids (null or a non-integer) is
1487
+ // `E_VALIDATION`; a missing or stale one is `E_CONFLICT`.
1488
+ if (input.revision === undefined) {
1489
+ teamDbFail(
1490
+ 'E_CONFLICT',
1491
+ `job "${existing.id}" is at revision ${existing.revision}; an update must carry "revision"`,
1492
+ 1,
1493
+ );
1494
+ }
1495
+ if (!Number.isInteger(input.revision) || input.revision < 1) {
1496
+ failField('revision', 'must be an integer of at least 1');
1497
+ }
1498
+ if (input.revision !== existing.revision) {
1499
+ teamDbFail(
1500
+ 'E_CONFLICT',
1501
+ `job "${existing.id}" is at revision ${existing.revision}, the body sent ${input.revision}`,
1502
+ 1,
1503
+ );
1504
+ }
1505
+ if (input.id !== existing.id) {
1506
+ teamDbFail('E_CONFLICT', 'the id is immutable; create a new job instead', 1);
1507
+ }
1508
+ } else if (input?.revision !== undefined) {
1509
+ // A create carries no revision, or revision 1. A forbidden shape is
1510
+ // `E_VALIDATION`; an integer other than 1 is `E_CONFLICT`.
1511
+ if (!Number.isInteger(input.revision) || input.revision < 1) {
1512
+ failField('revision', 'must be an integer of at least 1');
1513
+ }
1514
+ if (input.revision !== 1) {
1515
+ teamDbFail('E_CONFLICT', `job "${String(input?.id)}" does not exist; revision must be 1`, 1);
1516
+ }
1517
+ }
1518
+ const nowIso = new Date().toISOString();
1519
+ const normalized = validateJob(
1520
+ {
1521
+ ...input,
1522
+ createdAt: existing ? existing.createdAt : input?.createdAt ?? nowIso,
1523
+ updatedAt: nowIso,
1524
+ revision: existing ? existing.revision + 1 : 1,
1525
+ },
1526
+ { teamRoot },
1527
+ );
1528
+ if (existing && normalized.createdAt !== existing.createdAt) {
1529
+ teamDbFail('E_VALIDATION', 'parameter "createdAt": is immutable', 3);
1530
+ }
1531
+ if (options.dryRun) {
1532
+ if (json) return { exitCode: 0, output: renderJson({ ok: true, dryRun: true, job: normalized }) };
1533
+ return { exitCode: 0, output: `${JSON.stringify(normalized, null, 2)}\n` };
1534
+ }
1535
+ const nextJobs = existing
1536
+ ? file.jobs.map((job) => (job.id === normalized.id ? normalized : job))
1537
+ : [...file.jobs, normalized];
1538
+ // File before row: the definition is authoritative, the row re-derivable.
1539
+ writeJobsFile(teamRoot, nextJobs);
1540
+ projectOneJob(teamRoot, normalized);
1541
+ if (json) return { exitCode: 0, output: renderJson({ ok: true, job: normalized }) };
1542
+ return { exitCode: 0, output: `put: ${normalized.id} revision ${normalized.revision}\n` };
1543
+ }
1544
+
1545
+ if (subcommand === 'delete') {
1546
+ if (isKillSwitchSet(process.env)) teamDbFail('E_DISABLED', 'disabled by AI_RULES_TEAM_DB_DISABLE', 1);
1547
+ if (!id) teamDbFail('E_USAGE', 'jobs delete needs a job id', 3);
1548
+ const file = readJobsFile(teamRoot);
1549
+ const job = file.jobs.find((entry) => entry.id === id);
1550
+ if (!job) teamDbFail('E_NOT_FOUND', `no job "${id}"`, 1);
1551
+ const runsRemoved = options.keepRuns ? 0 : removeRunDirectories(teamRoot, id);
1552
+ writeJobsFile(teamRoot, file.jobs.filter((entry) => entry.id !== id));
1553
+ const removed = projectDeleteJob(teamRoot, id);
1554
+ if (json) return { exitCode: 0, output: renderJson({ ok: true, id, runsRemoved, rowsRemoved: removed }) };
1555
+ return { exitCode: 0, output: `delete: ${id} runsRemoved=${runsRemoved} rowsRemoved=${removed}\n` };
1556
+ }
1557
+
1558
+ if (subcommand === 'enable' || subcommand === 'disable') {
1559
+ if (isKillSwitchSet(process.env)) teamDbFail('E_DISABLED', 'disabled by AI_RULES_TEAM_DB_DISABLE', 1);
1560
+ if (!id) teamDbFail('E_USAGE', `jobs ${subcommand} needs a job id`, 3);
1561
+ const file = readJobsFile(teamRoot);
1562
+ const job = file.jobs.find((entry) => entry.id === id);
1563
+ if (!job) teamDbFail('E_NOT_FOUND', `no job "${id}"`, 1);
1564
+ if (job.enabled === (subcommand === 'enable')) {
1565
+ if (json) return { exitCode: 0, output: renderJson({ ok: true, job, changed: false }) };
1566
+ return { exitCode: 0, output: `${subcommand}: ${id} already ${subcommand}d\n` };
1567
+ }
1568
+ const nowIso = new Date().toISOString();
1569
+ const updated = validateJob(
1570
+ { ...job, enabled: subcommand === 'enable', updatedAt: nowIso, revision: job.revision + 1 },
1571
+ { teamRoot },
1572
+ );
1573
+ writeJobsFile(teamRoot, file.jobs.map((entry) => (entry.id === id ? updated : entry)));
1574
+ projectOneJob(teamRoot, updated);
1575
+ if (json) return { exitCode: 0, output: renderJson({ ok: true, job: updated }) };
1576
+ return { exitCode: 0, output: `${subcommand}: ${id} revision ${updated.revision}\n` };
1577
+ }
1578
+
1579
+ if (subcommand === 'reconcile') {
1580
+ const reconciled = reconcileRuns(teamRoot);
1581
+ if (json) return { exitCode: 0, output: renderJson({ ok: true, reconciled }) };
1582
+ return { exitCode: 0, output: `reconcile: ${reconciled} run(s) interrupted\n` };
1583
+ }
1584
+
1585
+ if (subcommand === 'run') {
1586
+ if (isKillSwitchSet(process.env)) teamDbFail('E_DISABLED', 'disabled by AI_RULES_TEAM_DB_DISABLE', 1);
1587
+ if (!id) teamDbFail('E_USAGE', 'jobs run needs --id <id>', 3);
1588
+ const file = readJobsFile(teamRoot);
1589
+ if (!file.jobs.some((entry) => entry.id === id)) teamDbFail('E_NOT_FOUND', `no job "${id}"`, 1);
1590
+ const requestedAt = new Date().toISOString();
1591
+ const state = readStateFile(teamRoot);
1592
+ state.requests.push({ jobId: id, requestedAt });
1593
+ writeStateFile(teamRoot, state);
1594
+ const online = isLeaseFresh(teamRoot);
1595
+ if (json) return { exitCode: 0, output: renderJson({ requested: true, requestedAt, schedulerOnline: online }) };
1596
+ return { exitCode: 0, output: `run: requested ${id} at ${requestedAt} (scheduler ${online ? 'online' : 'offline'})\n` };
1597
+ }
1598
+
1599
+ teamDbFail('E_USAGE', `unknown jobs subcommand "${subcommand}"`, 3);
1600
+ return null;
1601
+ }
1602
+
1603
+ /* --------------------------- projection entry points ----------------------- */
1604
+
1605
+ const withWritableDb = (teamRoot, fn) => {
1606
+ if (!isSqliteAvailable(process.env)) {
1607
+ process.stderr.write(`${INDEX_UNAVAILABLE_LINE}\n`);
1608
+ return null;
1609
+ }
1610
+ const handle = openTeamDb({ teamRoot });
1611
+ try {
1612
+ return fn(handle.db, handle);
1613
+ } finally {
1614
+ handle.db.close();
1615
+ }
1616
+ };
1617
+
1618
+ export function projectAll(teamRoot) {
1619
+ return withWritableDb(teamRoot, (db) => projectScheduler(db, { teamRoot }));
1620
+ }
1621
+
1622
+ function projectOneJob(teamRoot, job) {
1623
+ return withWritableDb(teamRoot, (db) => {
1624
+ projectJobRow(db, job, new Date().toISOString());
1625
+ return 1;
1626
+ });
1627
+ }
1628
+
1629
+ function projectDeleteJob(teamRoot, id) {
1630
+ return withWritableDb(teamRoot, (db) => {
1631
+ db.prepare('DELETE FROM scheduled_jobs WHERE id = ?').run(id);
1632
+ return 1;
1633
+ });
1634
+ }
1635
+
1636
+ function removeRunDirectories(teamRoot, jobId) {
1637
+ const paths = schedulerPaths(teamRoot);
1638
+ const dir = path.join(paths.runs, jobId);
1639
+ let removed = 0;
1640
+ for (const entry of safeReaddir(dir)) {
1641
+ try {
1642
+ fs.rmSync(path.join(dir, entry), { recursive: true, force: true });
1643
+ removed += 1;
1644
+ } catch {
1645
+ /* a run directory that cannot be removed is reported by the next sync */
1646
+ }
1647
+ }
1648
+ try {
1649
+ fs.rmdirSync(dir);
1650
+ } catch {
1651
+ /* not empty or already gone */
1652
+ }
1653
+ return removed;
1654
+ }
1655
+
1656
+ /**
1657
+ * Reconcile every active run to `interrupted`: one scheduler per root makes an
1658
+ * active row provably orphaned once that process is gone.
1659
+ */
1660
+ export function reconcileRuns(teamRoot, options = {}) {
1661
+ const root = resolveTeamRoot(teamRoot);
1662
+ const nowIso = options.now ?? new Date().toISOString();
1663
+ let reconciled = 0;
1664
+ for (const entry of listRunDirectories(root)) {
1665
+ let manifest;
1666
+ try {
1667
+ manifest = JSON.parse(fs.readFileSync(entry.manifest, 'utf8'));
1668
+ } catch {
1669
+ continue;
1670
+ }
1671
+ if (!ACTIVE_RUN_STATES.includes(String(manifest.state))) continue;
1672
+ const child = isRecord(manifest.child) ? manifest.child : {};
1673
+ const startedAt = Date.parse(child.startedAt ?? manifest.startedAt ?? nowIso);
1674
+ const next = {
1675
+ ...manifest,
1676
+ state: 'interrupted',
1677
+ reasonCode: 'E_ORPHANED',
1678
+ child: { ...child, finishedAt: nowIso, durationMs: Math.max(0, Date.parse(nowIso) - startedAt) },
1679
+ events: [
1680
+ ...(Array.isArray(manifest.events) ? manifest.events : []),
1681
+ { seq: (manifest.events?.length ?? 0) + 1, at: nowIso, state: 'interrupted', code: 'E_ORPHANED', message: 'scheduler restart' },
1682
+ ],
1683
+ };
1684
+ writeRunManifest(root, entry.jobId, entry.runId, next);
1685
+ reconciled += 1;
1686
+ }
1687
+ if (reconciled > 0) projectAll(root);
1688
+ return reconciled;
1689
+ }
1690
+
1691
+ /* ------------------------------- the runtime ------------------------------- */
1692
+
1693
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1694
+
1695
+ const nextScheduleCursor = (job, lastFire, now, tickMs) => {
1696
+ if (lastFire !== null) return lastFire;
1697
+ // No recorded fire yet: a cron job is due only for an instant inside the
1698
+ // current tick window; an interval job is due immediately.
1699
+ return job.schedule.kind === 'interval' ? now - job.schedule.everySeconds * 1000 : now - Math.max(tickMs, 1000);
1700
+ };
1701
+
1702
+ export const jobDueInstants = (job, lastFire, now, tickMs) => {
1703
+ const instants = [];
1704
+ let cursor = nextScheduleCursor(job, lastFire, now, tickMs);
1705
+ const every = job.schedule.kind === 'interval' ? job.schedule.everySeconds * 1000 : null;
1706
+ const parsed = job.schedule.kind === 'cron' ? parseCronExpression(job.schedule.expression) : null;
1707
+ for (let guard = 0; guard <= MAX_CATCH_UP; guard += 1) {
1708
+ const next =
1709
+ parsed === null
1710
+ ? cursor + every
1711
+ : nextCronInstant(parsed, job.schedule.timezone, cursor);
1712
+ if (next === null || next > now) break;
1713
+ instants.push(next);
1714
+ cursor = next;
1715
+ }
1716
+ return instants;
1717
+ };
1718
+
1719
+ const activeRunCount = (db, jobId) =>
1720
+ Number(
1721
+ db
1722
+ .prepare(
1723
+ `SELECT COUNT(*) AS n FROM job_runs WHERE job_id = ? AND state IN ('claimed','running')`,
1724
+ )
1725
+ .get(jobId).n,
1726
+ );
1727
+
1728
+ const baseManifest = (job, runId, trigger, scheduler) => ({
1729
+ version: RUN_MANIFEST_VERSION,
1730
+ runId,
1731
+ jobId: job.id,
1732
+ trigger,
1733
+ revision: job.revision,
1734
+ definitionHash: jobContentHash(job),
1735
+ scheduler: { pid: process.pid, host: os.hostname() },
1736
+ startedAt: new Date().toISOString(),
1737
+ child: {},
1738
+ state: 'claimed',
1739
+ reasonCode: null,
1740
+ logs: { stdout: { bytes: 0, truncated: false }, stderr: { bytes: 0, truncated: false } },
1741
+ events: [
1742
+ { seq: 1, at: new Date().toISOString(), state: 'claimed', code: null, message: 'claim' },
1743
+ ],
1744
+ });
1745
+
1746
+ /**
1747
+ * Mark the run that replays a truncated `catch-up`: the manifest carries the
1748
+ * flag and an event so the projection tells a bounded replay from a complete
1749
+ * one.
1750
+ */
1751
+ const withCatchUpNote = (manifest, note, at) => {
1752
+ if (!note) return manifest;
1753
+ const droppedAtLeast = Math.max(1, note.dueAtLeast - MAX_CATCH_UP);
1754
+ return {
1755
+ ...manifest,
1756
+ catchUp: { truncated: true, replayed: MAX_CATCH_UP, droppedAtLeast, dueAtLeast: note.dueAtLeast },
1757
+ events: [
1758
+ ...manifest.events,
1759
+ {
1760
+ seq: manifest.events.length + 1,
1761
+ at,
1762
+ state: 'claimed',
1763
+ code: 'E_CATCH_UP_TRUNCATED',
1764
+ message: `catch-up truncated: replayed ${MAX_CATCH_UP}, at least ${droppedAtLeast} occurrence(s) dropped`,
1765
+ },
1766
+ ],
1767
+ };
1768
+ };
1769
+
1770
+ const insertRunRow = (db, manifest, now) => {
1771
+ projectRunRow(db, manifest, now);
1772
+ };
1773
+
1774
+ const claimRun = (db, job, options) => {
1775
+ const { trigger, runId, now, policy, catchUp = null } = options;
1776
+ const manifest = baseManifest(job, runId, trigger, options.scheduler);
1777
+ const active = activeRunCount(db, job.id);
1778
+ db.exec('BEGIN IMMEDIATE');
1779
+ try {
1780
+ // Re-read inside the write lock: the count above is only a hint.
1781
+ const claimed = activeRunCount(db, job.id);
1782
+ const skip = policy === 'skip' && claimed > 0;
1783
+ const recorded = skip ? manifest : withCatchUpNote(manifest, catchUp, now);
1784
+ const stored = skip
1785
+ ? {
1786
+ ...manifest,
1787
+ state: 'skipped',
1788
+ reasonCode: 'E_CONCURRENCY_SKIP',
1789
+ events: [
1790
+ ...manifest.events,
1791
+ {
1792
+ seq: 2,
1793
+ at: now,
1794
+ state: 'skipped',
1795
+ code: 'E_CONCURRENCY_SKIP',
1796
+ message: `run ${claimed} still active under concurrency "${policy}"`,
1797
+ },
1798
+ ],
1799
+ }
1800
+ : recorded;
1801
+ insertRunRow(db, stored, now);
1802
+ db.exec('COMMIT');
1803
+ return { claimed: !skip, manifest: stored, active };
1804
+ } catch (error) {
1805
+ try {
1806
+ db.exec('ROLLBACK');
1807
+ } catch {
1808
+ /* the failed transaction is already unwound */
1809
+ }
1810
+ throw error;
1811
+ }
1812
+ };
1813
+
1814
+ const killGroup = (child, signal) => {
1815
+ if (!child.pid) return;
1816
+ try {
1817
+ if (process.platform === 'win32') child.kill(signal);
1818
+ else process.kill(-child.pid, signal);
1819
+ } catch {
1820
+ /* the child may have exited between the timer and the signal */
1821
+ }
1822
+ };
1823
+
1824
+ const finishWriters = (writers) =>
1825
+ Promise.all(
1826
+ writers.map(
1827
+ (writer) =>
1828
+ new Promise((resolve) => {
1829
+ if (writer.finalized) {
1830
+ resolve();
1831
+ return;
1832
+ }
1833
+ writer.once('finish', resolve);
1834
+ writer.once('error', resolve);
1835
+ writer.end();
1836
+ }),
1837
+ ),
1838
+ );
1839
+
1840
+ /**
1841
+ * Run one job child and finalize its manifest.
1842
+ *
1843
+ * One executor (D-1): `spawn(resolved argv[0], argv.slice(1), { cwd, env,
1844
+ * detached, shell })`. The `pipeline` kind is lowered to the same argv at claim
1845
+ * time by rendering `<runDir>/prompt.md` and substituting `{promptFile}`. A
1846
+ * resolved `.cmd`/`.bat` on `win32` is the one case that needs a shell; its
1847
+ * args are quoted for the `cmd.exe` command line.
1848
+ */
1849
+ async function executeRun(context, job, manifest) {
1850
+ const { teamRoot, db, graceMs } = context;
1851
+ const paths = schedulerPaths(teamRoot);
1852
+ const runDir = paths.runDir(job.id, manifest.runId);
1853
+ fs.mkdirSync(runDir, { recursive: true, mode: 0o700 });
1854
+ const startedAt = new Date().toISOString();
1855
+
1856
+ let argv = job.payload.kind === 'command' ? [...job.payload.argv] : null;
1857
+ let promptRecord = null;
1858
+ let reason = null;
1859
+ if (job.payload.kind === 'pipeline') {
1860
+ const templatePath = path.isAbsolute(job.payload.promptTemplate)
1861
+ ? job.payload.promptTemplate
1862
+ : path.resolve(teamRoot, job.payload.promptTemplate);
1863
+ try {
1864
+ const stats = fs.statSync(templatePath);
1865
+ if (stats.size > MAX_PROMPT_BYTES) reason = 'E_PROMPT_TOO_LARGE';
1866
+ else {
1867
+ const template = fs.readFileSync(templatePath, 'utf8');
1868
+ const rendered = template
1869
+ .replaceAll('{{job.id}}', job.id)
1870
+ .replaceAll('{{run.id}}', manifest.runId)
1871
+ .replaceAll('{{run.dir}}', runDir)
1872
+ .replaceAll('{{team.root}}', teamRoot)
1873
+ .replaceAll('{{now}}', startedAt);
1874
+ const promptPath = path.join(runDir, PROMPT_FILE);
1875
+ fs.writeFileSync(promptPath, rendered, { encoding: 'utf8', mode: 0o600 });
1876
+ promptRecord = {
1877
+ path: path.relative(teamRoot, promptPath),
1878
+ sha256: sha256(rendered),
1879
+ };
1880
+ argv = job.payload.runner.map((element) => element.replaceAll('{promptFile}', promptPath));
1881
+ }
1882
+ } catch {
1883
+ reason = 'E_PROMPT_MISSING';
1884
+ }
1885
+ }
1886
+
1887
+ const cwdInfo = resolveJobCwd(job, teamRoot);
1888
+ if (reason === null && cwdInfo.reason) reason = cwdInfo.reason;
1889
+
1890
+ const stdoutWriter = new CappedLogWriter(path.join(runDir, STDOUT_FILE));
1891
+ const stderrWriter = new CappedLogWriter(path.join(runDir, STDERR_FILE));
1892
+ const relative = (file) => path.relative(teamRoot, file);
1893
+
1894
+ const finish = async (extra) => {
1895
+ await finishWriters([stdoutWriter, stderrWriter]);
1896
+ const finishedAt = new Date().toISOString();
1897
+ const durationMs = Math.max(0, Date.parse(finishedAt) - Date.parse(startedAt));
1898
+ const finalManifest = {
1899
+ ...manifest,
1900
+ ...extra,
1901
+ child: {
1902
+ ...(extra.child ?? {}),
1903
+ argv: argv ?? [],
1904
+ cwd: cwdInfo.cwd,
1905
+ startedAt,
1906
+ finishedAt,
1907
+ durationMs,
1908
+ timedOut: Boolean(extra.child?.timedOut),
1909
+ },
1910
+ prompt: promptRecord ?? undefined,
1911
+ logs: {
1912
+ stdout: {
1913
+ path: relative(path.join(runDir, STDOUT_FILE)),
1914
+ bytes: stdoutWriter.bytes,
1915
+ sha256: stdoutWriter.digest(),
1916
+ truncated: stdoutWriter.truncated,
1917
+ },
1918
+ stderr: {
1919
+ path: relative(path.join(runDir, STDERR_FILE)),
1920
+ bytes: stderrWriter.bytes,
1921
+ sha256: stderrWriter.digest(),
1922
+ truncated: stderrWriter.truncated,
1923
+ },
1924
+ },
1925
+ };
1926
+ writeRunManifest(teamRoot, job.id, manifest.runId, finalManifest);
1927
+ projectRunRow(db, finalManifest, new Date().toISOString(), teamRoot);
1928
+ return finalManifest;
1929
+ };
1930
+
1931
+ if (reason !== null) {
1932
+ return finish({
1933
+ state: 'failed',
1934
+ reasonCode: reason,
1935
+ events: [
1936
+ ...manifest.events,
1937
+ { seq: manifest.events.length + 1, at: new Date().toISOString(), state: 'failed', code: reason, message: reason },
1938
+ ],
1939
+ });
1940
+ }
1941
+
1942
+ const env = childEnvironment(job, process.env);
1943
+ const resolvedCommand = resolveExecutable(argv[0], { env, cwd: cwdInfo.cwd });
1944
+ const useShell = process.platform === 'win32' && /\.(cmd|bat)$/i.test(resolvedCommand);
1945
+ const spawnArgs = useShell ? argv.slice(1).map(quoteWindowsArg) : argv.slice(1);
1946
+ return new Promise((resolve) => {
1947
+ let child;
1948
+ let timedOut = false;
1949
+ let settled = false;
1950
+ try {
1951
+ child = spawn(resolvedCommand, spawnArgs, {
1952
+ cwd: cwdInfo.cwd,
1953
+ env,
1954
+ stdio: ['ignore', 'pipe', 'pipe'],
1955
+ detached: process.platform !== 'win32',
1956
+ shell: useShell,
1957
+ });
1958
+ } catch (error) {
1959
+ resolve(
1960
+ finish({
1961
+ state: 'failed',
1962
+ reasonCode: 'E_SPAWN_FAILED',
1963
+ events: [
1964
+ ...manifest.events,
1965
+ { seq: manifest.events.length + 1, at: new Date().toISOString(), state: 'failed', code: 'E_SPAWN_FAILED', message: error.message },
1966
+ ],
1967
+ }),
1968
+ );
1969
+ return;
1970
+ }
1971
+
1972
+ const runningEvent = {
1973
+ seq: manifest.events.length + 1,
1974
+ at: new Date().toISOString(),
1975
+ state: 'running',
1976
+ code: null,
1977
+ message: `pid ${child.pid ?? '-'}`,
1978
+ };
1979
+ writeRunManifest(teamRoot, job.id, manifest.runId, {
1980
+ ...manifest,
1981
+ state: 'running',
1982
+ child: { pid: child.pid ?? null, argv, cwd: cwdInfo.cwd, startedAt },
1983
+ events: [...manifest.events, runningEvent],
1984
+ });
1985
+ projectRunRow(
1986
+ db,
1987
+ { ...manifest, state: 'running', child: { pid: child.pid ?? null, startedAt } },
1988
+ new Date().toISOString(),
1989
+ teamRoot,
1990
+ );
1991
+
1992
+ child.stdout.pipe(stdoutWriter);
1993
+ child.stderr.pipe(stderrWriter);
1994
+
1995
+ let graceTimer = null;
1996
+ const timeoutTimer = setTimeout(() => {
1997
+ timedOut = true;
1998
+ killGroup(child, 'SIGTERM');
1999
+ graceTimer = setTimeout(() => killGroup(child, 'SIGKILL'), graceMs);
2000
+ }, job.timeoutMs);
2001
+
2002
+ const settle = (extra) => {
2003
+ if (settled) return;
2004
+ settled = true;
2005
+ clearTimeout(timeoutTimer);
2006
+ if (graceTimer) clearTimeout(graceTimer);
2007
+ resolve(finish(extra));
2008
+ };
2009
+
2010
+ child.on('error', (error) => {
2011
+ settle({
2012
+ state: 'failed',
2013
+ reasonCode: 'E_SPAWN_FAILED',
2014
+ child: { exitCode: null, signal: null, timedOut },
2015
+ events: [
2016
+ ...manifest.events,
2017
+ runningEvent,
2018
+ { seq: runningEvent.seq + 1, at: new Date().toISOString(), state: 'failed', code: 'E_SPAWN_FAILED', message: error.message },
2019
+ ],
2020
+ });
2021
+ });
2022
+
2023
+ child.on('close', (code, signal) => {
2024
+ const state = timedOut ? 'timeout' : code === 0 ? 'succeeded' : 'failed';
2025
+ const reasonCode =
2026
+ state === 'succeeded'
2027
+ ? null
2028
+ : timedOut
2029
+ ? 'E_TIMEOUT'
2030
+ : typeof signal === 'string'
2031
+ ? `E_SIGNAL_${signal}`
2032
+ : `E_EXIT_${code ?? 'UNKNOWN'}`;
2033
+ settle({
2034
+ state,
2035
+ reasonCode,
2036
+ child: { exitCode: code ?? null, signal: signal ?? null, pid: child.pid ?? null, timedOut },
2037
+ events: [
2038
+ ...manifest.events,
2039
+ runningEvent,
2040
+ {
2041
+ seq: runningEvent.seq + 1,
2042
+ at: new Date().toISOString(),
2043
+ state,
2044
+ code: reasonCode,
2045
+ message: timedOut ? `timeout after ${job.timeoutMs} ms` : `exit ${code ?? signal}`,
2046
+ },
2047
+ ],
2048
+ });
2049
+ });
2050
+ });
2051
+ }
2052
+
2053
+ const pruneRunDirectories = (teamRoot, options = {}) => {
2054
+ const now = options.now === undefined ? Date.now() : Number(options.now);
2055
+ const cutoff = now - JOB_RUN_RETENTION_DAYS * 86400000;
2056
+ const byJob = new Map();
2057
+ for (const entry of listRunDirectories(teamRoot)) {
2058
+ if (!byJob.has(entry.jobId)) byJob.set(entry.jobId, []);
2059
+ byJob.get(entry.jobId).push(entry);
2060
+ }
2061
+ const removed = [];
2062
+ let totalBytes = 0;
2063
+ const survivors = [];
2064
+ for (const entries of byJob.values()) {
2065
+ entries.sort((left, right) => (left.runId < right.runId ? 1 : left.runId > right.runId ? -1 : 0));
2066
+ entries.forEach((entry, index) => {
2067
+ const active = isActiveManifest(entry.manifest);
2068
+ if (!active && (index >= JOB_RUN_RETENTION || entry.mtimeMs < cutoff)) {
2069
+ fs.rmSync(entry.dir, { recursive: true, force: true });
2070
+ removed.push({ jobId: entry.jobId, runId: entry.runId });
2071
+ return;
2072
+ }
2073
+ totalBytes += entry.bytes;
2074
+ survivors.push(entry);
2075
+ });
2076
+ }
2077
+ survivorLoop: for (const entry of survivors.sort((left, right) => left.mtimeMs - right.mtimeMs)) {
2078
+ if (totalBytes <= MAX_RUN_STORE_BYTES) break survivorLoop;
2079
+ if (isActiveManifest(entry.manifest)) continue;
2080
+ fs.rmSync(entry.dir, { recursive: true, force: true });
2081
+ totalBytes -= entry.bytes;
2082
+ removed.push({ jobId: entry.jobId, runId: entry.runId });
2083
+ }
2084
+ return removed;
2085
+ };
2086
+
2087
+ /**
2088
+ * Retention over files and rows together: a pruned run directory takes its
2089
+ * `job_runs` row with it, so `GET /runs` never lists a run whose log is gone.
2090
+ */
2091
+ const pruneRunStore = (db, teamRoot, options = {}) => {
2092
+ const removed = pruneRunDirectories(teamRoot, options);
2093
+ const removeRow = db.prepare('DELETE FROM job_runs WHERE run_id = ?');
2094
+ let rows = 0;
2095
+ for (const entry of removed) rows += removeRow.run(entry.runId).changes;
2096
+ return { directories: removed.length, rows };
2097
+ };
2098
+
2099
+ function isActiveManifest(manifestPath) {
2100
+ try {
2101
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
2102
+ return ACTIVE_RUN_STATES.includes(String(manifest.state));
2103
+ } catch {
2104
+ return false;
2105
+ }
2106
+ }
2107
+
2108
+ /**
2109
+ * `team-db.mjs schedule`: the timer, the lease and the writable connection.
2110
+ *
2111
+ * Startup order is lease → reconcile orphans → project → first claim, so a
2112
+ * rebuilt database can never be missing a definition while its timer runs.
2113
+ * The kill switch is checked before anything is created and at every tick; the
2114
+ * mid-run policy drains (N-5): no new claim, the in-flight child finishes
2115
+ * inside its own timeout, the result is recorded, exit 0.
2116
+ */
2117
+ export async function runScheduler(options = {}) {
2118
+ const teamRoot = resolveTeamRoot(options.teamRoot);
2119
+ const out = options.out ?? ((text) => process.stdout.write(text));
2120
+ const err = options.err ?? ((text) => process.stderr.write(text));
2121
+ const env = options.env ?? process.env;
2122
+ const tickMs = Number(options.intervalMs ?? DEFAULT_TICK_MS);
2123
+ const graceMs = Number(options.graceMs ?? DEFAULT_GRACE_MS);
2124
+ const drainMs = Number(options.drainMs ?? DEFAULT_DRAIN_MS);
2125
+ const once = Boolean(options.once);
2126
+
2127
+ if (isKillSwitchSet(env)) {
2128
+ err('team-db: disabled by AI_RULES_TEAM_DB_DISABLE\n');
2129
+ return 0;
2130
+ }
2131
+ if (!isSqliteAvailable(env)) {
2132
+ err(`${INDEX_UNAVAILABLE_LINE}\n`);
2133
+ return 0;
2134
+ }
2135
+
2136
+ const existing = readLease(teamRoot);
2137
+ if (existing.state === 'running') {
2138
+ teamDbFail(
2139
+ 'E_BUSY',
2140
+ `${schedulerPaths(teamRoot).lock} is held by pid ${existing.lease?.pid ?? '?'}; one scheduler per team root`,
2141
+ 4,
2142
+ );
2143
+ }
2144
+
2145
+ const startedAt = new Date().toISOString();
2146
+ const lease = { version: LEASE_VERSION, pid: process.pid, host: os.hostname(), startedAt, heartbeatAt: startedAt };
2147
+ writeLease(teamRoot, lease);
2148
+ fs.mkdirSync(schedulerPaths(teamRoot).runs, { recursive: true, mode: 0o700 });
2149
+
2150
+ const handle = openTeamDb({ teamRoot });
2151
+ const { db } = handle;
2152
+ let draining = false;
2153
+ const inFlight = new Set();
2154
+
2155
+ /**
2156
+ * Read-modify-write of `state.json`: a request that `jobs run` appended while
2157
+ * this tick runs is merged, never overwritten with the startup copy.
2158
+ */
2159
+ const updateState = (mutate) => {
2160
+ const fresh = readStateFile(teamRoot);
2161
+ mutate(fresh);
2162
+ writeStateFile(teamRoot, fresh);
2163
+ return fresh;
2164
+ };
2165
+
2166
+ const heartbeat = () => {
2167
+ lease.heartbeatAt = new Date().toISOString();
2168
+ writeLease(teamRoot, lease);
2169
+ };
2170
+
2171
+ try {
2172
+ reconcileRuns(teamRoot);
2173
+ projectScheduler(db, { teamRoot });
2174
+ pruneRunStore(db, teamRoot);
2175
+ retainRuns(db);
2176
+ heartbeat();
2177
+ if (!options.quiet) out(`schedule: lease ${path.basename(schedulerPaths(teamRoot).lock)} pid=${process.pid}\n`);
2178
+
2179
+ const shutdown = () => {
2180
+ draining = true;
2181
+ };
2182
+ process.once('SIGINT', shutdown);
2183
+ process.once('SIGTERM', shutdown);
2184
+
2185
+ const tick = async () => {
2186
+ const now = Date.now();
2187
+ const nowIso = new Date(now).toISOString();
2188
+ let file;
2189
+ try {
2190
+ file = readJobsFile(teamRoot);
2191
+ } catch (error) {
2192
+ err(`${error.message}\n`);
2193
+ return;
2194
+ }
2195
+ const jobsById = new Map(file.jobs.map((job) => [job.id, job]));
2196
+
2197
+ // Project a definition the file gained while this process was running:
2198
+ // a claim against a missing row would violate the foreign key.
2199
+ for (const job of file.jobs) {
2200
+ const row = db.prepare('SELECT id FROM scheduled_jobs WHERE id = ?').get(job.id);
2201
+ if (!row) projectJobRow(db, job, nowIso);
2202
+ }
2203
+
2204
+ const sameRequest = (left, right) =>
2205
+ left !== null &&
2206
+ right !== null &&
2207
+ left.jobId === right.jobId &&
2208
+ left.requestedAt === right.requestedAt;
2209
+
2210
+ // Two `jobs run` calls can carry the same millisecond; a claim consumes
2211
+ // exactly one queue entry, never every look-alike.
2212
+ const removeRequest = (requests, request) => {
2213
+ const index = requests.findIndex((entry) => sameRequest(entry, request));
2214
+ if (index < 0) return requests;
2215
+ const next = [...requests];
2216
+ next.splice(index, 1);
2217
+ return next;
2218
+ };
2219
+
2220
+ // Children run concurrently: the claim decides overlap, never the tick
2221
+ // loop. `fire` reports whether the occurrence produced a run record (a
2222
+ // claim or a recorded `skipped`), so a deferred `queue` stays due.
2223
+ const fire = (job, trigger, scheduledInstant, request = null, catchUp = null) => {
2224
+ if (draining || isKillSwitchSet(env)) return false;
2225
+ const runId = newRunId();
2226
+ const policy = job.concurrency;
2227
+ if (policy === 'queue' && activeRunCount(db, job.id) > 0) {
2228
+ // `queue` waits: the occurrence stays due and is claimed once the
2229
+ // active run finalizes. Nothing is recorded, nothing advances.
2230
+ return false;
2231
+ }
2232
+ const claim = claimRun(db, job, {
2233
+ trigger,
2234
+ runId,
2235
+ policy,
2236
+ now: nowIso,
2237
+ catchUp,
2238
+ scheduler: { pid: process.pid, host: lease.host },
2239
+ });
2240
+ writeRunManifest(teamRoot, job.id, runId, claim.manifest);
2241
+ // Merge into the state read at write time: a request appended by
2242
+ // `jobs run` since this tick began is never overwritten.
2243
+ updateState((fresh) => {
2244
+ fresh.lastFireAt[job.id] = scheduledInstant ?? nowIso;
2245
+ if (request !== null) {
2246
+ fresh.requests = removeRequest(fresh.requests, request);
2247
+ }
2248
+ });
2249
+ if (!claim.claimed) {
2250
+ if (!options.quiet) out(`schedule: ${job.id} skipped (${policy})\n`);
2251
+ return true;
2252
+ }
2253
+ const promise = executeRun({ teamRoot, db, graceMs }, job, claim.manifest)
2254
+ .then(() => {
2255
+ pruneRunStore(db, teamRoot);
2256
+ retainRuns(db);
2257
+ try {
2258
+ db.exec('PRAGMA wal_checkpoint(PASSIVE)');
2259
+ } catch {
2260
+ /* a checkpoint is best-effort */
2261
+ }
2262
+ })
2263
+ .catch((error) => {
2264
+ err(`schedule: ${job.id} finalize failed: ${error.message}\n`);
2265
+ })
2266
+ .finally(() => {
2267
+ inFlight.delete(promise);
2268
+ });
2269
+ inFlight.add(promise);
2270
+ return true;
2271
+ };
2272
+
2273
+ // Run-now: the queue is re-read before every claim, and a request leaves
2274
+ // it only when the claim that consumed it is recorded.
2275
+ const pendingRequests = readStateFile(teamRoot).requests.filter(
2276
+ (request) => request && jobsById.has(request.jobId),
2277
+ );
2278
+ for (const request of pendingRequests) {
2279
+ if (draining || isKillSwitchSet(env)) break;
2280
+ const stillQueued = readStateFile(teamRoot).requests.some((entry) =>
2281
+ sameRequest(entry, request),
2282
+ );
2283
+ if (!stillQueued) continue;
2284
+ fire(jobsById.get(request.jobId), 'manual', nowIso, request);
2285
+ }
2286
+
2287
+ for (const job of file.jobs) {
2288
+ if (draining || isKillSwitchSet(env)) break;
2289
+ if (!job.enabled) continue;
2290
+ const current = readStateFile(teamRoot);
2291
+ const lastFireRaw = current.lastFireAt[job.id];
2292
+ const lastFire = lastFireRaw === undefined ? null : Date.parse(lastFireRaw);
2293
+ const instants = jobDueInstants(job, Number.isNaN(lastFire) ? null : lastFire, now, tickMs);
2294
+ if (instants.length === 0) continue;
2295
+ const policy = job.misfire;
2296
+ const missed = instants.length;
2297
+ const lastInstant = new Date(instants[instants.length - 1]).toISOString();
2298
+ if (policy === 'skip') {
2299
+ updateState((fresh) => {
2300
+ fresh.lastFireAt[job.id] = lastInstant;
2301
+ });
2302
+ continue;
2303
+ }
2304
+ if (policy === 'run-once') {
2305
+ fire(job, missed > 1 ? 'catch-up' : 'schedule', lastInstant);
2306
+ continue;
2307
+ }
2308
+ // catch-up: five occurrences per gap. More than five behind the gap is a
2309
+ // truncation: the bound replays once and the rest is dropped with the
2310
+ // truncation recorded, instead of replaying five more on the next tick.
2311
+ const truncated = instants.length > MAX_CATCH_UP;
2312
+ const replay = instants.slice(0, MAX_CATCH_UP);
2313
+ const note = truncated ? { dueAtLeast: instants.length } : null;
2314
+ let fired = 0;
2315
+ for (const instant of replay) {
2316
+ if (draining || isKillSwitchSet(env)) break;
2317
+ if (fire(job, 'catch-up', new Date(instant).toISOString(), null, fired === 0 ? note : null)) {
2318
+ fired += 1;
2319
+ }
2320
+ }
2321
+ if (truncated && fired === MAX_CATCH_UP) {
2322
+ updateState((fresh) => {
2323
+ fresh.lastFireAt[job.id] = nowIso;
2324
+ });
2325
+ }
2326
+ }
2327
+ heartbeat();
2328
+ };
2329
+
2330
+ await tick();
2331
+ while (!once && !draining) {
2332
+ if (isKillSwitchSet(env)) {
2333
+ draining = true;
2334
+ break;
2335
+ }
2336
+ await sleep(tickMs);
2337
+ await tick();
2338
+ }
2339
+
2340
+ if (draining) {
2341
+ // N-5: the in-flight child finishes inside its own timeout; nothing new
2342
+ // is claimed and no projection write follows the observation.
2343
+ await Promise.race([Promise.allSettled([...inFlight]), sleep(drainMs)]);
2344
+ if (!options.quiet) out('schedule: drained on the kill switch\n');
2345
+ }
2346
+ // A claimed run must never outlive this process unrecorded: `--once` and a
2347
+ // drained shutdown both wait for their children.
2348
+ await Promise.allSettled([...inFlight]);
2349
+ return 0;
2350
+ } finally {
2351
+ try {
2352
+ handle.db.close();
2353
+ } catch {
2354
+ /* a close error after a settled loop is not a scheduler failure */
2355
+ }
2356
+ releaseLease(teamRoot, process.pid);
2357
+ }
2358
+ }
2359
+
2360
+ export { writeLease, releaseLease, emptyState, pruneRunDirectories, pruneRunStore };