@bonesofspring/ai-rules 0.2.63 → 0.2.64

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 (288) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +10 -3
  3. package/bin/cli.js +7 -5
  4. package/bin/lib/ai-local-drift.js +7 -6
  5. package/bin/lib/engine-scripts.js +4 -0
  6. package/bin/lib/engine-upgrade.js +10 -2
  7. package/bin/lib/manifest-schema.js +12 -0
  8. package/bin/lib/seed-ai-local-team.js +13 -0
  9. package/bin/mavis-install.js +4 -3
  10. package/bin/opencode-install.js +22 -6
  11. package/bin/zcode-install.js +4 -3
  12. package/docs/MCP-CATALOG.md +1 -1
  13. package/docs/OPENCODE-COMPATIBILITY.md +3 -2
  14. package/docs/OPENCODE.md +22 -2
  15. package/docs/PRESET-CONTRIBUTION.md +2 -2
  16. package/docs/TEAM-DB.md +71 -4
  17. package/docs/openapi/team-db.v1.json +4817 -2795
  18. package/mcp/defectdojo-mcp.mjs +41 -11
  19. package/mcp/lib/defectdojo.mjs +45 -2
  20. package/package.json +8 -2
  21. package/presets/_shared/ai-local/scripts/aggregate-agent-task-metrics.mjs +279 -0
  22. package/presets/_shared/ai-local/scripts/team-db-api.mjs +471 -7
  23. package/presets/_shared/ai-local/scripts/team-db-backlog.mjs +1366 -0
  24. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +573 -7
  25. package/presets/_shared/ai-local/scripts/team-db-project.mjs +288 -4
  26. package/presets/_shared/ai-local/scripts/team-db-scheduler.mjs +82 -10
  27. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +83 -0
  28. package/presets/_shared/ai-local/scripts/team-db.mjs +69 -6
  29. package/presets/_shared/ai-local/scripts/upstream-research.mjs +3 -0
  30. package/presets/_shared/core/agent-team/agent-task-metrics.md +7 -2
  31. package/presets/_shared/core/agent-team/agent-team-orchestrator.md +1 -0
  32. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +225 -0
  33. package/presets/_shared/hooks/run-hook.mjs +2 -1
  34. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +225 -0
  35. package/presets/claude/android-kotlin/hooks/run-hook.mjs +2 -1
  36. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  37. package/presets/claude/go/hooks/chain-team-phases.sh +225 -0
  38. package/presets/claude/go/hooks/run-hook.mjs +2 -1
  39. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  40. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +225 -0
  41. package/presets/claude/ios-swift/hooks/run-hook.mjs +2 -1
  42. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  43. package/presets/claude/java/hooks/chain-team-phases.sh +225 -0
  44. package/presets/claude/java/hooks/run-hook.mjs +2 -1
  45. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  46. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +225 -0
  47. package/presets/claude/mcp-ts/hooks/run-hook.mjs +2 -1
  48. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  49. package/presets/claude/mol/hooks/chain-team-phases.sh +225 -0
  50. package/presets/claude/mol/hooks/run-hook.mjs +2 -1
  51. package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  52. package/presets/claude/next/agents/code-reviewer.md +1 -0
  53. package/presets/claude/next/agents/mockup-reviewer.md +2 -1
  54. package/presets/claude/next/agents/task-analyst.md +2 -0
  55. package/presets/claude/next/commands/task.md +7 -1
  56. package/presets/claude/next/commands/technical-retro.md +7 -1
  57. package/presets/claude/next/commands/upstream-research.md +1 -1
  58. package/presets/claude/next/hooks/chain-team-phases.sh +225 -0
  59. package/presets/claude/next/hooks/run-hook.mjs +2 -1
  60. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  61. package/presets/claude/next/skills/figma-fidelity/SKILL.md +4 -1
  62. package/presets/claude/next/skills/mockup-review/SKILL.md +4 -0
  63. package/presets/claude/next/team/README.md +5 -1
  64. package/presets/claude/next/team/upstream/jobs.json +34 -0
  65. package/presets/claude/nuxt/hooks/chain-team-phases.sh +225 -0
  66. package/presets/claude/nuxt/hooks/run-hook.mjs +2 -1
  67. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  68. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +225 -0
  69. package/presets/claude/php-hexagonal/hooks/run-hook.mjs +2 -1
  70. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  71. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +225 -0
  72. package/presets/claude/php-laravel/hooks/run-hook.mjs +2 -1
  73. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  74. package/presets/claude/svelte/hooks/chain-team-phases.sh +225 -0
  75. package/presets/claude/svelte/hooks/run-hook.mjs +2 -1
  76. package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  77. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +225 -0
  78. package/presets/cursor/android-kotlin/hooks/run-hook.mjs +2 -1
  79. package/presets/cursor/go/hooks/chain-team-phases.sh +225 -0
  80. package/presets/cursor/go/hooks/run-hook.mjs +2 -1
  81. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +225 -0
  82. package/presets/cursor/ios-swift/hooks/run-hook.mjs +2 -1
  83. package/presets/cursor/java/hooks/chain-team-phases.sh +225 -0
  84. package/presets/cursor/java/hooks/run-hook.mjs +2 -1
  85. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +225 -0
  86. package/presets/cursor/mcp-ts/hooks/run-hook.mjs +2 -1
  87. package/presets/cursor/mol/hooks/chain-team-phases.sh +225 -0
  88. package/presets/cursor/mol/hooks/run-hook.mjs +2 -1
  89. package/presets/cursor/next/agents/code-reviewer.md +1 -0
  90. package/presets/cursor/next/agents/mockup-reviewer.md +2 -1
  91. package/presets/cursor/next/agents/task-analyst.md +2 -0
  92. package/presets/cursor/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -0
  93. package/presets/cursor/next/ai-local/rules-library/ui-change-review-gate.md +1 -0
  94. package/presets/cursor/next/commands/task.md +7 -1
  95. package/presets/cursor/next/commands/technical-retro.md +7 -1
  96. package/presets/cursor/next/commands/upstream-research.md +1 -1
  97. package/presets/cursor/next/hooks/chain-team-phases.sh +225 -0
  98. package/presets/cursor/next/hooks/run-hook.mjs +2 -1
  99. package/presets/cursor/next/skills/figma-fidelity/SKILL.md +4 -1
  100. package/presets/cursor/next/skills/mockup-review/SKILL.md +4 -0
  101. package/presets/cursor/next/team/README.md +5 -1
  102. package/presets/cursor/next/team/upstream/jobs.json +34 -0
  103. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +225 -0
  104. package/presets/cursor/nuxt/hooks/run-hook.mjs +2 -1
  105. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +225 -0
  106. package/presets/cursor/php-hexagonal/hooks/run-hook.mjs +2 -1
  107. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +225 -0
  108. package/presets/cursor/php-laravel/hooks/run-hook.mjs +2 -1
  109. package/presets/cursor/svelte/hooks/chain-team-phases.sh +225 -0
  110. package/presets/cursor/svelte/hooks/run-hook.mjs +2 -1
  111. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  112. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +225 -0
  113. package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +1 -0
  114. package/presets/mavis/go/adapter-map.json +1 -1
  115. package/presets/mavis/go/hooks/chain-team-phases.sh +225 -0
  116. package/presets/mavis/go/rules/agent-team-orchestrator.md +1 -0
  117. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  118. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +225 -0
  119. package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +1 -0
  120. package/presets/mavis/java/adapter-map.json +1 -1
  121. package/presets/mavis/java/hooks/chain-team-phases.sh +225 -0
  122. package/presets/mavis/java/rules/agent-team-orchestrator.md +1 -0
  123. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  124. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +225 -0
  125. package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +1 -0
  126. package/presets/mavis/mol/adapter-map.json +1 -1
  127. package/presets/mavis/mol/hooks/chain-team-phases.sh +225 -0
  128. package/presets/mavis/mol/rules/agent-team-orchestrator.md +1 -0
  129. package/presets/mavis/next/adapter-map.json +9 -1
  130. package/presets/mavis/next/agents/code-reviewer.md +1 -0
  131. package/presets/mavis/next/agents/mockup-reviewer.md +2 -1
  132. package/presets/mavis/next/agents/task-analyst.md +2 -0
  133. package/presets/mavis/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -0
  134. package/presets/mavis/next/ai-local/rules-library/ui-change-review-gate.md +1 -0
  135. package/presets/mavis/next/commands/task.md +7 -1
  136. package/presets/mavis/next/commands/technical-retro.md +7 -1
  137. package/presets/mavis/next/commands/upstream-research.md +1 -1
  138. package/presets/mavis/next/hooks/chain-team-phases.sh +225 -0
  139. package/presets/mavis/next/rules/agent-team-orchestrator.md +1 -0
  140. package/presets/mavis/next/skills/figma-fidelity/SKILL.md +4 -1
  141. package/presets/mavis/next/skills/mockup-review/SKILL.md +4 -0
  142. package/presets/mavis/next/team/README.md +5 -1
  143. package/presets/mavis/next/team/upstream/jobs.json +34 -0
  144. package/presets/mavis/nuxt/adapter-map.json +1 -1
  145. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +225 -0
  146. package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +1 -0
  147. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  148. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +225 -0
  149. package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +1 -0
  150. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  151. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +225 -0
  152. package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +1 -0
  153. package/presets/mavis/svelte/adapter-map.json +1 -1
  154. package/presets/mavis/svelte/hooks/chain-team-phases.sh +225 -0
  155. package/presets/mavis/svelte/rules/agent-team-orchestrator.md +1 -0
  156. package/presets/opencode/android-kotlin/OPENCODE.md +4 -1
  157. package/presets/opencode/android-kotlin/README.md +1 -0
  158. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  159. package/presets/opencode/android-kotlin/hooks/README.md +4 -2
  160. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +225 -0
  161. package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +1 -0
  162. package/presets/opencode/go/OPENCODE.md +4 -1
  163. package/presets/opencode/go/README.md +1 -0
  164. package/presets/opencode/go/adapter-map.json +1 -1
  165. package/presets/opencode/go/hooks/README.md +4 -2
  166. package/presets/opencode/go/hooks/chain-team-phases.sh +225 -0
  167. package/presets/opencode/go/rules/agent-team-orchestrator.md +1 -0
  168. package/presets/opencode/ios-swift/OPENCODE.md +4 -1
  169. package/presets/opencode/ios-swift/README.md +1 -0
  170. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  171. package/presets/opencode/ios-swift/hooks/README.md +4 -2
  172. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +225 -0
  173. package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +1 -0
  174. package/presets/opencode/java/OPENCODE.md +4 -1
  175. package/presets/opencode/java/README.md +1 -0
  176. package/presets/opencode/java/adapter-map.json +1 -1
  177. package/presets/opencode/java/hooks/README.md +4 -2
  178. package/presets/opencode/java/hooks/chain-team-phases.sh +225 -0
  179. package/presets/opencode/java/rules/agent-team-orchestrator.md +1 -0
  180. package/presets/opencode/mcp-ts/OPENCODE.md +4 -1
  181. package/presets/opencode/mcp-ts/README.md +1 -0
  182. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  183. package/presets/opencode/mcp-ts/hooks/README.md +4 -2
  184. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +225 -0
  185. package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +1 -0
  186. package/presets/opencode/mol/OPENCODE.md +4 -1
  187. package/presets/opencode/mol/README.md +1 -0
  188. package/presets/opencode/mol/adapter-map.json +1 -1
  189. package/presets/opencode/mol/hooks/README.md +4 -2
  190. package/presets/opencode/mol/hooks/chain-team-phases.sh +225 -0
  191. package/presets/opencode/mol/rules/agent-team-orchestrator.md +1 -0
  192. package/presets/opencode/next/OPENCODE.md +4 -1
  193. package/presets/opencode/next/README.md +1 -0
  194. package/presets/opencode/next/adapter-map.json +9 -1
  195. package/presets/opencode/next/agents/code-reviewer.md +1 -0
  196. package/presets/opencode/next/agents/mockup-reviewer.md +2 -1
  197. package/presets/opencode/next/agents/task-analyst.md +2 -0
  198. package/presets/opencode/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -0
  199. package/presets/opencode/next/ai-local/rules-library/ui-change-review-gate.md +1 -0
  200. package/presets/opencode/next/commands/task.md +7 -1
  201. package/presets/opencode/next/commands/technical-retro.md +7 -1
  202. package/presets/opencode/next/commands/upstream-research.md +1 -1
  203. package/presets/opencode/next/hooks/README.md +4 -2
  204. package/presets/opencode/next/hooks/chain-team-phases.sh +225 -0
  205. package/presets/opencode/next/rules/agent-team-orchestrator.md +1 -0
  206. package/presets/opencode/next/skills/figma-fidelity/SKILL.md +4 -1
  207. package/presets/opencode/next/skills/mockup-review/SKILL.md +4 -0
  208. package/presets/opencode/next/team/README.md +5 -1
  209. package/presets/opencode/next/team/upstream/jobs.json +34 -0
  210. package/presets/opencode/nuxt/OPENCODE.md +4 -1
  211. package/presets/opencode/nuxt/README.md +1 -0
  212. package/presets/opencode/nuxt/adapter-map.json +1 -1
  213. package/presets/opencode/nuxt/hooks/README.md +4 -2
  214. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +225 -0
  215. package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +1 -0
  216. package/presets/opencode/php-hexagonal/OPENCODE.md +4 -1
  217. package/presets/opencode/php-hexagonal/README.md +1 -0
  218. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  219. package/presets/opencode/php-hexagonal/hooks/README.md +4 -2
  220. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +225 -0
  221. package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +1 -0
  222. package/presets/opencode/php-laravel/OPENCODE.md +4 -1
  223. package/presets/opencode/php-laravel/README.md +1 -0
  224. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  225. package/presets/opencode/php-laravel/hooks/README.md +4 -2
  226. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +225 -0
  227. package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +1 -0
  228. package/presets/opencode/platform-contract.json +6 -0
  229. package/presets/opencode/plugins/task-status/README.md +92 -0
  230. package/presets/opencode/plugins/task-status/details-data.ts +130 -0
  231. package/presets/opencode/plugins/task-status/details.tsx +84 -0
  232. package/presets/opencode/plugins/task-status/eta.ts +230 -0
  233. package/presets/opencode/plugins/task-status/index.ts +6 -0
  234. package/presets/opencode/plugins/task-status/package.json +10 -0
  235. package/presets/opencode/plugins/task-status/task-view.ts +606 -0
  236. package/presets/opencode/plugins/task-status/tui.tsx +139 -0
  237. package/presets/opencode/svelte/OPENCODE.md +4 -1
  238. package/presets/opencode/svelte/README.md +1 -0
  239. package/presets/opencode/svelte/adapter-map.json +1 -1
  240. package/presets/opencode/svelte/hooks/README.md +4 -2
  241. package/presets/opencode/svelte/hooks/chain-team-phases.sh +225 -0
  242. package/presets/opencode/svelte/rules/agent-team-orchestrator.md +1 -0
  243. package/presets/zcode/android-kotlin/adapter-map.json +1 -1
  244. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +225 -0
  245. package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +1 -0
  246. package/presets/zcode/go/adapter-map.json +1 -1
  247. package/presets/zcode/go/hooks/chain-team-phases.sh +225 -0
  248. package/presets/zcode/go/rules/agent-team-orchestrator.md +1 -0
  249. package/presets/zcode/ios-swift/adapter-map.json +1 -1
  250. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +225 -0
  251. package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +1 -0
  252. package/presets/zcode/java/adapter-map.json +1 -1
  253. package/presets/zcode/java/hooks/chain-team-phases.sh +225 -0
  254. package/presets/zcode/java/rules/agent-team-orchestrator.md +1 -0
  255. package/presets/zcode/mcp-ts/adapter-map.json +1 -1
  256. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +225 -0
  257. package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +1 -0
  258. package/presets/zcode/mol/adapter-map.json +1 -1
  259. package/presets/zcode/mol/hooks/chain-team-phases.sh +225 -0
  260. package/presets/zcode/mol/rules/agent-team-orchestrator.md +1 -0
  261. package/presets/zcode/next/adapter-map.json +9 -1
  262. package/presets/zcode/next/agents/code-reviewer.md +1 -0
  263. package/presets/zcode/next/agents/mockup-reviewer.md +2 -1
  264. package/presets/zcode/next/agents/task-analyst.md +2 -0
  265. package/presets/zcode/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -0
  266. package/presets/zcode/next/ai-local/rules-library/ui-change-review-gate.md +1 -0
  267. package/presets/zcode/next/commands/task.md +7 -1
  268. package/presets/zcode/next/commands/technical-retro.md +7 -1
  269. package/presets/zcode/next/commands/upstream-research.md +1 -1
  270. package/presets/zcode/next/hooks/chain-team-phases.sh +225 -0
  271. package/presets/zcode/next/rules/agent-team-orchestrator.md +1 -0
  272. package/presets/zcode/next/skills/figma-fidelity/SKILL.md +4 -1
  273. package/presets/zcode/next/skills/mockup-review/SKILL.md +4 -0
  274. package/presets/zcode/next/team/README.md +5 -1
  275. package/presets/zcode/next/team/upstream/jobs.json +34 -0
  276. package/presets/zcode/nuxt/adapter-map.json +1 -1
  277. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +225 -0
  278. package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +1 -0
  279. package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
  280. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +225 -0
  281. package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +1 -0
  282. package/presets/zcode/php-laravel/adapter-map.json +1 -1
  283. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +225 -0
  284. package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +1 -0
  285. package/presets/zcode/svelte/adapter-map.json +1 -1
  286. package/presets/zcode/svelte/hooks/chain-team-phases.sh +225 -0
  287. package/presets/zcode/svelte/rules/agent-team-orchestrator.md +1 -0
  288. package/scripts/aggregate-agent-task-metrics.mjs +48 -4
@@ -3,11 +3,11 @@
3
3
  *
4
4
  * `node:http` only. The surface is loopback-only by default, sends no CORS
5
5
  * header, and reads files through SQLite rows (never through a request path).
6
- * The six mutating operations — the idempotent rescan, the confirmed task
7
- * delete, and the four job writes (create, update, delete, run-now) — each run
8
- * one bounded child process; the server itself never opens a writable
9
- * connection and the kill switch stops every mutation before a child is
10
- * spawned.
6
+ * The ten mutating operations — the idempotent rescan, the confirmed task
7
+ * delete, the four job writes (create, update, delete, run-now), and the four
8
+ * backlog writes (item create, item update, enqueue, cancel) — each run one
9
+ * bounded child process; the server itself never opens a writable connection
10
+ * and the kill switch stops every mutation before a child is spawned.
11
11
  *
12
12
  * Every SQL statement in this module is a static string with bound parameters.
13
13
  * The only interpolated fragments are the module-level constants `TASK_FILTER`,
@@ -60,6 +60,15 @@ import {
60
60
  readLogChunk,
61
61
  readStateFile,
62
62
  } from './team-db-scheduler.mjs';
63
+ import {
64
+ EFFECTIVE_ENTRY_STATUSES,
65
+ EFFECTIVE_ITEM_STATUSES,
66
+ countActiveTasks,
67
+ deriveBacklogOrdering,
68
+ effectiveEntryStatus,
69
+ rankCompare,
70
+ readBacklogConfig,
71
+ } from './team-db-backlog.mjs';
63
72
 
64
73
  export const DEFAULT_HOST = '127.0.0.1';
65
74
  export const DEFAULT_PORT = 4178;
@@ -76,6 +85,11 @@ export const JOB_BODY_MAX = 65536;
76
85
  export const JOB_WRITE_CHILD_TIMEOUT_MS = 10000;
77
86
  export const JOB_DELETE_CHILD_TIMEOUT_MS = 30000;
78
87
  export const JOB_RUN_CHILD_TIMEOUT_MS = 10000;
88
+ export const BACKLOG_ITEM_BODY_MAX = 16384;
89
+ export const BACKLOG_QUEUE_BODY_MAX = 1024;
90
+ export const BACKLOG_WRITE_CHILD_TIMEOUT_MS = 10000;
91
+ export const BACKLOG_DEFAULT_LIMIT = 50;
92
+ export const BACKLOG_MAX_LIMIT = 200;
79
93
  export const SCHEDULER_HINT = 'start team-db.mjs schedule';
80
94
  export const LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '::1'];
81
95
  const CLIENT_HEADERS = {
@@ -96,6 +110,8 @@ const TASK_STATE_SET = new Set(TASK_STATES);
96
110
  const PROFILE_SET = new Set(PROFILES);
97
111
  const EVENT_TYPE_SET = new Set(EVENT_TYPES);
98
112
  const OUTCOME_VALUES = new Set(['completed', 'blocked', 'changes_requested', 'validation_failed', 'skipped']);
113
+ const BACKLOG_EFFECTIVE_SET = new Set(EFFECTIVE_ITEM_STATUSES);
114
+ const BACKLOG_EFFECTIVE_ENTRY_SET = new Set(EFFECTIVE_ENTRY_STATUSES);
99
115
  const CODE_STATUS_ROWS = [
100
116
  ['E_BAD_REQUEST', 400],
101
117
  ['E_FORBIDDEN_HOST', 403],
@@ -316,6 +332,20 @@ const SQL = {
316
332
  SELECT DISTINCT slug FROM tasks
317
333
  WHERE slug LIKE ?1 ESCAPE '\\' OR title LIKE ?1 ESCAPE '\\'
318
334
  LIMIT ?2`,
335
+ // The backlog read plane: projected rows only, a broken row (parse_error)
336
+ // is recorded in the projection but never served, mirroring the CLI path
337
+ // which records the error and drops the record from the snapshot.
338
+ listBacklogItems: `SELECT * FROM backlog_items
339
+ WHERE absent_at IS NULL AND parse_error IS NULL ORDER BY id`,
340
+ getBacklogItem: 'SELECT * FROM backlog_items WHERE id = ?1 AND absent_at IS NULL AND parse_error IS NULL',
341
+ listBacklogDeps: 'SELECT item_id, dep_id FROM backlog_item_deps ORDER BY item_id, ordinal',
342
+ listBacklogEntries: `SELECT * FROM backlog_queue
343
+ WHERE absent_at IS NULL AND parse_error IS NULL ORDER BY entry_id`,
344
+ getBacklogEntry: 'SELECT * FROM backlog_queue WHERE entry_id = ?1 AND absent_at IS NULL AND parse_error IS NULL',
345
+ listBacklogEntriesForItem: `SELECT * FROM backlog_queue
346
+ WHERE item_id = ?1 AND absent_at IS NULL AND parse_error IS NULL ORDER BY entry_id`,
347
+ listBacklogTaskRows: 'SELECT slug, state, start_at, end_at FROM tasks WHERE absent_at IS NULL',
348
+ getBacklogTaskRow: 'SELECT state, start_at, end_at FROM tasks WHERE slug = ?1 AND absent_at IS NULL',
319
349
  };
320
350
 
321
351
  /* ------------------------------- validation -------------------------------- */
@@ -953,7 +983,7 @@ const getHealth = (handle, settings) => {
953
983
  },
954
984
  tasks: { total: Number(totals.total), absent: Number(totals.absent) },
955
985
  projectedAt: totals.projected_at ?? null,
956
- capabilities: ['sync', 'delete', 'jobs', 'schedule'],
986
+ capabilities: ['sync', 'delete', 'jobs', 'schedule', 'backlog'],
957
987
  scheduler: {
958
988
  state: lease.state,
959
989
  pid: lease.lease?.pid === undefined ? null : Number(lease.lease.pid),
@@ -1403,6 +1433,410 @@ const runDeleteChild = async (slug, context) => {
1403
1433
  return { slug: parsed.slug };
1404
1434
  };
1405
1435
 
1436
+ /* --------------------------------- backlog -------------------------------- */
1437
+
1438
+ const parseJsonArrayColumn = (text) => {
1439
+ try {
1440
+ const parsed = JSON.parse(text ?? '[]');
1441
+ return Array.isArray(parsed) ? parsed : [];
1442
+ } catch {
1443
+ return [];
1444
+ }
1445
+ };
1446
+
1447
+ /** A projected row back into the file shape the shared ordering consumes. */
1448
+ const backlogItemFromRow = (row, dependsOn) => ({
1449
+ schemaVersion: 1,
1450
+ id: row.id,
1451
+ revision: Number.isInteger(row.revision) ? row.revision : 1,
1452
+ title: row.title ?? '',
1453
+ status: row.status ?? 'planned',
1454
+ priority: Number.isInteger(row.priority) ? row.priority : 5,
1455
+ type: row.type ?? 'feature',
1456
+ description: row.description ?? null,
1457
+ labels: parseJsonArrayColumn(row.labels_json),
1458
+ history: parseJsonArrayColumn(row.history_json),
1459
+ dependsOn,
1460
+ sourceTask: row.source_task ?? null,
1461
+ sourceRefs: parseJsonArrayColumn(row.source_refs_json),
1462
+ createdAt: row.created_at ?? '1970-01-01T00:00:00.000Z',
1463
+ updatedAt: row.updated_at ?? '1970-01-01T00:00:00.000Z',
1464
+ completedAt: row.completed_at ?? null,
1465
+ cancelledAt: row.cancelled_at ?? null,
1466
+ cancelReason: row.cancel_reason ?? null,
1467
+ supersededBy: row.superseded_by ?? null,
1468
+ });
1469
+
1470
+ const backlogEntryFromRow = (row) => ({
1471
+ schemaVersion: 1,
1472
+ entryId: row.entry_id,
1473
+ itemId: row.item_id,
1474
+ status: row.status ?? 'queued',
1475
+ reason: row.reason ?? '',
1476
+ requestedBy: row.requested_by ?? '',
1477
+ command: row.command ?? null,
1478
+ revision: Number.isInteger(row.revision) ? row.revision : 1,
1479
+ requestedAt: row.requested_at ?? '1970-01-01T00:00:00.000Z',
1480
+ claimedAt: row.claimed_at ?? null,
1481
+ finishedAt: row.finished_at ?? null,
1482
+ history: parseJsonArrayColumn(row.history_json),
1483
+ });
1484
+
1485
+ /**
1486
+ * One snapshot of the projected backlog. The record shapes are the files'
1487
+ * own, so the shared `deriveBacklogOrdering` sees the same input on the CLI
1488
+ * path and the SQL read plane and the two can never disagree (D-4).
1489
+ */
1490
+ const readBacklogSnapshotRows = (db) => {
1491
+ const items = new Map();
1492
+ const entries = new Map();
1493
+ const taskRows = new Map();
1494
+ for (const row of db.prepare(SQL.listBacklogTaskRows).all()) {
1495
+ taskRows.set(row.slug, { state: row.state ?? null, startAt: row.start_at ?? null, endAt: row.end_at ?? null });
1496
+ }
1497
+ const depsByItem = new Map();
1498
+ for (const dep of db.prepare(SQL.listBacklogDeps).all()) {
1499
+ if (!depsByItem.has(dep.item_id)) depsByItem.set(dep.item_id, []);
1500
+ depsByItem.get(dep.item_id).push(dep.dep_id);
1501
+ }
1502
+ for (const row of db.prepare(SQL.listBacklogItems).all()) {
1503
+ items.set(row.id, backlogItemFromRow(row, depsByItem.get(row.id) ?? []));
1504
+ }
1505
+ for (const row of db.prepare(SQL.listBacklogEntries).all()) {
1506
+ entries.set(row.entry_id, backlogEntryFromRow(row));
1507
+ }
1508
+ const taskStates = new Map();
1509
+ for (const [slug, row] of taskRows) taskStates.set(slug, row.state);
1510
+ return { items, entries, taskRows, taskStates };
1511
+ };
1512
+
1513
+ const backlogItemJson = (annotated) => {
1514
+ const item = annotated.item;
1515
+ return {
1516
+ schemaVersion: 1,
1517
+ id: item.id,
1518
+ revision: item.revision,
1519
+ title: item.title,
1520
+ status: item.status,
1521
+ priority: item.priority,
1522
+ type: item.type,
1523
+ description: item.description,
1524
+ labels: item.labels,
1525
+ history: item.history,
1526
+ dependsOn: item.dependsOn,
1527
+ sourceTask: item.sourceTask,
1528
+ sourceRefs: item.sourceRefs,
1529
+ createdAt: item.createdAt,
1530
+ updatedAt: item.updatedAt,
1531
+ completedAt: item.completedAt,
1532
+ cancelledAt: item.cancelledAt,
1533
+ cancelReason: item.cancelReason,
1534
+ supersededBy: item.supersededBy,
1535
+ effectiveStatus: annotated.effectiveStatus,
1536
+ taskState: annotated.taskState,
1537
+ ready: annotated.ready,
1538
+ waitingOn: annotated.waitingOn,
1539
+ queueEntryId: annotated.queueEntryId,
1540
+ queuedAt: annotated.queuedAt,
1541
+ };
1542
+ };
1543
+
1544
+ const backlogItemSummaryJson = (annotated) => {
1545
+ const item = annotated.item;
1546
+ return {
1547
+ id: item.id,
1548
+ title: item.title,
1549
+ status: item.status,
1550
+ effectiveStatus: annotated.effectiveStatus,
1551
+ priority: item.priority,
1552
+ type: item.type,
1553
+ description: item.description,
1554
+ labels: item.labels,
1555
+ dependsOn: item.dependsOn,
1556
+ waitingOn: annotated.waitingOn,
1557
+ ready: annotated.ready,
1558
+ sourceTask: item.sourceTask,
1559
+ sourceRefs: item.sourceRefs,
1560
+ taskState: annotated.taskState,
1561
+ createdAt: item.createdAt,
1562
+ updatedAt: item.updatedAt,
1563
+ queueEntryId: annotated.queueEntryId,
1564
+ };
1565
+ };
1566
+
1567
+ const backlogQueueEntryJson = (entry, taskRows, itemTitle) => {
1568
+ const taskRow = taskRows.get(entry.itemId);
1569
+ const taskState = taskRow?.state ?? null;
1570
+ return {
1571
+ entryId: entry.entryId,
1572
+ itemId: entry.itemId,
1573
+ status: effectiveEntryStatus(entry, taskState),
1574
+ reason: entry.reason,
1575
+ requestedBy: entry.requestedBy,
1576
+ command: entry.command,
1577
+ revision: entry.revision,
1578
+ requestedAt: entry.requestedAt,
1579
+ claimedAt: entry.claimedAt,
1580
+ finishedAt: entry.finishedAt,
1581
+ history: entry.history,
1582
+ itemTitle,
1583
+ taskState,
1584
+ taskStartAt: taskRow?.startAt ?? null,
1585
+ taskEndAt: taskRow?.endAt ?? null,
1586
+ };
1587
+ };
1588
+
1589
+ const backlogOrdering = (db) => {
1590
+ const snapshot = readBacklogSnapshotRows(db);
1591
+ const asOf = new Date().toISOString();
1592
+ const ordering = deriveBacklogOrdering({ ...snapshot, asOf });
1593
+ return { snapshot, ordering, asOf };
1594
+ };
1595
+
1596
+ const listBacklogItems = (db, query, settings) => {
1597
+ const limit = parseInteger(query.get('limit'), 'limit', { min: 1, max: BACKLOG_MAX_LIMIT, fallback: BACKLOG_DEFAULT_LIMIT });
1598
+ const offset = parseInteger(query.get('offset'), 'offset', { min: 0, max: MAX_OFFSET, fallback: 0 });
1599
+ const statuses = parseCsv(query.get('status'), 'status', BACKLOG_EFFECTIVE_SET);
1600
+ const ready = parseBoolean(query.get('ready'), 'ready', null);
1601
+ const sourceTask = parsePattern(query.get('sourceTask'), 'sourceTask', slugPattern, 64);
1602
+ const { snapshot, ordering, asOf } = backlogOrdering(db);
1603
+ let ranked = [...ordering.byId.values()].sort((left, right) => rankCompare(left.item, right.item));
1604
+ if (statuses.length > 0) ranked = ranked.filter((annotated) => statuses.includes(annotated.effectiveStatus));
1605
+ if (ready !== null) ranked = ranked.filter((annotated) => annotated.ready === ready);
1606
+ if (sourceTask !== '') ranked = ranked.filter((annotated) => annotated.item.sourceTask === sourceTask);
1607
+ const total = ranked.length;
1608
+ const items = ranked.slice(offset, offset + limit).map(backlogItemSummaryJson);
1609
+ return {
1610
+ items,
1611
+ total,
1612
+ limit,
1613
+ offset,
1614
+ nextOffset: offset + items.length < total ? offset + items.length : null,
1615
+ asOf,
1616
+ readyCount: ordering.readyIds.length,
1617
+ criticalPathIds: ordering.criticalPathIds,
1618
+ maxActive: readBacklogConfig(settings.teamRoot).maxActive,
1619
+ activeCount: countActiveTasks(snapshot.taskStates),
1620
+ };
1621
+ };
1622
+
1623
+ const backlogItemDetail = (db, id) => {
1624
+ const { snapshot, ordering } = backlogOrdering(db);
1625
+ const annotated = ordering.byId.get(id);
1626
+ if (!annotated) fail('E_NOT_FOUND', 404, `no backlog item "${id}"`);
1627
+ const dependencies = (annotated.item.dependsOn ?? []).map((depId) => {
1628
+ const dep = ordering.byId.get(depId);
1629
+ return {
1630
+ id: depId,
1631
+ title: dep?.item.title ?? depId,
1632
+ status: dep?.effectiveStatus ?? 'planned',
1633
+ satisfied: dep?.effectiveStatus === 'completed',
1634
+ };
1635
+ });
1636
+ const dependents = [...ordering.byId.values()]
1637
+ .filter((other) => (other.item.dependsOn ?? []).includes(id))
1638
+ .sort((left, right) => rankCompare(left.item, right.item))
1639
+ .map((other) => ({
1640
+ id: other.item.id,
1641
+ title: other.item.title,
1642
+ status: other.effectiveStatus,
1643
+ satisfied: annotated.effectiveStatus === 'completed',
1644
+ }));
1645
+ const queue = [...snapshot.entries.values()]
1646
+ .filter((entry) => entry.itemId === id)
1647
+ .map((entry) => backlogQueueEntryJson(entry, snapshot.taskRows, annotated.item.title));
1648
+ return {
1649
+ item: backlogItemJson(annotated),
1650
+ dependencies,
1651
+ dependents,
1652
+ queue,
1653
+ criticalPath: ordering.criticalPathIds,
1654
+ };
1655
+ };
1656
+
1657
+ const listBacklogQueue = (db, query) => {
1658
+ const limit = parseInteger(query.get('limit'), 'limit', { min: 1, max: BACKLOG_MAX_LIMIT, fallback: BACKLOG_DEFAULT_LIMIT });
1659
+ const offset = parseInteger(query.get('offset'), 'offset', { min: 0, max: MAX_OFFSET, fallback: 0 });
1660
+ const statuses = parseCsv(query.get('status'), 'status', BACKLOG_EFFECTIVE_ENTRY_SET);
1661
+ const itemId = parsePattern(query.get('itemId'), 'itemId', slugPattern, 64);
1662
+ const snapshot = readBacklogSnapshotRows(db);
1663
+ let items = [...snapshot.entries.values()]
1664
+ .filter((entry) => itemId === '' || entry.itemId === itemId)
1665
+ .map((entry) => backlogQueueEntryJson(entry, snapshot.taskRows, snapshot.items.get(entry.itemId)?.title ?? entry.itemId));
1666
+ if (statuses.length > 0) items = items.filter((entry) => statuses.includes(entry.status));
1667
+ const total = items.length;
1668
+ const pageItems = items.slice(offset, offset + limit);
1669
+ const activeEntryId = items.find((entry) => entry.status === 'active')?.entryId ?? null;
1670
+ return {
1671
+ items: pageItems,
1672
+ total,
1673
+ limit,
1674
+ offset,
1675
+ nextOffset: offset + pageItems.length < total ? offset + pageItems.length : null,
1676
+ asOf: new Date().toISOString(),
1677
+ activeEntryId,
1678
+ };
1679
+ };
1680
+
1681
+ const parseBacklogBody = (context, noun) => {
1682
+ const text = context.body.toString('utf8').trim();
1683
+ if (text === '') fail('E_VALIDATION', 422, `${noun} is required`, { parameter: 'body' });
1684
+ try {
1685
+ return JSON.parse(text);
1686
+ } catch {
1687
+ fail('E_VALIDATION', 422, `${noun} is not valid JSON`, { parameter: 'body' });
1688
+ }
1689
+ return null;
1690
+ };
1691
+
1692
+ const parseEntryId = (value) => {
1693
+ if (typeof value !== 'string' || !RUN_ID_RE.test(value)) {
1694
+ fail('E_VALIDATION', 422, 'the entry id has an invalid shape', { parameter: 'entryId' });
1695
+ }
1696
+ return value;
1697
+ };
1698
+
1699
+ /**
1700
+ * One child refusal back into the documented envelope. The CLI code travels in
1701
+ * `details.code` (additionalProperties); the transport code is per mutation
1702
+ * because the same CLI code means a different refusal on a different verb.
1703
+ */
1704
+ const failBacklogRefusal = (result, transportByCode) => {
1705
+ const code = typeof result.code === 'string' ? result.code : 'E_INTERNAL';
1706
+ const [transport, status] = transportByCode.get(code) ?? ['E_INTERNAL', 500];
1707
+ fail(transport, status, String(result.message ?? 'the backlog write was refused'), { code });
1708
+ };
1709
+
1710
+ const CREATE_ITEM_REFUSALS = new Map([
1711
+ ['E_BACKLOG_DUPLICATE_ID', ['E_CONFLICT', 409]],
1712
+ ['E_ID_COLLISION', ['E_VALIDATION', 422]],
1713
+ ['E_SCHEMA', ['E_VALIDATION', 422]],
1714
+ ['E_BACKLOG_UNKNOWN_DEP', ['E_VALIDATION', 422]],
1715
+ ['E_BACKLOG_CYCLE', ['E_VALIDATION', 422]],
1716
+ ['E_BACKLOG_SELF_DEP', ['E_VALIDATION', 422]],
1717
+ ['E_BACKLOG_BUSY', ['E_BUSY', 503]],
1718
+ ]);
1719
+
1720
+ const UPDATE_ITEM_REFUSALS = new Map([
1721
+ ['E_BACKLOG_REVISION', ['E_CONFLICT', 409]],
1722
+ ['E_BACKLOG_TRANSITION', ['E_CONFLICT', 409]],
1723
+ ['E_SCHEMA', ['E_VALIDATION', 422]],
1724
+ ['E_BACKLOG_UNKNOWN_DEP', ['E_VALIDATION', 422]],
1725
+ ['E_BACKLOG_CYCLE', ['E_VALIDATION', 422]],
1726
+ ['E_BACKLOG_SELF_DEP', ['E_VALIDATION', 422]],
1727
+ ['E_BACKLOG_BUSY', ['E_BUSY', 503]],
1728
+ ]);
1729
+
1730
+ const ENQUEUE_REFUSALS = new Map([
1731
+ ['E_BACKLOG_TRANSITION', ['E_CONFLICT', 409]],
1732
+ ['E_SCHEMA', ['E_VALIDATION', 422]],
1733
+ ['E_BACKLOG_UNKNOWN_DEP', ['E_VALIDATION', 422]],
1734
+ ['E_BACKLOG_BUSY', ['E_BUSY', 503]],
1735
+ ]);
1736
+
1737
+ const CANCEL_REFUSALS = new Map([
1738
+ ['E_BACKLOG_TRANSITION', ['E_CONFLICT', 409]],
1739
+ ['E_SCHEMA', ['E_VALIDATION', 422]],
1740
+ ['E_BACKLOG_UNKNOWN_DEP', ['E_NOT_FOUND', 404]],
1741
+ ['E_BACKLOG_BUSY', ['E_BUSY', 503]],
1742
+ ]);
1743
+
1744
+ const backlogQueueEntryById = (db, entryId) => {
1745
+ const row = db.prepare(SQL.getBacklogEntry).get(entryId);
1746
+ if (!row) fail('E_NOT_FOUND', 404, `no queue entry "${entryId}"`);
1747
+ const entry = backlogEntryFromRow(row);
1748
+ const taskRow = db.prepare(SQL.getBacklogTaskRow).get(entry.itemId);
1749
+ const item = db.prepare(SQL.getBacklogItem).get(entry.itemId);
1750
+ const taskRows = new Map();
1751
+ if (taskRow) {
1752
+ taskRows.set(entry.itemId, { state: taskRow.state ?? null, startAt: taskRow.start_at ?? null, endAt: taskRow.end_at ?? null });
1753
+ }
1754
+ return backlogQueueEntryJson(entry, taskRows, item?.title ?? entry.itemId);
1755
+ };
1756
+
1757
+ const createBacklogItem = async (context) => {
1758
+ const parsed = parseBacklogBody(context, 'an item body');
1759
+ const result = await runTeamDbChild(['backlog', 'add', '--file', '-'], {
1760
+ settings: context.settings,
1761
+ timeoutMs: BACKLOG_WRITE_CHILD_TIMEOUT_MS,
1762
+ input: JSON.stringify(parsed),
1763
+ label: 'backlog create',
1764
+ });
1765
+ if (result.ok !== true || typeof result.item?.id !== 'string') {
1766
+ failBacklogRefusal(result, CREATE_ITEM_REFUSALS);
1767
+ }
1768
+ return { json: backlogItemDetail(context.db(), result.item.id), status: 201 };
1769
+ };
1770
+
1771
+ const updateBacklogItem = async (context) => {
1772
+ const id = parseSlug(context.params.id);
1773
+ const parsed = parseBacklogBody(context, 'an item body');
1774
+ if (parsed && parsed.id !== undefined && parsed.id !== id) {
1775
+ fail('E_CONFLICT', 409, 'the body id differs from the path id; the id is immutable');
1776
+ }
1777
+ const db = context.db();
1778
+ if (!db.prepare(SQL.getBacklogItem).get(id)) fail('E_NOT_FOUND', 404, `no backlog item "${id}"`);
1779
+ // The frozen route table refuses an update while a live entry exists: the
1780
+ // launch request must be cancelled before the item it targets can change.
1781
+ const taskRow = db.prepare(SQL.getBacklogTaskRow).get(id);
1782
+ const taskState = taskRow?.state ?? null;
1783
+ const live = db
1784
+ .prepare(SQL.listBacklogEntriesForItem)
1785
+ .all(id)
1786
+ .map((row) => backlogEntryFromRow(row))
1787
+ .some((entry) => !['cancelled', 'expired', 'done'].includes(effectiveEntryStatus(entry, taskState)));
1788
+ if (live) fail('E_CONFLICT', 409, `item "${id}" has a live queue entry; cancel it first`);
1789
+ const result = await runTeamDbChild(['backlog', 'set', id, '--file', '-'], {
1790
+ settings: context.settings,
1791
+ timeoutMs: BACKLOG_WRITE_CHILD_TIMEOUT_MS,
1792
+ input: JSON.stringify(parsed),
1793
+ label: 'backlog update',
1794
+ });
1795
+ if (result.ok !== true || typeof result.item?.id !== 'string') {
1796
+ failBacklogRefusal(result, UPDATE_ITEM_REFUSALS);
1797
+ }
1798
+ return { json: backlogItemDetail(db, id) };
1799
+ };
1800
+
1801
+ const enqueueBacklogItem = async (context) => {
1802
+ const parsed = parseBacklogBody(context, 'an enqueue body');
1803
+ const itemId = parsed?.itemId;
1804
+ if (typeof itemId !== 'string' || !slugPattern.test(itemId)) {
1805
+ fail('E_VALIDATION', 422, 'itemId must match the slug grammar', { parameter: 'itemId' });
1806
+ }
1807
+ const db = context.db();
1808
+ if (!db.prepare(SQL.getBacklogItem).get(itemId)) fail('E_NOT_FOUND', 404, `no backlog item "${itemId}"`);
1809
+ const result = await runTeamDbChild(['backlog', 'enqueue', '--file', '-'], {
1810
+ settings: context.settings,
1811
+ timeoutMs: BACKLOG_WRITE_CHILD_TIMEOUT_MS,
1812
+ input: JSON.stringify(parsed),
1813
+ label: 'backlog enqueue',
1814
+ });
1815
+ if (result.ok !== true || typeof result.entry?.entryId !== 'string') {
1816
+ failBacklogRefusal(result, ENQUEUE_REFUSALS);
1817
+ }
1818
+ return { json: backlogQueueEntryById(db, result.entry.entryId), status: result.existing ? 200 : 201 };
1819
+ };
1820
+
1821
+ const cancelBacklogQueueEntry = async (context) => {
1822
+ const entryId = parseEntryId(context.params.entryId);
1823
+ const text = context.body.toString('utf8').trim();
1824
+ if (text !== '' && text !== '{}') {
1825
+ fail('E_VALIDATION', 422, 'the cancel accepts no request body', { parameter: 'body' });
1826
+ }
1827
+ const db = context.db();
1828
+ if (!db.prepare(SQL.getBacklogEntry).get(entryId)) fail('E_NOT_FOUND', 404, `no queue entry "${entryId}"`);
1829
+ const result = await runTeamDbChild(['backlog', 'cancel', entryId], {
1830
+ settings: context.settings,
1831
+ timeoutMs: BACKLOG_WRITE_CHILD_TIMEOUT_MS,
1832
+ label: 'backlog cancel',
1833
+ });
1834
+ if (result.ok !== true || typeof result.entry?.entryId !== 'string') {
1835
+ failBacklogRefusal(result, CANCEL_REFUSALS);
1836
+ }
1837
+ return { json: backlogQueueEntryById(db, entryId) };
1838
+ };
1839
+
1406
1840
  /* --------------------------------- routing -------------------------------- */
1407
1841
 
1408
1842
  const route = (method, routePath, operationId, handler, options = {}) => ({
@@ -1508,6 +1942,34 @@ export const ROUTES = [
1508
1942
  route('POST', '/api/v1/jobs/{id}/run', 'runJobNow', (context) => runJobNow(context), {
1509
1943
  bodyLimit: MAX_REQUEST_BODY_BYTES,
1510
1944
  }),
1945
+ // The backlog entries: `/api/v1/backlog/queue` sits before
1946
+ // `/api/v1/backlog/{id}` so the `{id}` pattern can never shadow the literal
1947
+ // `queue` segment — the same discipline that keeps `/api/v1/jobs/{id}` from
1948
+ // shadowing `/api/v1/jobs/{id}/runs`.
1949
+ route('GET', '/api/v1/backlog', 'listBacklogItems', (context) => ({
1950
+ json: listBacklogItems(context.db(), context.query, context.settings),
1951
+ })),
1952
+ route('POST', '/api/v1/backlog', 'createBacklogItem', (context) => createBacklogItem(context), {
1953
+ bodyLimit: BACKLOG_ITEM_BODY_MAX,
1954
+ requireJson: true,
1955
+ }),
1956
+ route('GET', '/api/v1/backlog/queue', 'listBacklogQueue', (context) => ({
1957
+ json: listBacklogQueue(context.db(), context.query),
1958
+ })),
1959
+ route('POST', '/api/v1/backlog/queue', 'enqueueBacklogItem', (context) => enqueueBacklogItem(context), {
1960
+ bodyLimit: BACKLOG_QUEUE_BODY_MAX,
1961
+ requireJson: true,
1962
+ }),
1963
+ route('POST', '/api/v1/backlog/queue/{entryId}/cancel', 'cancelBacklogQueueEntry', (context) => cancelBacklogQueueEntry(context), {
1964
+ bodyLimit: BACKLOG_QUEUE_BODY_MAX,
1965
+ }),
1966
+ route('GET', '/api/v1/backlog/{id}', 'getBacklogItem', (context) => ({
1967
+ json: backlogItemDetail(context.db(), parseSlug(context.params.id)),
1968
+ })),
1969
+ route('PUT', '/api/v1/backlog/{id}', 'updateBacklogItem', (context) => updateBacklogItem(context), {
1970
+ bodyLimit: BACKLOG_ITEM_BODY_MAX,
1971
+ requireJson: true,
1972
+ }),
1511
1973
  ];
1512
1974
 
1513
1975
  /** The documented `METHOD path` pairs, for the contract gate's route parity. */
@@ -1695,7 +2157,9 @@ const handle = async (req, res, settings) => {
1695
2157
  handle: handleOnce,
1696
2158
  });
1697
2159
  if (result.json !== undefined) {
1698
- sendJson(req, res, 200, result.json);
2160
+ // A mutation may pin its own status: the backlog create answers 201
2161
+ // and the idempotent enqueue answers 200 or 201.
2162
+ sendJson(req, res, result.status ?? 200, result.json);
1699
2163
  return;
1700
2164
  }
1701
2165
  send(req, res, 200, { 'Content-Type': result.type, 'Cache-Control': result.cache }, result.body);