@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
@@ -32,6 +32,7 @@ import {
32
32
  teamDbFail,
33
33
  } from './team-db-schema.mjs';
34
34
  import { projectScheduler, retainRuns } from './team-db-scheduler.mjs';
35
+ import { validateEntrySchema, validateItemSchema } from './team-db-backlog.mjs';
35
36
 
36
37
  export const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
37
38
  export const MAX_RAW_BYTES = 32 * 1024 * 1024;
@@ -1337,6 +1338,269 @@ const projectTask = ({ db, teamRoot, slug, now, searchMode, deadlineAt }) => {
1337
1338
  return { status: existing ? 'updated' : 'inserted', errors };
1338
1339
  };
1339
1340
 
1341
+ /* ------------------------------ backlog walker ----------------------------- */
1342
+
1343
+ const BACKLOG_ITEM_DIR = 'backlog/items';
1344
+ const BACKLOG_QUEUE_DIR = 'backlog/queue';
1345
+
1346
+ const listBacklogJsonFiles = (teamRoot, dirName) => {
1347
+ const dir = path.join(teamRoot, dirName);
1348
+ if (!fs.existsSync(dir)) return [];
1349
+ return fs
1350
+ .readdirSync(dir)
1351
+ .filter((name) => name.endsWith('.json'))
1352
+ .map((name) => name.slice(0, -'.json'.length))
1353
+ .sort();
1354
+ };
1355
+
1356
+ const readBacklogJson = (file) => {
1357
+ try {
1358
+ return { text: fs.readFileSync(file, 'utf8'), error: null };
1359
+ } catch (error) {
1360
+ return { text: null, error: error.message };
1361
+ }
1362
+ };
1363
+
1364
+ const UPSERT_BACKLOG_ITEM_SQL = `
1365
+ INSERT INTO backlog_items (
1366
+ id, title, status, priority, type, description, labels_json, source_task,
1367
+ source_refs_json, revision, created_at, updated_at, completed_at, cancelled_at,
1368
+ cancel_reason, superseded_by, history_json, content_hash, parse_error,
1369
+ projected_at, first_seen_at, last_seen_at, absent_at
1370
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
1371
+ ON CONFLICT(id) DO UPDATE SET
1372
+ title = excluded.title,
1373
+ status = excluded.status,
1374
+ priority = excluded.priority,
1375
+ type = excluded.type,
1376
+ description = excluded.description,
1377
+ labels_json = excluded.labels_json,
1378
+ source_task = excluded.source_task,
1379
+ source_refs_json = excluded.source_refs_json,
1380
+ revision = excluded.revision,
1381
+ created_at = excluded.created_at,
1382
+ updated_at = excluded.updated_at,
1383
+ completed_at = excluded.completed_at,
1384
+ cancelled_at = excluded.cancelled_at,
1385
+ cancel_reason = excluded.cancel_reason,
1386
+ superseded_by = excluded.superseded_by,
1387
+ history_json = excluded.history_json,
1388
+ content_hash = excluded.content_hash,
1389
+ parse_error = excluded.parse_error,
1390
+ projected_at = excluded.projected_at,
1391
+ last_seen_at = excluded.last_seen_at,
1392
+ absent_at = NULL
1393
+ `;
1394
+
1395
+ const UPSERT_BACKLOG_ENTRY_SQL = `
1396
+ INSERT INTO backlog_queue (
1397
+ entry_id, item_id, status, reason, requested_by, command, revision,
1398
+ requested_at, claimed_at, finished_at, history_json, content_hash, parse_error,
1399
+ projected_at, first_seen_at, last_seen_at, absent_at
1400
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
1401
+ ON CONFLICT(entry_id) DO UPDATE SET
1402
+ item_id = excluded.item_id,
1403
+ status = excluded.status,
1404
+ reason = excluded.reason,
1405
+ requested_by = excluded.requested_by,
1406
+ command = excluded.command,
1407
+ revision = excluded.revision,
1408
+ requested_at = excluded.requested_at,
1409
+ claimed_at = excluded.claimed_at,
1410
+ finished_at = excluded.finished_at,
1411
+ history_json = excluded.history_json,
1412
+ content_hash = excluded.content_hash,
1413
+ parse_error = excluded.parse_error,
1414
+ projected_at = excluded.projected_at,
1415
+ last_seen_at = excluded.last_seen_at,
1416
+ absent_at = NULL
1417
+ `;
1418
+
1419
+ /**
1420
+ * One backlog item: parse, validate, upsert by natural key, replace its deps.
1421
+ * An unchanged `content_hash` only touches `last_seen_at`; a broken file
1422
+ * projects as a recorded `parse_error`, never aborts the run.
1423
+ */
1424
+ const projectBacklogItem = ({ db, teamRoot, stem, now, deadlineAt }) => {
1425
+ if (Date.now() > deadlineAt) teamDbFail('E_DEADLINE', 'projection deadline expired in the backlog walk', 4);
1426
+ const file = path.join(teamRoot, BACKLOG_ITEM_DIR, `${stem}.json`);
1427
+ const read = readBacklogJson(file);
1428
+ const contentHash = sha256(read.text ?? '');
1429
+ const existing = db.prepare('SELECT content_hash, absent_at FROM backlog_items WHERE id = ?').get(stem);
1430
+ if (read.text !== null && existing && existing.content_hash === contentHash && existing.absent_at === null) {
1431
+ db.prepare('UPDATE backlog_items SET last_seen_at = ? WHERE id = ?').run(now, stem);
1432
+ return { status: 'unchanged', parseError: null };
1433
+ }
1434
+ let item = null;
1435
+ let parseError = read.error;
1436
+ if (read.text !== null) {
1437
+ try {
1438
+ item = JSON.parse(read.text);
1439
+ } catch (error) {
1440
+ parseError = error.message;
1441
+ }
1442
+ if (item !== null) {
1443
+ try {
1444
+ validateItemSchema(item);
1445
+ } catch (error) {
1446
+ parseError = error instanceof TeamDbError ? `${error.code}: ${error.message}` : error.message;
1447
+ }
1448
+ }
1449
+ }
1450
+ db.prepare(UPSERT_BACKLOG_ITEM_SQL).run(
1451
+ stem,
1452
+ item?.title ?? null,
1453
+ item?.status ?? null,
1454
+ Number.isInteger(item?.priority) ? item.priority : null,
1455
+ item?.type ?? null,
1456
+ item?.description ?? null,
1457
+ Array.isArray(item?.labels) ? canonicalJson(item.labels) : null,
1458
+ item?.sourceTask ?? null,
1459
+ Array.isArray(item?.sourceRefs) ? canonicalJson(item.sourceRefs) : null,
1460
+ Number.isInteger(item?.revision) ? item.revision : null,
1461
+ isoTimestamp(item?.createdAt),
1462
+ isoTimestamp(item?.updatedAt),
1463
+ isoTimestamp(item?.completedAt),
1464
+ isoTimestamp(item?.cancelledAt),
1465
+ item?.cancelReason ?? null,
1466
+ item?.supersededBy ?? null,
1467
+ Array.isArray(item?.history) ? canonicalJson(item.history) : null,
1468
+ contentHash,
1469
+ parseError,
1470
+ now,
1471
+ now,
1472
+ now,
1473
+ );
1474
+ db.prepare('DELETE FROM backlog_item_deps WHERE item_id = ?').run(stem);
1475
+ if (Array.isArray(item?.dependsOn)) {
1476
+ const insert = db.prepare('INSERT INTO backlog_item_deps(item_id, dep_id, ordinal) VALUES (?, ?, ?)');
1477
+ item.dependsOn.forEach((dep, ordinal) => insert.run(stem, dep, ordinal));
1478
+ }
1479
+ return { status: existing ? 'updated' : 'inserted', parseError };
1480
+ };
1481
+
1482
+ /** One queue entry: upsert by entry id and replace its derived event rows. */
1483
+ const projectBacklogEntry = ({ db, teamRoot, stem, now, deadlineAt }) => {
1484
+ if (Date.now() > deadlineAt) teamDbFail('E_DEADLINE', 'projection deadline expired in the backlog walk', 4);
1485
+ const file = path.join(teamRoot, BACKLOG_QUEUE_DIR, `${stem}.json`);
1486
+ const read = readBacklogJson(file);
1487
+ const contentHash = sha256(read.text ?? '');
1488
+ const existing = db.prepare('SELECT content_hash, absent_at FROM backlog_queue WHERE entry_id = ?').get(stem);
1489
+ if (read.text !== null && existing && existing.content_hash === contentHash && existing.absent_at === null) {
1490
+ db.prepare('UPDATE backlog_queue SET last_seen_at = ? WHERE entry_id = ?').run(now, stem);
1491
+ return { status: 'unchanged', parseError: null };
1492
+ }
1493
+ let entry = null;
1494
+ let parseError = read.error;
1495
+ if (read.text !== null) {
1496
+ try {
1497
+ entry = JSON.parse(read.text);
1498
+ } catch (error) {
1499
+ parseError = error.message;
1500
+ }
1501
+ if (entry !== null) {
1502
+ try {
1503
+ validateEntrySchema(entry);
1504
+ } catch (error) {
1505
+ parseError = error instanceof TeamDbError ? `${error.code}: ${error.message}` : error.message;
1506
+ }
1507
+ }
1508
+ }
1509
+ db.prepare(UPSERT_BACKLOG_ENTRY_SQL).run(
1510
+ stem,
1511
+ entry?.itemId ?? null,
1512
+ entry?.status ?? null,
1513
+ entry?.reason ?? null,
1514
+ entry?.requestedBy ?? null,
1515
+ entry?.command ?? null,
1516
+ Number.isInteger(entry?.revision) ? entry.revision : null,
1517
+ isoTimestamp(entry?.requestedAt),
1518
+ isoTimestamp(entry?.claimedAt),
1519
+ isoTimestamp(entry?.finishedAt),
1520
+ Array.isArray(entry?.history) ? canonicalJson(entry.history) : null,
1521
+ contentHash,
1522
+ parseError,
1523
+ now,
1524
+ now,
1525
+ now,
1526
+ );
1527
+ db.prepare('DELETE FROM backlog_queue_events WHERE entry_id = ?').run(stem);
1528
+ if (Array.isArray(entry?.history)) {
1529
+ const insert = db.prepare(
1530
+ 'INSERT INTO backlog_queue_events(entry_id, seq, at, type, actor, detail) VALUES (?, ?, ?, ?, ?, ?)',
1531
+ );
1532
+ entry.history.forEach((event, index) => {
1533
+ insert.run(stem, index + 1, isoTimestamp(event?.at), event?.type ?? null, event?.actor ?? null, event?.detail ?? null);
1534
+ });
1535
+ }
1536
+ return { status: existing ? 'updated' : 'inserted', parseError };
1537
+ };
1538
+
1539
+ /**
1540
+ * Walk `backlog/items/*.json` and `backlog/queue/*.json`: two bounded
1541
+ * listings, idempotent by `content_hash`, absent marking for files the walk
1542
+ * did not see. `parse_error` rows are recorded failures, never an abort. The
1543
+ * whole walk runs in one transaction — 200 rows must stay far under the
1544
+ * 250 ms WP3 bound, and a deadline failure rolls the walk back as a unit.
1545
+ */
1546
+ export function projectBacklog({ db, teamRoot, now, deadlineAt = Infinity }) {
1547
+ const seenItems = new Set();
1548
+ const seenEntries = new Set();
1549
+ const counters = { inserted: 0, updated: 0, unchanged: 0, failed: 0, absent: 0 };
1550
+ const errors = [];
1551
+ db.exec('BEGIN IMMEDIATE');
1552
+ try {
1553
+ for (const stem of listBacklogJsonFiles(teamRoot, BACKLOG_ITEM_DIR)) {
1554
+ seenItems.add(stem);
1555
+ try {
1556
+ const { status, parseError } = projectBacklogItem({ db, teamRoot, stem, now, deadlineAt });
1557
+ counters[status] += 1;
1558
+ if (parseError !== null) {
1559
+ counters.failed += 1;
1560
+ errors.push({ path: `${BACKLOG_ITEM_DIR}/${stem}.json`, reason: parseError });
1561
+ }
1562
+ } catch (error) {
1563
+ if (error instanceof TeamDbError) throw error;
1564
+ counters.failed += 1;
1565
+ errors.push({ path: `${BACKLOG_ITEM_DIR}/${stem}.json`, reason: error.message });
1566
+ }
1567
+ }
1568
+ for (const stem of listBacklogJsonFiles(teamRoot, BACKLOG_QUEUE_DIR)) {
1569
+ seenEntries.add(stem);
1570
+ try {
1571
+ const { status, parseError } = projectBacklogEntry({ db, teamRoot, stem, now, deadlineAt });
1572
+ counters[status] += 1;
1573
+ if (parseError !== null) {
1574
+ counters.failed += 1;
1575
+ errors.push({ path: `${BACKLOG_QUEUE_DIR}/${stem}.json`, reason: parseError });
1576
+ }
1577
+ } catch (error) {
1578
+ if (error instanceof TeamDbError) throw error;
1579
+ counters.failed += 1;
1580
+ errors.push({ path: `${BACKLOG_QUEUE_DIR}/${stem}.json`, reason: error.message });
1581
+ }
1582
+ }
1583
+ const markAbsent = (table, keyColumn, seen) => {
1584
+ for (const row of db.prepare(`SELECT ${keyColumn} AS key FROM ${table} WHERE absent_at IS NULL`).all()) {
1585
+ if (seen.has(row.key)) continue;
1586
+ db.prepare(`UPDATE ${table} SET absent_at = ? WHERE ${keyColumn} = ? AND absent_at IS NULL`).run(now, row.key);
1587
+ counters.absent += 1;
1588
+ }
1589
+ };
1590
+ markAbsent('backlog_items', 'id', seenItems);
1591
+ markAbsent('backlog_queue', 'entry_id', seenEntries);
1592
+ db.exec('COMMIT');
1593
+ } catch (error) {
1594
+ try {
1595
+ db.exec('ROLLBACK');
1596
+ } catch {
1597
+ /* the transaction may already be gone; the original error is the finding */
1598
+ }
1599
+ throw error;
1600
+ }
1601
+ return { ...counters, errors };
1602
+ }
1603
+
1340
1604
  /* --------------------------- search and lifecycle -------------------------- */
1341
1605
 
1342
1606
  const escapeLike = (value) => value.replace(/[\\%_]/g, '\\$&');
@@ -1550,10 +1814,30 @@ export function syncProjection(options = {}) {
1550
1814
  : db.prepare('UPDATE tasks SET absent_at = ? WHERE absent_at IS NULL');
1551
1815
  result.absent += slugs.length ? statement.run(startedAt, ...slugs).changes : statement.run(startedAt).changes;
1552
1816
  }
1553
- if (prune) result.pruned += db.prepare('DELETE FROM tasks WHERE absent_at IS NOT NULL').run().changes;
1554
- // Projection order is tasks -> jobs.json -> runs/** (FK-safe) -> retention.
1555
- // `sync --slug` skips the scheduler so the hook's 4.5 s deadline holds; a
1556
- // full sync reconciles.
1817
+ if (prune) {
1818
+ result.pruned += db.prepare('DELETE FROM tasks WHERE absent_at IS NOT NULL').run().changes;
1819
+ // Backlog rows follow their files: pruning deletes rows marked absent.
1820
+ result.pruned += db.prepare('DELETE FROM backlog_queue WHERE absent_at IS NOT NULL').run().changes;
1821
+ result.pruned += db.prepare('DELETE FROM backlog_items WHERE absent_at IS NOT NULL').run().changes;
1822
+ }
1823
+ // Projection order is tasks -> backlog -> jobs.json -> runs/** (FK-safe)
1824
+ // -> retention. The backlog walk is two bounded listings, runs in slug
1825
+ // mode too, and stays inside the deadline budget (WP3 VERIFY: 200 items
1826
+ // must cost well under 250 ms).
1827
+ {
1828
+ const backlogProjection = projectBacklog({
1829
+ db,
1830
+ teamRoot: handle.teamRoot,
1831
+ now: new Date().toISOString(),
1832
+ deadlineAt,
1833
+ });
1834
+ result.inserted += backlogProjection.inserted;
1835
+ result.updated += backlogProjection.updated;
1836
+ result.unchanged += backlogProjection.unchanged;
1837
+ result.absent += backlogProjection.absent;
1838
+ result.failed += backlogProjection.failed;
1839
+ for (const error of backlogProjection.errors) result.errors.push(error);
1840
+ }
1557
1841
  if (!slug) {
1558
1842
  const schedulerProjection = projectScheduler(db, { teamRoot: handle.teamRoot });
1559
1843
  result.failed += schedulerProjection.failed;
@@ -48,6 +48,14 @@ export const STDOUT_FILE = 'stdout.log';
48
48
  export const STDERR_FILE = 'stderr.log';
49
49
  export const PROMPT_FILE = 'prompt.md';
50
50
 
51
+ /**
52
+ * The `{{...}}` vocabulary a pipeline prompt may use: `validateJob` refuses any
53
+ * other token (the definition would render verbatim) and `executeRun` renders
54
+ * exactly this list. One list owns the contract between `payload.promptTemplate`
55
+ * and the render pass.
56
+ */
57
+ export const PROMPT_TOKENS = ['{{job.id}}', '{{run.id}}', '{{run.dir}}', '{{team.root}}', '{{now}}'];
58
+
51
59
  export const JOB_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
52
60
  export const RUN_ID_RE = /^[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}$/;
53
61
  export const ENV_NAME_RE = /^[A-Z_][A-Z0-9_]{0,63}$/;
@@ -666,6 +674,22 @@ export function validateJob(input, options = {}) {
666
674
  if (fs.existsSync(resolved.resolved) && fs.statSync(resolved.resolved).size > MAX_PROMPT_BYTES) {
667
675
  failField('payload.promptTemplate', `must be at most ${MAX_PROMPT_BYTES} bytes`);
668
676
  }
677
+ // The `{{placeholder}}` contract: every token in the template must be one
678
+ // the scheduler renders, or the definition would run with the raw token
679
+ // left in the prompt. An absent file stays a runtime reason
680
+ // (E_PROMPT_MISSING), not a definition error.
681
+ if (fs.existsSync(resolved.resolved)) {
682
+ const template = fs.readFileSync(resolved.resolved, 'utf8');
683
+ for (const match of template.matchAll(/\{\{([^{}]*)\}\}/g)) {
684
+ const token = match[0];
685
+ if (!PROMPT_TOKENS.includes(token)) {
686
+ failField(
687
+ 'payload.promptTemplate',
688
+ `unknown placeholder ${token}; a pipeline prompt may use ${PROMPT_TOKENS.join(', ')}`,
689
+ );
690
+ }
691
+ }
692
+ }
669
693
  promptTemplate = resolved.value;
670
694
  if (payload.runner === undefined) {
671
695
  failField('payload.runner', 'no runner configured: kind "pipeline" needs payload.runner');
@@ -815,7 +839,7 @@ export function writeStateFile(teamRoot, state) {
815
839
  /**
816
840
  * Read the lease without creating anything. A lease older than
817
841
  * `LEASE_STALE_MS` is reported `stale`, never deleted: the next scheduler start
818
- * overwrites it only after taking its own lock.
842
+ * re-claims it only through its own exclusive create (`wx`).
819
843
  */
820
844
  export function readLease(teamRoot, options = {}) {
821
845
  const paths = schedulerPaths(teamRoot);
@@ -855,6 +879,29 @@ const writeLease = (teamRoot, lease) => {
855
879
  writeAtomic(paths.lock, `${JSON.stringify(lease, null, 2)}\n`);
856
880
  };
857
881
 
882
+ /**
883
+ * Claim the lease with one exclusive create (`wx`): two simultaneous starts
884
+ * cannot both observe no lease and both write one, so the loser refuses
885
+ * exactly like a sequential second start (E_BUSY, exit 4). Returns false when
886
+ * the create lost a race; the caller re-reads and refuses.
887
+ */
888
+ const claimLease = (teamRoot, lease) => {
889
+ const paths = schedulerPaths(teamRoot);
890
+ let fd;
891
+ try {
892
+ fd = fs.openSync(paths.lock, 'wx', 0o600);
893
+ } catch (error) {
894
+ if (error && error.code === 'EEXIST') return false;
895
+ throw error;
896
+ }
897
+ try {
898
+ fs.writeFileSync(fd, `${JSON.stringify(lease, null, 2)}\n`, 'utf8');
899
+ } finally {
900
+ fs.closeSync(fd);
901
+ }
902
+ return true;
903
+ };
904
+
858
905
  const releaseLease = (teamRoot, pid) => {
859
906
  const paths = schedulerPaths(teamRoot);
860
907
  try {
@@ -1412,8 +1459,12 @@ export function resolveExecutable(command, { platform = process.platform, env =
1412
1459
  return command;
1413
1460
  }
1414
1461
 
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);
1462
+ /**
1463
+ * A `.cmd`/`.bat` runs through `cmd.exe`, which joins argv into one line. The
1464
+ * cmd.exe doubling convention (`""`) keeps an embedded quote inside the
1465
+ * argument; `\"` would end the quoted argument instead.
1466
+ */
1467
+ export const quoteWindowsArg = (value) => (/[\s"]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value);
1417
1468
 
1418
1469
  /* -------------------------------- CLI surface ------------------------------ */
1419
1470
 
@@ -1865,12 +1916,17 @@ async function executeRun(context, job, manifest) {
1865
1916
  if (stats.size > MAX_PROMPT_BYTES) reason = 'E_PROMPT_TOO_LARGE';
1866
1917
  else {
1867
1918
  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);
1919
+ const tokenValues = {
1920
+ '{{job.id}}': job.id,
1921
+ '{{run.id}}': manifest.runId,
1922
+ '{{run.dir}}': runDir,
1923
+ '{{team.root}}': teamRoot,
1924
+ '{{now}}': startedAt,
1925
+ };
1926
+ const rendered = PROMPT_TOKENS.reduce(
1927
+ (text, token) => text.replaceAll(token, tokenValues[token]),
1928
+ template,
1929
+ );
1874
1930
  const promptPath = path.join(runDir, PROMPT_FILE);
1875
1931
  fs.writeFileSync(promptPath, rendered, { encoding: 'utf8', mode: 0o600 });
1876
1932
  promptRecord = {
@@ -2142,9 +2198,25 @@ export async function runScheduler(options = {}) {
2142
2198
  );
2143
2199
  }
2144
2200
 
2201
+ // Stale takeover stays remove-then-create (D-6): re-read before the delete so
2202
+ // a lease another start reclaimed in the meantime is left standing, and the
2203
+ // exclusive create below refuses instead.
2204
+ if (existing.state === 'stale' && readLease(teamRoot).state === 'stale') {
2205
+ fs.rmSync(schedulerPaths(teamRoot).lock, { force: true });
2206
+ }
2207
+
2145
2208
  const startedAt = new Date().toISOString();
2146
2209
  const lease = { version: LEASE_VERSION, pid: process.pid, host: os.hostname(), startedAt, heartbeatAt: startedAt };
2147
- writeLease(teamRoot, lease);
2210
+ // One exclusive create decides the claim (C3): an EEXIST here means a
2211
+ // simultaneous start created the lease between our read and ours.
2212
+ if (!claimLease(teamRoot, lease)) {
2213
+ const raced = readLease(teamRoot);
2214
+ teamDbFail(
2215
+ 'E_BUSY',
2216
+ `${schedulerPaths(teamRoot).lock} is held by pid ${raced.lease?.pid ?? '?'}; one scheduler per team root`,
2217
+ 4,
2218
+ );
2219
+ }
2148
2220
  fs.mkdirSync(schedulerPaths(teamRoot).runs, { recursive: true, mode: 0o700 });
2149
2221
 
2150
2222
  const handle = openTeamDb({ teamRoot });
@@ -396,6 +396,83 @@ CREATE INDEX idx_job_runs_state_started ON job_runs(state, started_at DESC);
396
396
  CREATE INDEX idx_job_run_events_at ON job_run_events(at);
397
397
  `;
398
398
 
399
+ /**
400
+ * Migration 3: the backlog projection. Four tables, five indexes, additive
401
+ * only — no `ALTER` of `tasks` or `scheduler` tables, so a wrong v3 costs a
402
+ * v4, never an edit (D-1, brief R-2). `active`/`done` are derived from the
403
+ * joined task row, never stored; `backlog_item_deps` has no FK on `dep_id` so
404
+ * a broken file set projects as a recorded error instead of aborting the run.
405
+ */
406
+ export const BACKLOG_SQL = SQL`CREATE TABLE backlog_items (
407
+ id TEXT PRIMARY KEY,
408
+ title TEXT,
409
+ status TEXT CHECK (status IS NULL OR status IN ('planned','completed','cancelled','superseded')),
410
+ priority INTEGER CHECK (priority IS NULL OR priority BETWEEN 0 AND 9),
411
+ type TEXT,
412
+ description TEXT,
413
+ labels_json TEXT,
414
+ source_task TEXT,
415
+ source_refs_json TEXT,
416
+ revision INTEGER,
417
+ created_at TEXT,
418
+ updated_at TEXT,
419
+ completed_at TEXT,
420
+ cancelled_at TEXT,
421
+ cancel_reason TEXT,
422
+ superseded_by TEXT,
423
+ history_json TEXT,
424
+ content_hash TEXT,
425
+ parse_error TEXT,
426
+ projected_at TEXT NOT NULL,
427
+ first_seen_at TEXT NOT NULL,
428
+ last_seen_at TEXT NOT NULL,
429
+ absent_at TEXT
430
+ ) STRICT;
431
+
432
+ CREATE TABLE backlog_item_deps (
433
+ item_id TEXT NOT NULL,
434
+ dep_id TEXT NOT NULL,
435
+ ordinal INTEGER NOT NULL,
436
+ PRIMARY KEY (item_id, dep_id)
437
+ ) STRICT;
438
+
439
+ CREATE TABLE backlog_queue (
440
+ entry_id TEXT PRIMARY KEY,
441
+ item_id TEXT NOT NULL,
442
+ status TEXT CHECK (status IS NULL OR status IN ('queued','claimed','cancelled','expired')),
443
+ reason TEXT,
444
+ requested_by TEXT,
445
+ command TEXT,
446
+ revision INTEGER,
447
+ requested_at TEXT,
448
+ claimed_at TEXT,
449
+ finished_at TEXT,
450
+ history_json TEXT,
451
+ content_hash TEXT,
452
+ parse_error TEXT,
453
+ projected_at TEXT NOT NULL,
454
+ first_seen_at TEXT NOT NULL,
455
+ last_seen_at TEXT NOT NULL,
456
+ absent_at TEXT
457
+ ) STRICT;
458
+
459
+ CREATE TABLE backlog_queue_events (
460
+ entry_id TEXT NOT NULL,
461
+ seq INTEGER NOT NULL CHECK (seq >= 1),
462
+ at TEXT,
463
+ type TEXT,
464
+ actor TEXT,
465
+ detail TEXT,
466
+ PRIMARY KEY (entry_id, seq)
467
+ ) STRICT;
468
+
469
+ CREATE INDEX idx_backlog_items_order ON backlog_items(status, priority, created_at, id);
470
+ CREATE INDEX idx_backlog_items_source ON backlog_items(source_task);
471
+ CREATE INDEX idx_backlog_item_deps_dep ON backlog_item_deps(dep_id);
472
+ CREATE INDEX idx_backlog_queue_status ON backlog_queue(status, requested_at);
473
+ CREATE INDEX idx_backlog_queue_item ON backlog_queue(item_id);
474
+ `;
475
+
399
476
  const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
400
477
 
401
478
  /**
@@ -415,6 +492,12 @@ export const MIGRATIONS = [
415
492
  sql: SCHEDULER_SQL,
416
493
  checksum: '2e9d913368619565e3283f2099ca1d7a4039ee96f147ed7a8ce7b38b61dafe3c',
417
494
  },
495
+ {
496
+ version: 3,
497
+ name: '0003-backlog',
498
+ sql: BACKLOG_SQL,
499
+ checksum: '430c079a4ec42bc93094f364df228c2f55772e1f9e8f1e0e509b1d16c2de7f90',
500
+ },
418
501
  ];
419
502
 
420
503
  /** Highest migration version shipped by this module. */