@bonesofspring/ai-rules 0.2.64 → 0.2.66

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 (464) hide show
  1. package/CHANGELOG.md +80 -11
  2. package/README.md +24 -16
  3. package/bin/lib/engine-scripts.js +52 -12
  4. package/bin/lib/engine-upgrade.js +5 -2
  5. package/bin/lib/seed-ai-local-team.js +13 -3
  6. package/docs/OPENCODE.md +17 -9
  7. package/docs/PRESET-CONTRIBUTION.md +41 -0
  8. package/docs/TEAM-DB.md +240 -60
  9. package/docs/TOKEN-ECONOMY.md +79 -0
  10. package/docs/openapi/team-db.v1.json +1238 -377
  11. package/mcp/defectdojo-mcp.mjs +7 -5
  12. package/mcp/lib/defectdojo.mjs +26 -14
  13. package/package.json +31 -20
  14. package/presets/_shared/ai-local/scripts/dump-output.mjs +371 -0
  15. package/presets/_shared/ai-local/scripts/process-lease.mjs +576 -0
  16. package/presets/_shared/ai-local/scripts/processes.mjs +1618 -0
  17. package/presets/_shared/ai-local/scripts/run.mjs +5 -5
  18. package/presets/_shared/ai-local/scripts/team-db-api.mjs +465 -152
  19. package/presets/_shared/ai-local/scripts/team-db-dashboard.mjs +235 -10
  20. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +416 -176
  21. package/presets/_shared/ai-local/scripts/team-db-project.mjs +171 -62
  22. package/presets/_shared/ai-local/scripts/team-db-scheduler.mjs +4 -0
  23. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +143 -5
  24. package/presets/_shared/ai-local/scripts/team-db-task-runner.mjs +567 -0
  25. package/presets/_shared/ai-local/scripts/{team-db-backlog.mjs → team-db-tracker.mjs} +900 -197
  26. package/presets/_shared/ai-local/scripts/team-db-ui.mjs +750 -0
  27. package/presets/_shared/ai-local/scripts/team-db.mjs +184 -23
  28. package/presets/_shared/core/agent-team/agent-team-orchestrator.md +4 -2
  29. package/presets/_shared/core/architecture/feature-delivery-workflow.md +4 -0
  30. package/presets/_shared/core/quality/context-and-iteration.md +1 -0
  31. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +105 -17
  32. package/presets/_shared/hooks/guard-shell-command.mjs.tmpl +40 -2
  33. package/presets/claude/android-kotlin/agents/task-analyst.md +1 -1
  34. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +105 -17
  35. package/presets/claude/android-kotlin/hooks/guard-shell-command.mjs +41 -2
  36. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +4 -2
  37. package/presets/claude/android-kotlin/settings.json +6 -1
  38. package/presets/claude/go/agents/task-analyst.md +1 -1
  39. package/presets/claude/go/hooks/chain-team-phases.sh +105 -17
  40. package/presets/claude/go/hooks/guard-shell-command.mjs +41 -2
  41. package/presets/claude/go/rules/architecture/feature-delivery.md +4 -0
  42. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +4 -2
  43. package/presets/claude/go/settings.json +6 -1
  44. package/presets/claude/ios-swift/agents/task-analyst.md +1 -1
  45. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +105 -17
  46. package/presets/claude/ios-swift/hooks/guard-shell-command.mjs +41 -2
  47. package/presets/claude/ios-swift/rules/architecture/feature-delivery.md +4 -0
  48. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +4 -2
  49. package/presets/claude/ios-swift/settings.json +6 -1
  50. package/presets/claude/java/agents/task-analyst.md +1 -1
  51. package/presets/claude/java/hooks/chain-team-phases.sh +105 -17
  52. package/presets/claude/java/hooks/guard-shell-command.mjs +41 -2
  53. package/presets/claude/java/rules/architecture/feature-delivery.md +4 -0
  54. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +4 -2
  55. package/presets/claude/java/settings.json +6 -1
  56. package/presets/claude/mcp-ts/agents/task-analyst.md +1 -1
  57. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +105 -17
  58. package/presets/claude/mcp-ts/hooks/guard-shell-command.mjs +41 -2
  59. package/presets/claude/mcp-ts/rules/architecture/feature-delivery.md +4 -0
  60. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +4 -2
  61. package/presets/claude/mcp-ts/settings.json +6 -1
  62. package/presets/claude/mol/agents/task-analyst.md +1 -1
  63. package/presets/claude/mol/hooks/chain-team-phases.sh +105 -17
  64. package/presets/claude/mol/hooks/guard-shell-command.mjs +41 -2
  65. package/presets/claude/mol/rules/architecture/feature-delivery-workflow.md +4 -0
  66. package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +4 -2
  67. package/presets/claude/mol/settings.json +6 -1
  68. package/presets/claude/next/MCP.md +2 -0
  69. package/presets/claude/next/REPO_AGENTS.md +2 -0
  70. package/presets/claude/next/agents/build-verifier.md +1 -1
  71. package/presets/claude/next/agents/ci-investigator.md +3 -0
  72. package/presets/claude/next/agents/debugger.md +3 -0
  73. package/presets/claude/next/agents/feature-developer.md +3 -0
  74. package/presets/claude/next/agents/mockup-reviewer.md +2 -0
  75. package/presets/claude/next/agents/performance-auditor.md +2 -0
  76. package/presets/claude/next/agents/playwright-test-generator.md +3 -0
  77. package/presets/claude/next/agents/playwright-test-healer.md +3 -0
  78. package/presets/claude/next/agents/playwright-test-planner.md +3 -0
  79. package/presets/claude/next/agents/qa-tester.md +3 -0
  80. package/presets/claude/next/agents/task-analyst.md +1 -1
  81. package/presets/claude/next/commands/README.md +7 -1
  82. package/presets/claude/next/commands/task.md +1 -1
  83. package/presets/claude/next/commands/ui-start.md +78 -0
  84. package/presets/claude/next/commands/ui-stop.md +71 -0
  85. package/presets/claude/next/hooks/chain-team-phases.sh +105 -17
  86. package/presets/claude/next/hooks/guard-shell-command.mjs +41 -2
  87. package/presets/claude/next/rules/README.md +2 -1
  88. package/presets/claude/next/rules/architecture/feature-delivery-workflow.md +4 -0
  89. package/presets/claude/next/rules/stack/next-app-core.md +1 -0
  90. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +4 -2
  91. package/presets/claude/next/rules/tooling-and-review/dev-process-lifecycle.md +43 -0
  92. package/presets/claude/next/settings.json +6 -1
  93. package/presets/claude/next/team/README.md +7 -3
  94. package/presets/claude/nuxt/agents/task-analyst.md +1 -1
  95. package/presets/claude/nuxt/hooks/chain-team-phases.sh +105 -17
  96. package/presets/claude/nuxt/hooks/guard-shell-command.mjs +41 -2
  97. package/presets/claude/nuxt/rules/architecture/feature-delivery-workflow.md +4 -0
  98. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +4 -2
  99. package/presets/claude/nuxt/settings.json +6 -1
  100. package/presets/claude/php-hexagonal/agents/task-analyst.md +1 -1
  101. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +105 -17
  102. package/presets/claude/php-hexagonal/hooks/guard-shell-command.mjs +41 -2
  103. package/presets/claude/php-hexagonal/rules/architecture/feature-delivery.md +4 -0
  104. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +4 -2
  105. package/presets/claude/php-hexagonal/settings.json +6 -1
  106. package/presets/claude/php-laravel/agents/task-analyst.md +1 -1
  107. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +106 -18
  108. package/presets/claude/php-laravel/hooks/guard-shell-command.mjs +41 -2
  109. package/presets/claude/php-laravel/rules/architecture/feature-delivery.md +4 -0
  110. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +4 -2
  111. package/presets/claude/php-laravel/settings.json +6 -1
  112. package/presets/claude/svelte/agents/task-analyst.md +1 -1
  113. package/presets/claude/svelte/hooks/chain-team-phases.sh +105 -17
  114. package/presets/claude/svelte/hooks/guard-shell-command.mjs +41 -2
  115. package/presets/claude/svelte/rules/architecture/feature-delivery-workflow.md +4 -0
  116. package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +4 -2
  117. package/presets/claude/svelte/settings.json +6 -1
  118. package/presets/cursor/android-kotlin/agents/task-analyst.md +1 -1
  119. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +105 -17
  120. package/presets/cursor/android-kotlin/hooks/guard-shell-command.mjs +41 -2
  121. package/presets/cursor/android-kotlin/rules/agent-team-orchestrator.mdc +1 -1
  122. package/presets/cursor/go/agents/task-analyst.md +1 -1
  123. package/presets/cursor/go/hooks/chain-team-phases.sh +105 -17
  124. package/presets/cursor/go/hooks/guard-shell-command.mjs +41 -2
  125. package/presets/cursor/go/rules/agent-team-orchestrator.mdc +1 -1
  126. package/presets/cursor/ios-swift/agents/task-analyst.md +1 -1
  127. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +105 -17
  128. package/presets/cursor/ios-swift/hooks/guard-shell-command.mjs +41 -2
  129. package/presets/cursor/ios-swift/rules/agent-team-orchestrator.mdc +1 -1
  130. package/presets/cursor/java/agents/task-analyst.md +1 -1
  131. package/presets/cursor/java/hooks/chain-team-phases.sh +105 -17
  132. package/presets/cursor/java/hooks/guard-shell-command.mjs +41 -2
  133. package/presets/cursor/java/rules/agent-team-orchestrator.mdc +1 -1
  134. package/presets/cursor/mcp-ts/agents/task-analyst.md +1 -1
  135. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +105 -17
  136. package/presets/cursor/mcp-ts/hooks/guard-shell-command.mjs +41 -2
  137. package/presets/cursor/mcp-ts/rules/agent-team-orchestrator.mdc +1 -1
  138. package/presets/cursor/mol/agents/task-analyst.md +1 -1
  139. package/presets/cursor/mol/hooks/chain-team-phases.sh +105 -17
  140. package/presets/cursor/mol/hooks/guard-shell-command.mjs +41 -2
  141. package/presets/cursor/mol/rules/agent-team-orchestrator.mdc +1 -1
  142. package/presets/cursor/next/MCP.md +2 -0
  143. package/presets/cursor/next/REPO_AGENTS.md +2 -0
  144. package/presets/cursor/next/agents/build-verifier.md +1 -1
  145. package/presets/cursor/next/agents/ci-investigator.md +2 -0
  146. package/presets/cursor/next/agents/debugger.md +2 -0
  147. package/presets/cursor/next/agents/feature-developer.md +2 -0
  148. package/presets/cursor/next/agents/mockup-reviewer.md +2 -0
  149. package/presets/cursor/next/agents/performance-auditor.md +2 -0
  150. package/presets/cursor/next/agents/playwright-test-generator.md +2 -0
  151. package/presets/cursor/next/agents/playwright-test-healer.md +2 -0
  152. package/presets/cursor/next/agents/playwright-test-planner.md +2 -0
  153. package/presets/cursor/next/agents/qa-tester.md +2 -0
  154. package/presets/cursor/next/agents/task-analyst.md +1 -1
  155. package/presets/cursor/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -1
  156. package/presets/cursor/next/commands/README.md +7 -1
  157. package/presets/cursor/next/commands/task.md +1 -1
  158. package/presets/cursor/next/commands/ui-start.md +78 -0
  159. package/presets/cursor/next/commands/ui-stop.md +71 -0
  160. package/presets/cursor/next/hooks/chain-team-phases.sh +105 -17
  161. package/presets/cursor/next/hooks/guard-shell-command.mjs +41 -2
  162. package/presets/cursor/next/rules/README.md +2 -1
  163. package/presets/cursor/next/rules/agent-team-orchestrator.mdc +3 -1
  164. package/presets/cursor/next/rules/dev-process-lifecycle.mdc +43 -0
  165. package/presets/cursor/next/rules/next-app-core.mdc +1 -0
  166. package/presets/cursor/next/team/README.md +7 -3
  167. package/presets/cursor/nuxt/agents/task-analyst.md +1 -1
  168. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +105 -17
  169. package/presets/cursor/nuxt/hooks/guard-shell-command.mjs +41 -2
  170. package/presets/cursor/nuxt/rules/agent-team-orchestrator.mdc +1 -1
  171. package/presets/cursor/php-hexagonal/agents/task-analyst.md +1 -1
  172. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +105 -17
  173. package/presets/cursor/php-hexagonal/hooks/guard-shell-command.mjs +41 -2
  174. package/presets/cursor/php-hexagonal/rules/agent-team-orchestrator.mdc +1 -1
  175. package/presets/cursor/php-laravel/agents/task-analyst.md +1 -1
  176. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +106 -18
  177. package/presets/cursor/php-laravel/hooks/guard-shell-command.mjs +41 -2
  178. package/presets/cursor/php-laravel/rules/agent-team-orchestrator.mdc +1 -1
  179. package/presets/cursor/svelte/agents/task-analyst.md +1 -1
  180. package/presets/cursor/svelte/hooks/chain-team-phases.sh +105 -17
  181. package/presets/cursor/svelte/hooks/guard-shell-command.mjs +41 -2
  182. package/presets/cursor/svelte/rules/agent-team-orchestrator.mdc +1 -1
  183. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  184. package/presets/mavis/android-kotlin/agents/task-analyst.md +1 -1
  185. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +105 -17
  186. package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +4 -2
  187. package/presets/mavis/go/adapter-map.json +1 -1
  188. package/presets/mavis/go/agents/task-analyst.md +1 -1
  189. package/presets/mavis/go/hooks/chain-team-phases.sh +105 -17
  190. package/presets/mavis/go/rules/agent-team-orchestrator.md +4 -2
  191. package/presets/mavis/go/rules/feature-delivery-workflow.md +4 -0
  192. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  193. package/presets/mavis/ios-swift/agents/task-analyst.md +1 -1
  194. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +105 -17
  195. package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +4 -2
  196. package/presets/mavis/ios-swift/rules/feature-delivery-workflow.md +4 -0
  197. package/presets/mavis/java/adapter-map.json +1 -1
  198. package/presets/mavis/java/agents/task-analyst.md +1 -1
  199. package/presets/mavis/java/hooks/chain-team-phases.sh +105 -17
  200. package/presets/mavis/java/rules/agent-team-orchestrator.md +4 -2
  201. package/presets/mavis/java/rules/feature-delivery-workflow.md +4 -0
  202. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  203. package/presets/mavis/mcp-ts/agents/task-analyst.md +1 -1
  204. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +105 -17
  205. package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +4 -2
  206. package/presets/mavis/mcp-ts/rules/feature-delivery-workflow.md +4 -0
  207. package/presets/mavis/mol/adapter-map.json +1 -1
  208. package/presets/mavis/mol/agents/task-analyst.md +1 -1
  209. package/presets/mavis/mol/hooks/chain-team-phases.sh +105 -17
  210. package/presets/mavis/mol/rules/agent-team-orchestrator.md +4 -2
  211. package/presets/mavis/mol/rules/feature-delivery-workflow.md +4 -0
  212. package/presets/mavis/next/MCP.md +2 -0
  213. package/presets/mavis/next/REPO_AGENTS.md +2 -0
  214. package/presets/mavis/next/adapter-map.json +33 -1
  215. package/presets/mavis/next/agents/build-verifier.md +1 -1
  216. package/presets/mavis/next/agents/ci-investigator.md +3 -0
  217. package/presets/mavis/next/agents/debugger.md +3 -0
  218. package/presets/mavis/next/agents/feature-developer.md +3 -0
  219. package/presets/mavis/next/agents/mockup-reviewer.md +2 -0
  220. package/presets/mavis/next/agents/performance-auditor.md +2 -0
  221. package/presets/mavis/next/agents/playwright-test-generator.md +3 -0
  222. package/presets/mavis/next/agents/playwright-test-healer.md +3 -0
  223. package/presets/mavis/next/agents/playwright-test-planner.md +3 -0
  224. package/presets/mavis/next/agents/qa-tester.md +3 -0
  225. package/presets/mavis/next/agents/task-analyst.md +1 -1
  226. package/presets/mavis/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -1
  227. package/presets/mavis/next/commands/README.md +7 -1
  228. package/presets/mavis/next/commands/task.md +1 -1
  229. package/presets/mavis/next/commands/ui-start.md +73 -0
  230. package/presets/mavis/next/commands/ui-stop.md +66 -0
  231. package/presets/mavis/next/hooks/chain-team-phases.sh +105 -17
  232. package/presets/mavis/next/rules/agent-team-orchestrator.md +4 -2
  233. package/presets/mavis/next/rules/dev-process-lifecycle.md +38 -0
  234. package/presets/mavis/next/rules/feature-delivery-workflow.md +4 -0
  235. package/presets/mavis/next/rules/next-app-core.md +1 -0
  236. package/presets/mavis/next/team/README.md +7 -3
  237. package/presets/mavis/nuxt/adapter-map.json +1 -1
  238. package/presets/mavis/nuxt/agents/task-analyst.md +1 -1
  239. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +105 -17
  240. package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +4 -2
  241. package/presets/mavis/nuxt/rules/feature-delivery-workflow.md +4 -0
  242. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  243. package/presets/mavis/php-hexagonal/agents/task-analyst.md +1 -1
  244. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +105 -17
  245. package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +4 -2
  246. package/presets/mavis/php-hexagonal/rules/feature-delivery-workflow.md +4 -0
  247. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  248. package/presets/mavis/php-laravel/agents/task-analyst.md +1 -1
  249. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +106 -18
  250. package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +4 -2
  251. package/presets/mavis/php-laravel/rules/feature-delivery-workflow.md +4 -0
  252. package/presets/mavis/svelte/adapter-map.json +1 -1
  253. package/presets/mavis/svelte/agents/task-analyst.md +1 -1
  254. package/presets/mavis/svelte/hooks/chain-team-phases.sh +105 -17
  255. package/presets/mavis/svelte/rules/agent-team-orchestrator.md +4 -2
  256. package/presets/mavis/svelte/rules/feature-delivery-workflow.md +4 -0
  257. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  258. package/presets/opencode/android-kotlin/agents/task-analyst.md +1 -1
  259. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +105 -17
  260. package/presets/opencode/android-kotlin/opencode.json +5 -1
  261. package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +4 -2
  262. package/presets/opencode/go/adapter-map.json +1 -1
  263. package/presets/opencode/go/agents/task-analyst.md +1 -1
  264. package/presets/opencode/go/hooks/chain-team-phases.sh +105 -17
  265. package/presets/opencode/go/opencode.json +5 -1
  266. package/presets/opencode/go/rules/agent-team-orchestrator.md +4 -2
  267. package/presets/opencode/go/rules/feature-delivery-workflow.md +4 -0
  268. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  269. package/presets/opencode/ios-swift/agents/task-analyst.md +1 -1
  270. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +105 -17
  271. package/presets/opencode/ios-swift/opencode.json +5 -1
  272. package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +4 -2
  273. package/presets/opencode/ios-swift/rules/feature-delivery-workflow.md +4 -0
  274. package/presets/opencode/java/adapter-map.json +1 -1
  275. package/presets/opencode/java/agents/task-analyst.md +1 -1
  276. package/presets/opencode/java/hooks/chain-team-phases.sh +105 -17
  277. package/presets/opencode/java/opencode.json +5 -1
  278. package/presets/opencode/java/rules/agent-team-orchestrator.md +4 -2
  279. package/presets/opencode/java/rules/feature-delivery-workflow.md +4 -0
  280. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  281. package/presets/opencode/mcp-ts/agents/task-analyst.md +1 -1
  282. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +105 -17
  283. package/presets/opencode/mcp-ts/opencode.json +5 -1
  284. package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +4 -2
  285. package/presets/opencode/mcp-ts/rules/feature-delivery-workflow.md +4 -0
  286. package/presets/opencode/mol/adapter-map.json +1 -1
  287. package/presets/opencode/mol/agents/task-analyst.md +1 -1
  288. package/presets/opencode/mol/hooks/chain-team-phases.sh +105 -17
  289. package/presets/opencode/mol/opencode.json +4 -0
  290. package/presets/opencode/mol/rules/agent-team-orchestrator.md +4 -2
  291. package/presets/opencode/mol/rules/feature-delivery-workflow.md +4 -0
  292. package/presets/opencode/next/MCP.md +2 -0
  293. package/presets/opencode/next/REPO_AGENTS.md +2 -0
  294. package/presets/opencode/next/adapter-map.json +33 -1
  295. package/presets/opencode/next/agents/build-verifier.md +1 -1
  296. package/presets/opencode/next/agents/ci-investigator.md +3 -0
  297. package/presets/opencode/next/agents/debugger.md +3 -0
  298. package/presets/opencode/next/agents/feature-developer.md +3 -0
  299. package/presets/opencode/next/agents/mockup-reviewer.md +2 -0
  300. package/presets/opencode/next/agents/performance-auditor.md +2 -0
  301. package/presets/opencode/next/agents/playwright-test-generator.md +3 -0
  302. package/presets/opencode/next/agents/playwright-test-healer.md +3 -0
  303. package/presets/opencode/next/agents/playwright-test-planner.md +3 -0
  304. package/presets/opencode/next/agents/qa-tester.md +3 -0
  305. package/presets/opencode/next/agents/task-analyst.md +1 -1
  306. package/presets/opencode/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -1
  307. package/presets/opencode/next/commands/README.md +7 -1
  308. package/presets/opencode/next/commands/task.md +1 -1
  309. package/presets/opencode/next/commands/ui-start.md +81 -0
  310. package/presets/opencode/next/commands/ui-stop.md +74 -0
  311. package/presets/opencode/next/hooks/chain-team-phases.sh +105 -17
  312. package/presets/opencode/next/opencode.json +4 -0
  313. package/presets/opencode/next/rules/agent-team-orchestrator.md +4 -2
  314. package/presets/opencode/next/rules/dev-process-lifecycle.md +38 -0
  315. package/presets/opencode/next/rules/feature-delivery-workflow.md +4 -0
  316. package/presets/opencode/next/rules/next-app-core.md +1 -0
  317. package/presets/opencode/next/team/README.md +7 -3
  318. package/presets/opencode/nuxt/adapter-map.json +1 -1
  319. package/presets/opencode/nuxt/agents/task-analyst.md +1 -1
  320. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +105 -17
  321. package/presets/opencode/nuxt/opencode.json +4 -0
  322. package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +4 -2
  323. package/presets/opencode/nuxt/rules/feature-delivery-workflow.md +4 -0
  324. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  325. package/presets/opencode/php-hexagonal/agents/task-analyst.md +1 -1
  326. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +105 -17
  327. package/presets/opencode/php-hexagonal/opencode.json +5 -1
  328. package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +4 -2
  329. package/presets/opencode/php-hexagonal/rules/feature-delivery-workflow.md +4 -0
  330. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  331. package/presets/opencode/php-laravel/agents/task-analyst.md +1 -1
  332. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +106 -18
  333. package/presets/opencode/php-laravel/opencode.json +5 -1
  334. package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +4 -2
  335. package/presets/opencode/php-laravel/rules/feature-delivery-workflow.md +4 -0
  336. package/presets/opencode/plugins/task-status/README.md +23 -11
  337. package/presets/opencode/plugins/task-status/details-data.ts +64 -46
  338. package/presets/opencode/plugins/task-status/details.tsx +12 -2
  339. package/presets/opencode/plugins/task-status/format.ts +16 -0
  340. package/presets/opencode/plugins/task-status/prompt-text.ts +37 -0
  341. package/presets/opencode/plugins/task-status/task-view.ts +241 -177
  342. package/presets/opencode/plugins/task-status/tui.tsx +57 -15
  343. package/presets/opencode/plugins/task-status/types.ts +74 -0
  344. package/presets/opencode/svelte/adapter-map.json +1 -1
  345. package/presets/opencode/svelte/agents/task-analyst.md +1 -1
  346. package/presets/opencode/svelte/hooks/chain-team-phases.sh +105 -17
  347. package/presets/opencode/svelte/opencode.json +4 -0
  348. package/presets/opencode/svelte/rules/agent-team-orchestrator.md +4 -2
  349. package/presets/opencode/svelte/rules/feature-delivery-workflow.md +4 -0
  350. package/presets/zcode/android-kotlin/adapter-map.json +1 -1
  351. package/presets/zcode/android-kotlin/agents/task-analyst.md +1 -1
  352. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +105 -17
  353. package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +4 -2
  354. package/presets/zcode/go/adapter-map.json +1 -1
  355. package/presets/zcode/go/agents/task-analyst.md +1 -1
  356. package/presets/zcode/go/hooks/chain-team-phases.sh +105 -17
  357. package/presets/zcode/go/rules/agent-team-orchestrator.md +4 -2
  358. package/presets/zcode/go/rules/feature-delivery-workflow.md +4 -0
  359. package/presets/zcode/ios-swift/adapter-map.json +1 -1
  360. package/presets/zcode/ios-swift/agents/task-analyst.md +1 -1
  361. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +105 -17
  362. package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +4 -2
  363. package/presets/zcode/ios-swift/rules/feature-delivery-workflow.md +4 -0
  364. package/presets/zcode/java/adapter-map.json +1 -1
  365. package/presets/zcode/java/agents/task-analyst.md +1 -1
  366. package/presets/zcode/java/hooks/chain-team-phases.sh +105 -17
  367. package/presets/zcode/java/rules/agent-team-orchestrator.md +4 -2
  368. package/presets/zcode/java/rules/feature-delivery-workflow.md +4 -0
  369. package/presets/zcode/mcp-ts/adapter-map.json +1 -1
  370. package/presets/zcode/mcp-ts/agents/task-analyst.md +1 -1
  371. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +105 -17
  372. package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +4 -2
  373. package/presets/zcode/mcp-ts/rules/feature-delivery-workflow.md +4 -0
  374. package/presets/zcode/mol/adapter-map.json +1 -1
  375. package/presets/zcode/mol/agents/task-analyst.md +1 -1
  376. package/presets/zcode/mol/hooks/chain-team-phases.sh +105 -17
  377. package/presets/zcode/mol/rules/agent-team-orchestrator.md +4 -2
  378. package/presets/zcode/mol/rules/feature-delivery-workflow.md +4 -0
  379. package/presets/zcode/next/MCP.md +2 -0
  380. package/presets/zcode/next/REPO_AGENTS.md +2 -0
  381. package/presets/zcode/next/adapter-map.json +33 -1
  382. package/presets/zcode/next/agents/build-verifier.md +1 -1
  383. package/presets/zcode/next/agents/ci-investigator.md +3 -0
  384. package/presets/zcode/next/agents/debugger.md +3 -0
  385. package/presets/zcode/next/agents/feature-developer.md +3 -0
  386. package/presets/zcode/next/agents/mockup-reviewer.md +2 -0
  387. package/presets/zcode/next/agents/performance-auditor.md +2 -0
  388. package/presets/zcode/next/agents/playwright-test-generator.md +3 -0
  389. package/presets/zcode/next/agents/playwright-test-healer.md +3 -0
  390. package/presets/zcode/next/agents/playwright-test-planner.md +3 -0
  391. package/presets/zcode/next/agents/qa-tester.md +3 -0
  392. package/presets/zcode/next/agents/task-analyst.md +1 -1
  393. package/presets/zcode/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -1
  394. package/presets/zcode/next/commands/README.md +7 -1
  395. package/presets/zcode/next/commands/task.md +1 -1
  396. package/presets/zcode/next/commands/ui-start.md +81 -0
  397. package/presets/zcode/next/commands/ui-stop.md +74 -0
  398. package/presets/zcode/next/hooks/chain-team-phases.sh +105 -17
  399. package/presets/zcode/next/rules/agent-team-orchestrator.md +4 -2
  400. package/presets/zcode/next/rules/dev-process-lifecycle.md +38 -0
  401. package/presets/zcode/next/rules/feature-delivery-workflow.md +4 -0
  402. package/presets/zcode/next/rules/next-app-core.md +1 -0
  403. package/presets/zcode/next/team/README.md +7 -3
  404. package/presets/zcode/nuxt/adapter-map.json +1 -1
  405. package/presets/zcode/nuxt/agents/task-analyst.md +1 -1
  406. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +105 -17
  407. package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +4 -2
  408. package/presets/zcode/nuxt/rules/feature-delivery-workflow.md +4 -0
  409. package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
  410. package/presets/zcode/php-hexagonal/agents/task-analyst.md +1 -1
  411. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +105 -17
  412. package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +4 -2
  413. package/presets/zcode/php-hexagonal/rules/feature-delivery-workflow.md +4 -0
  414. package/presets/zcode/php-laravel/adapter-map.json +1 -1
  415. package/presets/zcode/php-laravel/agents/task-analyst.md +1 -1
  416. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +106 -18
  417. package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +4 -2
  418. package/presets/zcode/php-laravel/rules/feature-delivery-workflow.md +4 -0
  419. package/presets/zcode/svelte/adapter-map.json +1 -1
  420. package/presets/zcode/svelte/agents/task-analyst.md +1 -1
  421. package/presets/zcode/svelte/hooks/chain-team-phases.sh +105 -17
  422. package/presets/zcode/svelte/rules/agent-team-orchestrator.md +4 -2
  423. package/presets/zcode/svelte/rules/feature-delivery-workflow.md +4 -0
  424. package/presets/_shared/ai-local/scripts/upstream-research.mjs +0 -2964
  425. package/presets/claude/next/commands/upstream-research.md +0 -23
  426. package/presets/claude/next/team/upstream/config.json +0 -31
  427. package/presets/claude/next/team/upstream/digest-template.md +0 -55
  428. package/presets/claude/next/team/upstream/jobs.json +0 -34
  429. package/presets/claude/next/team/upstream/opencode.json +0 -34
  430. package/presets/claude/next/team/upstream/projects.json +0 -4
  431. package/presets/claude/next/team/upstream/prompt.md +0 -77
  432. package/presets/claude/next/team/upstream/signatures.json +0 -9
  433. package/presets/cursor/next/commands/upstream-research.md +0 -23
  434. package/presets/cursor/next/team/upstream/config.json +0 -31
  435. package/presets/cursor/next/team/upstream/digest-template.md +0 -55
  436. package/presets/cursor/next/team/upstream/jobs.json +0 -34
  437. package/presets/cursor/next/team/upstream/opencode.json +0 -34
  438. package/presets/cursor/next/team/upstream/projects.json +0 -4
  439. package/presets/cursor/next/team/upstream/prompt.md +0 -77
  440. package/presets/cursor/next/team/upstream/signatures.json +0 -9
  441. package/presets/mavis/next/commands/upstream-research.md +0 -18
  442. package/presets/mavis/next/team/upstream/config.json +0 -31
  443. package/presets/mavis/next/team/upstream/digest-template.md +0 -55
  444. package/presets/mavis/next/team/upstream/jobs.json +0 -34
  445. package/presets/mavis/next/team/upstream/opencode.json +0 -34
  446. package/presets/mavis/next/team/upstream/projects.json +0 -4
  447. package/presets/mavis/next/team/upstream/prompt.md +0 -77
  448. package/presets/mavis/next/team/upstream/signatures.json +0 -9
  449. package/presets/opencode/next/commands/upstream-research.md +0 -26
  450. package/presets/opencode/next/team/upstream/config.json +0 -31
  451. package/presets/opencode/next/team/upstream/digest-template.md +0 -55
  452. package/presets/opencode/next/team/upstream/jobs.json +0 -34
  453. package/presets/opencode/next/team/upstream/opencode.json +0 -34
  454. package/presets/opencode/next/team/upstream/projects.json +0 -4
  455. package/presets/opencode/next/team/upstream/prompt.md +0 -77
  456. package/presets/opencode/next/team/upstream/signatures.json +0 -9
  457. package/presets/zcode/next/commands/upstream-research.md +0 -26
  458. package/presets/zcode/next/team/upstream/config.json +0 -31
  459. package/presets/zcode/next/team/upstream/digest-template.md +0 -55
  460. package/presets/zcode/next/team/upstream/jobs.json +0 -34
  461. package/presets/zcode/next/team/upstream/opencode.json +0 -34
  462. package/presets/zcode/next/team/upstream/projects.json +0 -4
  463. package/presets/zcode/next/team/upstream/prompt.md +0 -77
  464. package/presets/zcode/next/team/upstream/signatures.json +0 -9
@@ -1,20 +1,21 @@
1
1
  /**
2
- * The file-authoritative backlog store for `.ai.local/team/backlog/**`:
3
- * items, the launch queue, the deterministic eligibility order and the import
4
- * envelope.
2
+ * The file-authoritative tracker store for `.ai.local/team/tracker/**`:
3
+ * items, links, the launch queue, the deterministic eligibility order and the
4
+ * import envelope.
5
5
  *
6
6
  * Files are authoritative and this module is the only writer of
7
- * `backlog/items/*.json` and `backlog/queue/*.json` (I-1, I-2). The store is
7
+ * `tracker/items/*.json`, `tracker/links/*.json` and `tracker/queue/*.json`
8
+ * (I-1, I-2). The store is
8
9
  * file-only by design: no verb here opens a database, so the kill switch
9
- * (`AI_RULES_TEAM_DB_DISABLE=1`) never disables a backlog write — it stops the
10
- * projection only (R3-7). A write verb projects afterwards on a best-effort
11
- * bounded child so the read-only API sees fresh rows; a projection failure
12
- * never fails the write.
10
+ * (`AI_RULES_TEAM_DB_DISABLE=1`) never disables a tracker write — it stops the
11
+ * projection only (R3-7). The `team-db.mjs` wrapper projects the tracker store after a write so the
12
+ * read-only API sees fresh rows; a projection failure never fails the write.
13
13
  *
14
- * The stored status lattice (`planned|completed|cancelled|superseded`) is the
15
- * only decision recorded; every operational status (`effectiveStatus`) is
16
- * derived from the item, the queue entries and the hook-owned task state, and
17
- * is never written to a file (I-3). `rank(item) = priority ASC → createdAt ASC
14
+ * The stored status lattice
15
+ * (`backlog|planned|completed|cancelled|superseded`) is the only decision
16
+ * recorded; every operational status (`effectiveStatus`) is derived from the
17
+ * item, the links, the queue entries and the hook-owned task state, and is
18
+ * never written to a file (I-3). `rank(item) = priority ASC → createdAt ASC
18
19
  * → id ASC` is a total order and the only order (I-4, D-4). This module never
19
20
  * writes a lifecycle, gate or metric file and never starts an agent run: the
20
21
  * hook stop seam consumes `drain --claim` and owns the launch (I-5, D-5).
@@ -23,27 +24,41 @@
23
24
  import crypto from 'node:crypto';
24
25
  import fs from 'node:fs';
25
26
  import path from 'node:path';
26
- import { fileURLToPath } from 'node:url';
27
- import { spawnSync } from 'node:child_process';
28
27
 
29
28
  import { DEFAULT_TEAM_ROOT, TeamDbError, teamDbFail } from './team-db-schema.mjs';
30
29
  import { acquireLock, releaseLock } from './lock.mjs';
31
30
 
32
- export const BACKLOG_DIR = 'backlog';
31
+ export const TRACKER_DIR = 'tracker';
32
+ /** The shipped store directory this one replaced; read once by `migrate-ids`. */
33
+ const LEGACY_TRACKER_DIR = 'backlog';
33
34
  export const ITEMS_DIR = 'items';
34
35
  export const QUEUE_DIR = 'queue';
36
+ export const LINKS_DIR = 'links';
35
37
  export const CONFIG_FILE = 'config.json';
36
38
 
37
39
  export const ITEM_SCHEMA_VERSION = 1;
38
40
  export const ENTRY_SCHEMA_VERSION = 1;
41
+ export const LINK_SCHEMA_VERSION = 1;
39
42
  export const CONFIG_SCHEMA_VERSION = 1;
40
43
 
41
- /** One grammar across `backlog id`, `tasks/<slug>/` and `params.slug` (D-2). */
42
- export const ITEM_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
44
+ /** Tracker item ids are positive integers assigned by the store. */
45
+ export const ITEM_ID_RE = /^[1-9][0-9]*$/;
46
+ /** The team-task slug grammar; the link carries a slug that may differ from the item id. */
47
+ export const TASK_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
43
48
  /** The scheduler's `RUN_ID_RE` shape, so one id grammar reads across the tree. */
44
49
  export const ENTRY_ID_RE = /^[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}$/;
45
50
 
46
- export const ITEM_STATUSES = ['planned', 'completed', 'cancelled', 'superseded'];
51
+ /** Parse a persisted or path item id into the one numeric representation. */
52
+ export const parseItemId = (value, label = 'item id') => {
53
+ const id = typeof value === 'number' ? value : /^[0-9]+$/.test(String(value)) ? Number(value) : NaN;
54
+ if (!Number.isInteger(id) || id < 1) reject('E_SCHEMA', `${label} must be a positive integer`);
55
+ return id;
56
+ };
57
+
58
+ export const LINK_DECISIONS = ['requested', 'stopped', 'unlinked'];
59
+ export const LINK_ROLES = ['primary', 'follow-up'];
60
+
61
+ export const ITEM_STATUSES = ['backlog', 'planned', 'completed', 'cancelled', 'superseded'];
47
62
  export const ITEM_TYPES = ['feature', 'bugfix', 'spike', 'chore', 'docs', 'refactor'];
48
63
  export const ENTRY_STATUSES = ['queued', 'claimed', 'cancelled', 'expired'];
49
64
 
@@ -61,9 +76,21 @@ export const ITEM_HISTORY_TYPES = new Set([
61
76
  ]);
62
77
  export const ENTRY_HISTORY_TYPES = new Set(['enqueued', 'claimed', 'released', 'cancelled', 'expired', 'recovered']);
63
78
 
64
- export const EFFECTIVE_ITEM_STATUSES = ['planned', 'queued', 'launched', 'completed', 'cancelled', 'superseded'];
79
+ export const EFFECTIVE_ITEM_STATUSES = ['backlog', 'planned', 'queued', 'launched', 'completed', 'cancelled', 'superseded'];
65
80
  export const EFFECTIVE_ENTRY_STATUSES = ['queued', 'claimed', 'active', 'done', 'cancelled', 'expired'];
66
81
 
82
+ /** The derived state of a link, never stored (the stored field is `decision`). */
83
+ export const EFFECTIVE_LINK_STATES = [
84
+ 'requested',
85
+ 'claimed',
86
+ 'active',
87
+ 'paused',
88
+ 'stopped',
89
+ 'completed',
90
+ 'failed',
91
+ 'unlinked',
92
+ ];
93
+
67
94
  /** WIP states that hold a launch slot; everything else is passive (R3-2). */
68
95
  export const HOLDING_TASK_STATES = new Set(['in_progress', 'awaiting_artifact_receipt', 'blocked']);
69
96
 
@@ -73,6 +100,9 @@ export const CLAIM_STALE_MS = 90 * 1000;
73
100
  export const FUTURE_CREATED_AT_SKEW_MS = 5 * 60 * 1000;
74
101
 
75
102
  export const MAX_TITLE_CHARS = 120;
103
+ export const MAX_TASK_SLUG_CHARS = 48;
104
+ export const MAX_PROMPT_BYTES = 64 * 1024;
105
+ export const MAX_LINK_HISTORY = 64;
76
106
  export const MAX_DESCRIPTION_CHARS = 2000;
77
107
  export const MAX_LABELS = 8;
78
108
  export const MAX_LABEL_CHARS = 32;
@@ -123,34 +153,56 @@ const capHistory = (history, max) => history.slice(Math.max(0, history.length -
123
153
 
124
154
  /* --------------------------------- paths ---------------------------------- */
125
155
 
126
- export const backlogPaths = (teamRoot) => {
127
- const root = path.join(teamRoot, BACKLOG_DIR);
156
+ export const trackerPaths = (teamRoot) => {
157
+ const root = path.join(teamRoot, TRACKER_DIR);
128
158
  return {
129
159
  root,
130
160
  items: path.join(root, ITEMS_DIR),
131
161
  queue: path.join(root, QUEUE_DIR),
162
+ links: path.join(root, LINKS_DIR),
132
163
  config: path.join(root, CONFIG_FILE),
133
164
  lock: path.join(root, '.lock'),
134
165
  };
135
166
  };
136
167
 
137
- export const itemFilePath = (teamRoot, id) => path.join(backlogPaths(teamRoot).items, `${id}.json`);
138
- export const entryFilePath = (teamRoot, entryId) => path.join(backlogPaths(teamRoot).queue, `${entryId}.json`);
168
+ export const itemFilePath = (teamRoot, id) => path.join(trackerPaths(teamRoot).items, `${id}.json`);
169
+ export const entryFilePath = (teamRoot, entryId) => path.join(trackerPaths(teamRoot).queue, `${entryId}.json`);
170
+ export const linkFilePath = (teamRoot, linkId) => path.join(trackerPaths(teamRoot).links, `${linkId}.json`);
171
+ export const linkPromptPath = (teamRoot, linkId) => path.join(trackerPaths(teamRoot).links, `${linkId}.md`);
172
+ export const linkIdOf = (itemId, taskSlug) => `${itemId}--${taskSlug}`;
173
+ export const sequenceFilePath = (teamRoot) => path.join(trackerPaths(teamRoot).root, 'sequence.json');
174
+ const idMigrationFilePath = (teamRoot) => path.join(trackerPaths(teamRoot).root, 'id-migration.json');
175
+
176
+ /** The monotonic item-id sequence; max(existing) covers a lost sequence file. */
177
+ const nextItemId = (teamRoot) => {
178
+ const current = listItemIds(teamRoot).reduce((max, id) => Math.max(max, id), 0);
179
+ let reserved = 0;
180
+ try {
181
+ const parsed = JSON.parse(fs.readFileSync(sequenceFilePath(teamRoot), 'utf8'));
182
+ if (Number.isInteger(parsed?.nextId) && parsed.nextId > 0) reserved = parsed.nextId;
183
+ } catch {
184
+ /* a missing or unreadable sequence falls back to the file maximum */
185
+ }
186
+ const nextId = Math.max(current + 1, reserved, 1);
187
+ writeAtomic(sequenceFilePath(teamRoot), `${JSON.stringify({ schemaVersion: 1, nextId: nextId + 1 }, null, 2)}\n`);
188
+ return nextId;
189
+ };
139
190
 
140
191
  /** Both directories are created on first write (`mkdir -p` inside the CLI). */
141
- const ensureBacklogDirs = (teamRoot) => {
142
- fs.mkdirSync(backlogPaths(teamRoot).items, { recursive: true });
143
- fs.mkdirSync(backlogPaths(teamRoot).queue, { recursive: true });
192
+ const ensureTrackerDirs = (teamRoot) => {
193
+ fs.mkdirSync(trackerPaths(teamRoot).items, { recursive: true });
194
+ fs.mkdirSync(trackerPaths(teamRoot).queue, { recursive: true });
195
+ fs.mkdirSync(trackerPaths(teamRoot).links, { recursive: true });
144
196
  };
145
197
 
146
- const withBacklogLock = (teamRoot, run) => {
147
- fs.mkdirSync(backlogPaths(teamRoot).root, { recursive: true });
148
- const lockPath = backlogPaths(teamRoot).lock;
198
+ const withTrackerLock = (teamRoot, run) => {
199
+ fs.mkdirSync(trackerPaths(teamRoot).root, { recursive: true });
200
+ const lockPath = trackerPaths(teamRoot).lock;
149
201
  let token = null;
150
202
  try {
151
203
  token = acquireLock(lockPath, { timeoutMs: 5000 });
152
204
  } catch (error) {
153
- teamDbFail('E_BACKLOG_BUSY', `could not take the backlog lock at ${lockPath}: ${error.message}`, 4);
205
+ teamDbFail('E_TRACKER_BUSY', `could not take the tracker lock at ${lockPath}: ${error.message}`, 4);
154
206
  }
155
207
  try {
156
208
  return run();
@@ -162,7 +214,17 @@ const withBacklogLock = (teamRoot, run) => {
162
214
  /* --------------------------------- reading -------------------------------- */
163
215
 
164
216
  export const listItemIds = (teamRoot) => {
165
- const dir = backlogPaths(teamRoot).items;
217
+ const dir = trackerPaths(teamRoot).items;
218
+ if (!fs.existsSync(dir)) return [];
219
+ return fs
220
+ .readdirSync(dir)
221
+ .filter((name) => name.endsWith('.json') && ITEM_ID_RE.test(name.slice(0, -'.json'.length)))
222
+ .map((name) => Number(name.slice(0, -'.json'.length)))
223
+ .sort((left, right) => left - right);
224
+ };
225
+
226
+ export const listEntryIds = (teamRoot) => {
227
+ const dir = trackerPaths(teamRoot).queue;
166
228
  if (!fs.existsSync(dir)) return [];
167
229
  return fs
168
230
  .readdirSync(dir)
@@ -171,8 +233,8 @@ export const listItemIds = (teamRoot) => {
171
233
  .sort();
172
234
  };
173
235
 
174
- export const listEntryIds = (teamRoot) => {
175
- const dir = backlogPaths(teamRoot).queue;
236
+ export const listLinkIds = (teamRoot) => {
237
+ const dir = trackerPaths(teamRoot).links;
176
238
  if (!fs.existsSync(dir)) return [];
177
239
  return fs
178
240
  .readdirSync(dir)
@@ -181,12 +243,32 @@ export const listEntryIds = (teamRoot) => {
181
243
  .sort();
182
244
  };
183
245
 
246
+ export const readLinkFile = (teamRoot, linkId) => {
247
+ try {
248
+ return JSON.parse(fs.readFileSync(linkFilePath(teamRoot, linkId), 'utf8'));
249
+ } catch (error) {
250
+ if (error.code === 'ENOENT') return null;
251
+ teamDbFail('E_SCHEMA', `tracker link ${linkId} is unreadable: ${error.message}`, 1);
252
+ }
253
+ return null;
254
+ };
255
+
256
+ export const readLinkPrompt = (teamRoot, linkId) => {
257
+ try {
258
+ return fs.readFileSync(linkPromptPath(teamRoot, linkId), 'utf8');
259
+ } catch (error) {
260
+ if (error.code === 'ENOENT') return null;
261
+ teamDbFail('E_SCHEMA', `tracker link prompt ${linkId} is unreadable: ${error.message}`, 1);
262
+ }
263
+ return null;
264
+ };
265
+
184
266
  export const readItemFile = (teamRoot, id) => {
185
267
  try {
186
268
  return JSON.parse(fs.readFileSync(itemFilePath(teamRoot, id), 'utf8'));
187
269
  } catch (error) {
188
270
  if (error.code === 'ENOENT') return null;
189
- teamDbFail('E_SCHEMA', `backlog item ${id} is unreadable: ${error.message}`, 1);
271
+ teamDbFail('E_SCHEMA', `tracker item ${id} is unreadable: ${error.message}`, 1);
190
272
  }
191
273
  return null;
192
274
  };
@@ -201,6 +283,16 @@ const readEntryFile = (teamRoot, entryId) => {
201
283
  return null;
202
284
  };
203
285
 
286
+ const listAllItemStems = (teamRoot) => {
287
+ const dir = trackerPaths(teamRoot).items;
288
+ if (!fs.existsSync(dir)) return [];
289
+ return fs
290
+ .readdirSync(dir)
291
+ .filter((name) => name.endsWith('.json'))
292
+ .map((name) => name.slice(0, -'.json'.length))
293
+ .sort();
294
+ };
295
+
204
296
  const readAllItems = (teamRoot) => {
205
297
  const items = new Map();
206
298
  for (const id of listItemIds(teamRoot)) {
@@ -210,6 +302,15 @@ const readAllItems = (teamRoot) => {
210
302
  return items;
211
303
  };
212
304
 
305
+ const readAllItemsIncludingLegacy = (teamRoot) => {
306
+ const items = new Map();
307
+ for (const stem of listAllItemStems(teamRoot)) {
308
+ const item = readItemFile(teamRoot, stem);
309
+ if (item) items.set(item.id ?? stem, item);
310
+ }
311
+ return items;
312
+ };
313
+
213
314
  const readAllEntries = (teamRoot) => {
214
315
  const entries = new Map();
215
316
  for (const entryId of listEntryIds(teamRoot)) {
@@ -219,13 +320,22 @@ const readAllEntries = (teamRoot) => {
219
320
  return entries;
220
321
  };
221
322
 
323
+ const readAllLinks = (teamRoot) => {
324
+ const links = new Map();
325
+ for (const linkId of listLinkIds(teamRoot)) {
326
+ const link = readLinkFile(teamRoot, linkId);
327
+ if (link) links.set(linkId, link);
328
+ }
329
+ return links;
330
+ };
331
+
222
332
  /** The hook-owned `state` of every `tasks/<slug>/status.json`, read once. */
223
333
  export const readTaskStates = (teamRoot) => {
224
334
  const states = new Map();
225
335
  const tasksDir = path.join(teamRoot, 'tasks');
226
336
  if (!fs.existsSync(tasksDir)) return states;
227
337
  for (const entry of fs.readdirSync(tasksDir, { withFileTypes: true })) {
228
- if (!entry.isDirectory() || !ITEM_ID_RE.test(entry.name)) continue;
338
+ if (!entry.isDirectory() || !TASK_SLUG_RE.test(entry.name)) continue;
229
339
  try {
230
340
  const status = JSON.parse(fs.readFileSync(path.join(tasksDir, entry.name, 'status.json'), 'utf8'));
231
341
  if (isRecord(status) && typeof status.state === 'string') states.set(entry.name, status.state);
@@ -238,27 +348,27 @@ export const readTaskStates = (teamRoot) => {
238
348
 
239
349
  /* ------------------------------- configuration ---------------------------- */
240
350
 
241
- export function validateBacklogConfig(config) {
351
+ export function validateTrackerConfig(config) {
242
352
  if (!isRecord(config) || config.schemaVersion !== CONFIG_SCHEMA_VERSION) {
243
- reject('E_SCHEMA', `backlog config.json: schemaVersion must be ${CONFIG_SCHEMA_VERSION}`, 1);
353
+ reject('E_SCHEMA', `tracker config.json: schemaVersion must be ${CONFIG_SCHEMA_VERSION}`, 1);
244
354
  }
245
355
  if (!Number.isInteger(config.maxActive) || config.maxActive < MAX_ACTIVE_MIN || config.maxActive > MAX_ACTIVE_MAX) {
246
- reject('E_SCHEMA', `backlog config.json: maxActive must be an integer between ${MAX_ACTIVE_MIN} and ${MAX_ACTIVE_MAX}`, 1);
356
+ reject('E_SCHEMA', `tracker config.json: maxActive must be an integer between ${MAX_ACTIVE_MIN} and ${MAX_ACTIVE_MAX}`, 1);
247
357
  }
248
358
  return config;
249
359
  }
250
360
 
251
361
  /** Operator-edited like `scheduler/jobs.json`; absent means the default. */
252
- export const readBacklogConfig = (teamRoot) => {
253
- const file = backlogPaths(teamRoot).config;
362
+ export const readTrackerConfig = (teamRoot) => {
363
+ const file = trackerPaths(teamRoot).config;
254
364
  if (!fs.existsSync(file)) return { schemaVersion: CONFIG_SCHEMA_VERSION, maxActive: DEFAULT_MAX_ACTIVE };
255
365
  let config;
256
366
  try {
257
367
  config = JSON.parse(fs.readFileSync(file, 'utf8'));
258
368
  } catch (error) {
259
- teamDbFail('E_SCHEMA', `backlog config.json is not valid JSON: ${error.message}`, 1);
369
+ teamDbFail('E_SCHEMA', `tracker config.json is not valid JSON: ${error.message}`, 1);
260
370
  }
261
- return validateBacklogConfig(config);
371
+ return validateTrackerConfig(config);
262
372
  };
263
373
 
264
374
  /* -------------------------------- validation ------------------------------ */
@@ -274,13 +384,13 @@ const validateNullableTimestamp = (item, field, value) => {
274
384
  * identity → graph; the first failure wins (the frozen outcome table).
275
385
  */
276
386
  export function validateItemSchema(item) {
277
- if (!isRecord(item)) reject('E_SCHEMA', 'backlog item must be an object');
387
+ if (!isRecord(item)) reject('E_SCHEMA', 'tracker item must be an object');
278
388
  if (item.schemaVersion !== ITEM_SCHEMA_VERSION) {
279
389
  reject('E_SCHEMA', `item ${item.id ?? '?'}: schemaVersion must be ${ITEM_SCHEMA_VERSION}`);
280
390
  }
281
391
  const id = item.id;
282
- if (typeof id !== 'string' || !ITEM_ID_RE.test(id) || id.length < 3 || id.length > 64) {
283
- reject('E_SCHEMA', `item id must match ${ITEM_ID_RE.source} with 3-64 characters`);
392
+ if (!Number.isInteger(id) || id < 1) {
393
+ reject('E_SCHEMA', 'item id must be a positive integer');
284
394
  }
285
395
  if (!Number.isInteger(item.revision) || item.revision < 1) {
286
396
  reject('E_SCHEMA', `item ${id}: revision must be an integer >= 1`);
@@ -316,8 +426,8 @@ export function validateItemSchema(item) {
316
426
  if (item.cancelReason !== null && !(typeof item.cancelReason === 'string' && item.cancelReason.length >= 1 && item.cancelReason.length <= MAX_CANCEL_REASON_CHARS)) {
317
427
  reject('E_SCHEMA', `item ${id}: cancelReason must be 1-${MAX_CANCEL_REASON_CHARS} characters`);
318
428
  }
319
- if (item.supersededBy !== null && !(typeof item.supersededBy === 'string' && ITEM_ID_RE.test(item.supersededBy))) {
320
- reject('E_SCHEMA', `item ${id}: supersededBy must match ${ITEM_ID_RE.source}`);
429
+ if (item.supersededBy !== null && (!Number.isInteger(item.supersededBy) || item.supersededBy < 1)) {
430
+ reject('E_SCHEMA', `item ${id}: supersededBy must be a positive integer`);
321
431
  }
322
432
  if (item.status === 'superseded' && item.supersededBy === null) {
323
433
  reject('E_SCHEMA', `item ${id}: supersededBy is required when status is superseded`);
@@ -329,15 +439,15 @@ export function validateItemSchema(item) {
329
439
  reject('E_SCHEMA', `item ${id}: dependsOn must not contain duplicates`);
330
440
  }
331
441
  for (const dep of item.dependsOn) {
332
- if (typeof dep !== 'string' || !ITEM_ID_RE.test(dep)) {
333
- reject('E_SCHEMA', `item ${id}: dependency "${String(dep)}" must match ${ITEM_ID_RE.source}`);
442
+ if (!Number.isInteger(dep) || dep < 1) {
443
+ reject('E_SCHEMA', `item ${id}: dependency "${String(dep)}" must be a positive integer`);
334
444
  }
335
445
  }
336
446
  if (!Number.isInteger(item.priority) || item.priority < 0 || item.priority > 9) {
337
447
  reject('E_SCHEMA', `item ${id}: priority must be an integer between 0 and 9`);
338
448
  }
339
- if (item.sourceTask !== null && !(typeof item.sourceTask === 'string' && ITEM_ID_RE.test(item.sourceTask))) {
340
- reject('E_SCHEMA', `item ${id}: sourceTask must match ${ITEM_ID_RE.source}`);
449
+ if (item.sourceTask !== null && !(typeof item.sourceTask === 'string' && TASK_SLUG_RE.test(item.sourceTask))) {
450
+ reject('E_SCHEMA', `item ${id}: sourceTask must match ${TASK_SLUG_RE.source}`);
341
451
  }
342
452
  if (!Array.isArray(item.sourceRefs) || item.sourceRefs.length > MAX_SOURCE_REFS) {
343
453
  reject('E_SCHEMA', `item ${id}: sourceRefs must be an array of at most ${MAX_SOURCE_REFS} refs`);
@@ -381,8 +491,8 @@ const validateHistoryEvent = (where, event, types) => {
381
491
 
382
492
  /** Identity phase: the file stem is the id (one file per id, D-2). */
383
493
  export function validateItemIdentity(item, fileStem) {
384
- if (item.id !== fileStem) {
385
- reject('E_BACKLOG_DUPLICATE_ID', `item file "${fileStem}.json" holds id "${item.id}"`);
494
+ if (!ITEM_ID_RE.test(String(fileStem)) || Number(fileStem) !== item.id) {
495
+ reject('E_TRACKER_DUPLICATE_ID', `item file "${fileStem}.json" holds id "${item.id}"`);
386
496
  }
387
497
  }
388
498
 
@@ -411,14 +521,14 @@ export function validateItemGraph(item, itemsById) {
411
521
  const merged = new Map(itemsById);
412
522
  merged.set(item.id, item);
413
523
  for (const dep of item.dependsOn ?? []) {
414
- if (dep === item.id) reject('E_BACKLOG_SELF_DEP', `item ${item.id}: dependsOn contains itself`);
415
- if (!merged.has(dep)) reject('E_BACKLOG_UNKNOWN_DEP', `item ${item.id}: dependency "${dep}" has no item file`);
524
+ if (dep === item.id) reject('E_TRACKER_SELF_DEP', `item ${item.id}: dependsOn contains itself`);
525
+ if (!merged.has(dep)) reject('E_TRACKER_UNKNOWN_DEP', `item ${item.id}: dependency "${dep}" has no item file`);
416
526
  }
417
527
  if (item.supersededBy !== null && !merged.has(item.supersededBy)) {
418
- reject('E_BACKLOG_UNKNOWN_DEP', `item ${item.id}: supersededBy "${item.supersededBy}" has no item file`);
528
+ reject('E_TRACKER_UNKNOWN_DEP', `item ${item.id}: supersededBy "${item.supersededBy}" has no item file`);
419
529
  }
420
530
  if (detectsCycleThrough(item.id, merged)) {
421
- reject('E_BACKLOG_CYCLE', `item ${item.id}: dependsOn contains a cycle`);
531
+ reject('E_TRACKER_CYCLE', `item ${item.id}: dependsOn contains a cycle`);
422
532
  }
423
533
  }
424
534
 
@@ -426,14 +536,14 @@ export function validateItemGraph(item, itemsById) {
426
536
  * The stored lattice: planned → completed (reopen back to planned), planned →
427
537
  * cancelled, planned → superseded. Terminal statuses never leave. A cancelled
428
538
  * item needs its `cancelReason` (the frozen outcome table folds this into
429
- * `E_BACKLOG_TRANSITION`).
539
+ * `E_TRACKER_TRANSITION`).
430
540
  */
431
541
  export function validateTransition(existing, next) {
432
542
  const from = existing?.status ?? null;
433
543
  const to = next.status;
434
544
  const needsReason = () => {
435
545
  if (to === 'cancelled' && !(typeof next.cancelReason === 'string' && next.cancelReason.length >= 1)) {
436
- reject('E_BACKLOG_TRANSITION', `item ${next.id}: a cancelled item needs cancelReason`);
546
+ reject('E_TRACKER_TRANSITION', `item ${next.id}: a cancelled item needs cancelReason`);
437
547
  }
438
548
  };
439
549
  if (from === null) {
@@ -445,13 +555,14 @@ export function validateTransition(existing, next) {
445
555
  return;
446
556
  }
447
557
  const legal = {
448
- planned: new Set(['planned', 'completed', 'cancelled', 'superseded']),
449
- completed: new Set(['planned']),
558
+ backlog: new Set(['backlog', 'planned', 'completed', 'cancelled', 'superseded']),
559
+ planned: new Set(['backlog', 'planned', 'completed', 'cancelled', 'superseded']),
560
+ completed: new Set(['backlog', 'planned']),
450
561
  cancelled: new Set(),
451
562
  superseded: new Set(),
452
563
  };
453
564
  if (!legal[from]?.has(to)) {
454
- reject('E_BACKLOG_TRANSITION', `item ${next.id}: transition ${from} -> ${to} is outside the stored lattice`);
565
+ reject('E_TRACKER_TRANSITION', `item ${next.id}: transition ${from} -> ${to} is outside the stored lattice`);
455
566
  }
456
567
  needsReason();
457
568
  }
@@ -466,8 +577,18 @@ export function validateEntrySchema(entry) {
466
577
  if (typeof entry.entryId !== 'string' || !ENTRY_ID_RE.test(entry.entryId)) {
467
578
  reject('E_SCHEMA', `entry id must match ${ENTRY_ID_RE.source}`);
468
579
  }
469
- if (typeof entry.itemId !== 'string' || !ITEM_ID_RE.test(entry.itemId)) {
470
- reject('E_SCHEMA', `entry ${entry.entryId}: itemId must match ${ITEM_ID_RE.source}`);
580
+ if (!Number.isInteger(entry.itemId) || entry.itemId < 1) {
581
+ reject('E_SCHEMA', `entry ${entry.entryId}: itemId must be a positive integer`);
582
+ }
583
+ if (entry.taskSlug !== undefined && entry.taskSlug !== null) {
584
+ if (typeof entry.taskSlug !== 'string' || !TASK_SLUG_RE.test(entry.taskSlug) || entry.taskSlug.length > MAX_TASK_SLUG_CHARS) {
585
+ reject('E_SCHEMA', `entry ${entry.entryId}: taskSlug must match ${TASK_SLUG_RE.source} with 3-${MAX_TASK_SLUG_CHARS} characters`);
586
+ }
587
+ }
588
+ if (entry.linkId !== undefined && entry.linkId !== null) {
589
+ if (typeof entry.linkId !== 'string' || entry.linkId.length > 160) {
590
+ reject('E_SCHEMA', `entry ${entry.entryId}: linkId must be null or <itemId>--<taskSlug>`);
591
+ }
471
592
  }
472
593
  if (!ENTRY_STATUSES.includes(entry.status)) {
473
594
  reject('E_SCHEMA', `entry ${entry.entryId}: status must be one of ${ENTRY_STATUSES.join('|')}`);
@@ -506,6 +627,70 @@ export function validateEntrySchema(entry) {
506
627
  return entry;
507
628
  }
508
629
 
630
+ /* ------------------------------- link schema ------------------------------ */
631
+
632
+ const LINK_ID_RE = /^[1-9][0-9]*--[a-z0-9]+(?:-[a-z0-9]+)*$/;
633
+
634
+ export function validateLinkSchema(link) {
635
+ if (!isRecord(link)) reject('E_SCHEMA', 'tracker link must be an object');
636
+ if (link.schemaVersion !== LINK_SCHEMA_VERSION) {
637
+ reject('E_SCHEMA', `link ${link.linkId ?? '?'}: schemaVersion must be ${LINK_SCHEMA_VERSION}`);
638
+ }
639
+ if (typeof link.linkId !== 'string' || !LINK_ID_RE.test(link.linkId) || link.linkId.length > 160) {
640
+ reject('E_SCHEMA', `link ${link.linkId ?? '?'}: linkId must be <itemId>--<taskSlug>`);
641
+ }
642
+ if (!Number.isInteger(link.itemId) || link.itemId < 1) {
643
+ reject('E_SCHEMA', `link ${link.linkId}: itemId must be a positive integer`);
644
+ }
645
+ if (typeof link.taskSlug !== 'string' || !TASK_SLUG_RE.test(link.taskSlug) || link.taskSlug.length > MAX_TASK_SLUG_CHARS) {
646
+ reject('E_SCHEMA', `link ${link.linkId}: taskSlug must match ${TASK_SLUG_RE.source} with 3-${MAX_TASK_SLUG_CHARS} characters`);
647
+ }
648
+ if (link.linkId !== linkIdOf(link.itemId, link.taskSlug)) {
649
+ reject('E_SCHEMA', `link ${link.linkId}: linkId must be "${linkIdOf(link.itemId, link.taskSlug)}"`);
650
+ }
651
+ if (link.entryId !== null && (typeof link.entryId !== 'string' || !ENTRY_ID_RE.test(link.entryId))) {
652
+ reject('E_SCHEMA', `link ${link.linkId}: entryId must be null or a queue entry id`);
653
+ }
654
+ if (!LINK_ROLES.includes(link.role)) {
655
+ reject('E_SCHEMA', `link ${link.linkId}: role must be one of ${LINK_ROLES.join('|')}`);
656
+ }
657
+ if (!LINK_DECISIONS.includes(link.decision)) {
658
+ reject('E_SCHEMA', `link ${link.linkId}: decision must be one of ${LINK_DECISIONS.join('|')}`);
659
+ }
660
+ if (
661
+ link.promptPath !== null &&
662
+ !(typeof link.promptPath === 'string' && link.promptPath.startsWith(`${TRACKER_DIR}/${LINKS_DIR}/`) && !link.promptPath.includes('..'))
663
+ ) {
664
+ reject('E_SCHEMA', `link ${link.linkId}: promptPath must stay under ${TRACKER_DIR}/${LINKS_DIR}/`);
665
+ }
666
+ if (link.language !== null && !(typeof link.language === 'string' && link.language.length >= 2 && link.language.length <= 16)) {
667
+ reject('E_SCHEMA', `link ${link.linkId}: language must be null or a 2-16 character tag`);
668
+ }
669
+ if (!Number.isInteger(link.revision) || link.revision < 1) {
670
+ reject('E_SCHEMA', `link ${link.linkId}: revision must be an integer >= 1`);
671
+ }
672
+ if (!isIsoZ(link.createdAt)) reject('E_SCHEMA', `link ${link.linkId}: createdAt must be an RFC 3339 timestamp ending in Z`);
673
+ if (!isIsoZ(link.updatedAt)) reject('E_SCHEMA', `link ${link.linkId}: updatedAt must be an RFC 3339 timestamp ending in Z`);
674
+ if (Date.parse(link.updatedAt) < Date.parse(link.createdAt)) {
675
+ reject('E_SCHEMA', `link ${link.linkId}: updatedAt must be >= createdAt`);
676
+ }
677
+ if (!Array.isArray(link.history) || link.history.length > MAX_LINK_HISTORY) {
678
+ reject('E_SCHEMA', `link ${link.linkId}: history must be an array capped at ${MAX_LINK_HISTORY}`);
679
+ }
680
+ for (const event of link.history) {
681
+ if (!isRecord(event) || !isIsoZ(event.at) || typeof event.type !== 'string' || typeof event.actor !== 'string') {
682
+ reject('E_SCHEMA', `link ${link.linkId}: every history event needs at, type and actor`);
683
+ }
684
+ }
685
+ return link;
686
+ }
687
+
688
+ export function validateLinkIdentity(link, fileStem) {
689
+ if (link.linkId !== fileStem) {
690
+ reject('E_TRACKER_LINK_ID', `link file "${fileStem}.json" holds linkId "${link.linkId}"`);
691
+ }
692
+ }
693
+
509
694
  /* ------------------------------ file writes ------------------------------- */
510
695
 
511
696
  const writeAtomic = (file, content) => {
@@ -515,15 +700,25 @@ const writeAtomic = (file, content) => {
515
700
  };
516
701
 
517
702
  const writeItemFile = (teamRoot, item) => {
518
- ensureBacklogDirs(teamRoot);
703
+ ensureTrackerDirs(teamRoot);
519
704
  writeAtomic(itemFilePath(teamRoot, item.id), `${JSON.stringify(item, null, 2)}\n`);
520
705
  };
521
706
 
522
707
  const writeEntryFile = (teamRoot, entry) => {
523
- ensureBacklogDirs(teamRoot);
708
+ ensureTrackerDirs(teamRoot);
524
709
  writeAtomic(entryFilePath(teamRoot, entry.entryId), `${JSON.stringify(entry, null, 2)}\n`);
525
710
  };
526
711
 
712
+ const writeLinkFile = (teamRoot, link) => {
713
+ ensureTrackerDirs(teamRoot);
714
+ writeAtomic(linkFilePath(teamRoot, link.linkId), `${JSON.stringify(link, null, 2)}\n`);
715
+ };
716
+
717
+ const writeLinkPrompt = (teamRoot, linkId, prompt) => {
718
+ ensureTrackerDirs(teamRoot);
719
+ writeAtomic(linkPromptPath(teamRoot, linkId), prompt);
720
+ };
721
+
527
722
  /** The scheduler's `newRunId` shape — duplicated so the queue stays file-only. */
528
723
  export const newEntryId = () => {
529
724
  const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z');
@@ -533,10 +728,22 @@ export const newEntryId = () => {
533
728
  /* ---------------------------- derived statuses ---------------------------- */
534
729
 
535
730
  /** The stored decision lattice plus the derived operational status (I-3). */
536
- export const effectiveItemStatus = (item, taskState, nonTerminalEntryExists) => {
731
+ export const effectiveItemStatus = (item, taskState, nonTerminalEntryExists, links = [], taskStates = new Map()) => {
537
732
  if (item.status === 'cancelled') return 'cancelled';
538
733
  if (item.status === 'superseded') return 'superseded';
539
- if (item.status === 'completed' || taskState === 'completed') return 'completed';
734
+ if (item.status === 'completed') return 'completed';
735
+ if (links.length > 0) {
736
+ const states = links.map((link) => effectiveLinkState(link, null, taskStates.get(link.taskSlug) ?? null));
737
+ if (states.every((state) => state === 'completed')) return 'completed';
738
+ if (states.some((state) => ['active', 'paused', 'claimed'].includes(state))) return 'launched';
739
+ if (states.some((state) => state === 'requested')) return 'queued';
740
+ if (states.every((state) => ['stopped', 'unlinked'].includes(state))) {
741
+ if (nonTerminalEntryExists) return 'queued';
742
+ return item.status === 'backlog' ? 'backlog' : 'planned';
743
+ }
744
+ }
745
+ if (taskState === 'completed') return 'completed';
746
+ if (item.status === 'backlog') return 'backlog';
540
747
  if (taskState !== null) return 'launched';
541
748
  if (nonTerminalEntryExists) return 'queued';
542
749
  return 'planned';
@@ -551,8 +758,39 @@ export const effectiveEntryStatus = (entry, taskState) => {
551
758
  return 'queued';
552
759
  };
553
760
 
761
+ /**
762
+ * The derived state of one link.
763
+ *
764
+ * The stored decision wins only for a stop/unlink the operator made. A task
765
+ * row, when present, is the stronger signal: completed/active/paused. An open
766
+ * queue entry means the request is still waiting for the hook.
767
+ */
768
+ export const effectiveLinkState = (link, entry, taskState) => {
769
+ if (link.decision === 'unlinked') return 'unlinked';
770
+ if (link.decision === 'stopped') return 'stopped';
771
+ if (taskState === 'completed') return 'completed';
772
+ if (taskState === 'paused') return 'paused';
773
+ if (taskState !== null) return 'active';
774
+ if (entry !== null && entry !== undefined) {
775
+ if (entry.status === 'claimed') return 'claimed';
776
+ if (entry.status === 'queued') return 'requested';
777
+ }
778
+ return 'requested';
779
+ };
780
+
554
781
  const isNonTerminalEntryStatus = (status) => !['cancelled', 'expired', 'done'].includes(status);
555
782
 
783
+ /** Collapse the linked task states into the item's display state. */
784
+ const aggregateTaskState = (states, linkCount, legacyState) => {
785
+ if (legacyState !== null) return legacyState;
786
+ if (linkCount === 0 || states.length === 0) return null;
787
+ if (states.every((state) => state === 'completed')) return 'completed';
788
+ const holding = states.find((state) => HOLDING_TASK_STATES.has(state));
789
+ if (holding !== undefined) return holding;
790
+ if (states.includes('paused')) return 'paused';
791
+ return states[0];
792
+ };
793
+
556
794
  /* ------------------------------- ordering --------------------------------- */
557
795
 
558
796
  /** The total order comparator: `priority ASC → createdAt ASC → id ASC` (R-3). */
@@ -562,16 +800,23 @@ export const rankCompare = (left, right) =>
562
800
  (left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
563
801
 
564
802
  /**
565
- * One snapshot, one pass (D-4, R-1…R-6). Feed this the item, queue and task
566
- * records the caller read once — files on the CLI path, projected rows on the
567
- * API path — so the CLI and the SQL read plane can never disagree. No wall
803
+ * One snapshot, one pass (D-4, R-1…R-6). Feed this the item, queue, link and
804
+ * task records the caller read once — files on the CLI path, projected rows on
805
+ * the API path — so the CLI and the SQL read plane can never disagree. No wall
568
806
  * clock, readdir order or database row order may influence the output.
569
807
  */
570
- export function deriveBacklogOrdering({ items, entries, taskStates, asOf }) {
808
+ export function deriveTrackerOrdering({ items, entries, links = new Map(), taskStates, asOf }) {
571
809
  const byId = new Map();
810
+ const linksByItem = new Map();
811
+ for (const link of links.values()) {
812
+ const list = linksByItem.get(link.itemId) ?? [];
813
+ list.push(link);
814
+ linksByItem.set(link.itemId, list);
815
+ }
816
+ const entryTaskSlug = (entry) => entry.taskSlug ?? `tracker-${entry.itemId}`;
572
817
  const entryStatuses = new Map();
573
818
  for (const [entryId, entry] of entries) {
574
- entryStatuses.set(entryId, effectiveEntryStatus(entry, taskStates.get(entry.itemId) ?? null));
819
+ entryStatuses.set(entryId, effectiveEntryStatus(entry, taskStates.get(entryTaskSlug(entry)) ?? null));
575
820
  }
576
821
  const openEntriesByItem = new Map();
577
822
  for (const [entryId, entry] of entries) {
@@ -582,11 +827,17 @@ export function deriveBacklogOrdering({ items, entries, taskStates, asOf }) {
582
827
  openEntriesByItem.set(entry.itemId, list);
583
828
  }
584
829
  for (const [id, item] of items) {
585
- const taskState = taskStates.get(id) ?? null;
830
+ const itemLinks = linksByItem.get(id) ?? [];
831
+ const statusLinks = itemLinks.filter((link) => link.decision !== 'unlinked');
832
+ const linkedStates = statusLinks
833
+ .map((link) => taskStates.get(link.taskSlug) ?? null)
834
+ .filter((state) => state !== null);
835
+ const legacyState = statusLinks.length === 0 ? (taskStates.get(String(id)) ?? null) : null;
836
+ const taskState = aggregateTaskState(linkedStates, statusLinks.length, legacyState);
586
837
  const openEntries = openEntriesByItem.get(id) ?? [];
587
838
  const openEntryId = openEntries.length > 0 ? openEntries.sort()[0] : null;
588
839
  const openEntry = openEntryId !== null ? entries.get(openEntryId) : null;
589
- const effectiveStatus = effectiveItemStatus(item, taskState, openEntryId !== null);
840
+ const effectiveStatus = effectiveItemStatus(item, taskState, openEntryId !== null, statusLinks, taskStates);
590
841
  byId.set(id, {
591
842
  item,
592
843
  effectiveStatus,
@@ -594,6 +845,7 @@ export function deriveBacklogOrdering({ items, entries, taskStates, asOf }) {
594
845
  openEntry,
595
846
  queueEntryId: openEntryId,
596
847
  queuedAt: openEntry?.requestedAt ?? null,
848
+ links: itemLinks,
597
849
  ready: false,
598
850
  blocked: false,
599
851
  waitingOn: [],
@@ -636,7 +888,7 @@ export function deriveBacklogOrdering({ items, entries, taskStates, asOf }) {
636
888
  const computeCriticalPathIds = (items, byId) => {
637
889
  const openIds = new Set(
638
890
  [...byId.values()]
639
- .filter((annotated) => ['planned', 'queued', 'launched'].includes(annotated.effectiveStatus))
891
+ .filter((annotated) => ['backlog', 'planned', 'queued', 'launched'].includes(annotated.effectiveStatus))
640
892
  .map((annotated) => annotated.item.id),
641
893
  );
642
894
  const memo = new Map();
@@ -664,9 +916,9 @@ const computeCriticalPathIds = (items, byId) => {
664
916
  return best;
665
917
  };
666
918
 
667
- /** Read the whole backlog tree once, under the tree lock (R-4). */
668
- export function readBacklogSnapshot(teamRoot) {
669
- return withBacklogLock(teamRoot, () => {
919
+ /** Read the whole tracker tree once, under the tree lock (R-4). */
920
+ export function readTrackerSnapshot(teamRoot) {
921
+ return withTrackerLock(teamRoot, () => {
670
922
  const asOf = nowIso();
671
923
  const items = new Map();
672
924
  const entries = new Map();
@@ -675,17 +927,25 @@ export function readBacklogSnapshot(teamRoot) {
675
927
  try {
676
928
  items.set(id, JSON.parse(fs.readFileSync(itemFilePath(teamRoot, id), 'utf8')));
677
929
  } catch (error) {
678
- errors.push({ path: `backlog/items/${id}.json`, reason: error.message });
930
+ errors.push({ path: `tracker/items/${id}.json`, reason: error.message });
679
931
  }
680
932
  }
681
933
  for (const entryId of listEntryIds(teamRoot)) {
682
934
  try {
683
935
  entries.set(entryId, JSON.parse(fs.readFileSync(entryFilePath(teamRoot, entryId), 'utf8')));
684
936
  } catch (error) {
685
- errors.push({ path: `backlog/queue/${entryId}.json`, reason: error.message });
937
+ errors.push({ path: `tracker/queue/${entryId}.json`, reason: error.message });
686
938
  }
687
939
  }
688
- return { asOf, items, entries, taskStates: readTaskStates(teamRoot), errors };
940
+ const links = new Map();
941
+ for (const linkId of listLinkIds(teamRoot)) {
942
+ try {
943
+ links.set(linkId, JSON.parse(fs.readFileSync(linkFilePath(teamRoot, linkId), 'utf8')));
944
+ } catch (error) {
945
+ errors.push({ path: `tracker/links/${linkId}.json`, reason: error.message });
946
+ }
947
+ }
948
+ return { asOf, items, entries, links, taskStates: readTaskStates(teamRoot), errors };
689
949
  });
690
950
  }
691
951
 
@@ -699,20 +959,11 @@ export const countActiveTasks = (taskStates) => {
699
959
 
700
960
  /* ------------------------------- item writes ------------------------------ */
701
961
 
702
- export function addBacklogItem(teamRoot, payload, options = {}) {
703
- if (!isRecord(payload)) reject('E_SCHEMA', 'backlog add payload must be an object');
704
- return withBacklogLock(teamRoot, () => {
962
+ export function addTrackerItem(teamRoot, payload, options = {}) {
963
+ if (!isRecord(payload)) reject('E_SCHEMA', 'tracker add payload must be an object');
964
+ return withTrackerLock(teamRoot, () => {
705
965
  const items = readAllItems(teamRoot);
706
- const id = payload.id;
707
- if (typeof id !== 'string' || !ITEM_ID_RE.test(id) || id.length < 3 || id.length > 64) {
708
- reject('E_SCHEMA', `item id must match ${ITEM_ID_RE.source} with 3-64 characters`);
709
- }
710
- if (items.has(id)) reject('E_BACKLOG_DUPLICATE_ID', `item "${id}" already exists`);
711
- // D-2: the id becomes the `/task` slug; an id that already names a task
712
- // folder this item did not create is a collision.
713
- if (fs.existsSync(path.join(teamRoot, 'tasks', id))) {
714
- reject('E_ID_COLLISION', `id "${id}" already names a tasks/${id}/ directory`);
715
- }
966
+ const id = nextItemId(teamRoot);
716
967
  const now = nowIso();
717
968
  const createdAt = payload.createdAt ?? now;
718
969
  const item = {
@@ -745,13 +996,14 @@ export function addBacklogItem(teamRoot, payload, options = {}) {
745
996
  });
746
997
  }
747
998
 
748
- export function setBacklogItem(teamRoot, id, payload, options = {}) {
749
- if (!isRecord(payload)) reject('E_SCHEMA', 'backlog set payload must be an object');
750
- return withBacklogLock(teamRoot, () => {
999
+ export function setTrackerItem(teamRoot, id, payload, options = {}) {
1000
+ if (!isRecord(payload)) reject('E_SCHEMA', 'tracker set payload must be an object');
1001
+ id = parseItemId(id, 'item id');
1002
+ return withTrackerLock(teamRoot, () => {
751
1003
  const existing = readItemFile(teamRoot, id);
752
- if (!existing) reject('E_BACKLOG_UNKNOWN_DEP', `no backlog item "${id}"`);
1004
+ if (!existing) reject('E_TRACKER_UNKNOWN_DEP', `no tracker item "${id}"`);
753
1005
  if (!Number.isInteger(payload.revision) || payload.revision !== existing.revision) {
754
- reject('E_BACKLOG_REVISION', `item ${id}: revision ${payload.revision ?? 'missing'} does not match the stored ${existing.revision}`);
1006
+ reject('E_TRACKER_REVISION', `item ${id}: revision ${payload.revision ?? 'missing'} does not match the stored ${existing.revision}`);
755
1007
  }
756
1008
  const next = { ...existing };
757
1009
  for (const key of ['title', 'status', 'priority', 'dependsOn', 'type', 'description', 'labels', 'completedAt', 'cancelledAt', 'cancelReason', 'supersededBy']) {
@@ -787,6 +1039,355 @@ export function setBacklogItem(teamRoot, id, payload, options = {}) {
787
1039
  });
788
1040
  }
789
1041
 
1042
+ /* ------------------------------- link writes ------------------------------ */
1043
+
1044
+ export function listLinksForItem(teamRoot, itemId) {
1045
+ itemId = parseItemId(itemId, 'itemId');
1046
+ return [...readAllLinks(teamRoot).values()]
1047
+ .filter((link) => link.itemId === itemId)
1048
+ .sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.linkId.localeCompare(right.linkId));
1049
+ }
1050
+
1051
+ export function addTrackerLink(teamRoot, payload, options = {}) {
1052
+ if (!isRecord(payload)) reject('E_SCHEMA', 'tracker link payload must be an object');
1053
+ return withTrackerLock(teamRoot, () => {
1054
+ const itemId = parseItemId(payload.itemId, 'itemId');
1055
+ const item = readItemFile(teamRoot, itemId);
1056
+ if (!item) reject('E_TRACKER_UNKNOWN_DEP', `no tracker item "${itemId}"`);
1057
+ if (item.status === 'cancelled' || item.status === 'superseded') {
1058
+ reject('E_TRACKER_TRANSITION', `item ${itemId} is ${item.status}; a task cannot be linked`);
1059
+ }
1060
+ const taskSlug = payload.taskSlug;
1061
+ if (typeof taskSlug !== 'string' || !TASK_SLUG_RE.test(taskSlug) || taskSlug.length < 3 || taskSlug.length > MAX_TASK_SLUG_CHARS) {
1062
+ reject('E_SCHEMA', `taskSlug must match ${TASK_SLUG_RE.source} with 3-${MAX_TASK_SLUG_CHARS} characters`);
1063
+ }
1064
+ const linkId = linkIdOf(itemId, taskSlug);
1065
+ if (readLinkFile(teamRoot, linkId)) {
1066
+ reject('E_TRACKER_LINK_EXISTS', `link ${linkId} already exists`);
1067
+ }
1068
+ const prompt = typeof payload.prompt === 'string' && payload.prompt.trim() !== ''
1069
+ ? payload.prompt
1070
+ : (item.description ?? item.title);
1071
+ if (Buffer.byteLength(prompt, 'utf8') > MAX_PROMPT_BYTES) {
1072
+ reject('E_SCHEMA', `link prompt must be at most ${MAX_PROMPT_BYTES} bytes`);
1073
+ }
1074
+ const language = payload.language ?? null;
1075
+ if (language !== null && !(typeof language === 'string' && language.length >= 2 && language.length <= 16)) {
1076
+ reject('E_SCHEMA', 'language must be null or a 2-16 character tag');
1077
+ }
1078
+ const now = nowIso();
1079
+ const link = {
1080
+ schemaVersion: LINK_SCHEMA_VERSION,
1081
+ linkId,
1082
+ itemId,
1083
+ taskSlug,
1084
+ entryId: payload.entryId ?? null,
1085
+ role: payload.role ?? 'primary',
1086
+ decision: 'requested',
1087
+ promptPath: `${TRACKER_DIR}/${LINKS_DIR}/${linkId}.md`,
1088
+ language,
1089
+ revision: 1,
1090
+ createdAt: now,
1091
+ updatedAt: now,
1092
+ history: [{ at: now, type: 'created', actor: options.actor ?? 'operator', detail: null }],
1093
+ };
1094
+ validateLinkSchema(link);
1095
+ validateLinkIdentity(link, linkId);
1096
+ writeLinkPrompt(teamRoot, linkId, prompt);
1097
+ writeLinkFile(teamRoot, link);
1098
+ return link;
1099
+ });
1100
+ }
1101
+
1102
+ export function setTrackerLink(teamRoot, linkId, payload, options = {}) {
1103
+ if (!isRecord(payload)) reject('E_SCHEMA', 'tracker link set payload must be an object');
1104
+ return withTrackerLock(teamRoot, () => {
1105
+ const existing = readLinkFile(teamRoot, linkId);
1106
+ if (!existing) reject('E_TRACKER_LINK_UNKNOWN', `no tracker link "${linkId}"`);
1107
+ if (payload.revision !== undefined && (!Number.isInteger(payload.revision) || payload.revision !== existing.revision)) {
1108
+ reject('E_TRACKER_REVISION', `link ${linkId}: revision ${payload.revision ?? 'missing'} does not match the stored ${existing.revision}`);
1109
+ }
1110
+ const next = { ...existing };
1111
+ for (const key of ['decision', 'entryId', 'role', 'language']) {
1112
+ if (payload[key] !== undefined) next[key] = payload[key];
1113
+ }
1114
+ if (payload.prompt !== undefined) {
1115
+ if (typeof payload.prompt !== 'string' || Buffer.byteLength(payload.prompt, 'utf8') > MAX_PROMPT_BYTES) {
1116
+ reject('E_SCHEMA', `link prompt must be a string of at most ${MAX_PROMPT_BYTES} bytes`);
1117
+ }
1118
+ writeLinkPrompt(teamRoot, linkId, payload.prompt);
1119
+ }
1120
+ const now = nowIso();
1121
+ next.revision = existing.revision + 1;
1122
+ next.updatedAt = now;
1123
+ const actor = options.actor ?? 'operator';
1124
+ const type = next.decision !== existing.decision
1125
+ ? (next.decision === 'stopped' ? 'stopped' : next.decision === 'unlinked' ? 'unlinked' : 'resumed')
1126
+ : 'updated';
1127
+ next.history = capHistory([...(existing.history ?? []), { at: now, type, actor, detail: null }], MAX_LINK_HISTORY);
1128
+ validateLinkSchema(next);
1129
+ validateLinkIdentity(next, linkId);
1130
+ writeLinkFile(teamRoot, next);
1131
+ return next;
1132
+ });
1133
+ }
1134
+
1135
+ export function removeTrackerLink(teamRoot, linkId, options = {}) {
1136
+ return withTrackerLock(teamRoot, () => {
1137
+ const existing = readLinkFile(teamRoot, linkId);
1138
+ if (!existing) reject('E_TRACKER_LINK_UNKNOWN', `no tracker link "${linkId}"`);
1139
+ fs.rmSync(linkFilePath(teamRoot, linkId), { force: true });
1140
+ fs.rmSync(linkPromptPath(teamRoot, linkId), { force: true });
1141
+ return { linkId, itemId: existing.itemId, taskSlug: existing.taskSlug };
1142
+ });
1143
+ }
1144
+
1145
+ /**
1146
+ * Hard delete one tracker item with its links and prompts. Team tasks are
1147
+ * never removed: an active link or a live queue entry refuses the delete.
1148
+ */
1149
+ export function deleteTrackerItem(teamRoot, id, options = {}) {
1150
+ id = parseItemId(id, 'item id');
1151
+ return withTrackerLock(teamRoot, () => {
1152
+ const existing = readItemFile(teamRoot, id);
1153
+ if (!existing) reject('E_TRACKER_UNKNOWN_DEP', `no tracker item "${id}"`);
1154
+ const itemLinks = listLinksForItem(teamRoot, id);
1155
+ const taskStates = readTaskStates(teamRoot);
1156
+ if (itemLinks.length === 0) {
1157
+ const legacyState = taskStates.get(String(id)) ?? null;
1158
+ if (legacyState !== null && !['completed', 'cancelled', 'superseded'].includes(legacyState)) {
1159
+ reject('E_TRACKER_LINK_ACTIVE', `item ${id} has an active legacy task ${id}`);
1160
+ }
1161
+ }
1162
+ for (const link of itemLinks) {
1163
+ const state = taskStates.get(link.taskSlug) ?? null;
1164
+ if (state !== null && !['completed', 'cancelled', 'superseded'].includes(state)) {
1165
+ reject('E_TRACKER_LINK_ACTIVE', `item ${id} has an active linked task ${link.taskSlug}`);
1166
+ }
1167
+ if (link.decision === 'requested' && link.entryId !== null) {
1168
+ const entry = readEntryFile(teamRoot, link.entryId);
1169
+ if (entry && ['queued', 'claimed'].includes(entry.status)) {
1170
+ reject('E_TRACKER_QUEUE_ACTIVE', `item ${id} has a live queue entry ${link.entryId}`);
1171
+ }
1172
+ }
1173
+ }
1174
+ for (const entry of readAllEntries(teamRoot).values()) {
1175
+ if (entry.itemId === id && ['queued', 'claimed'].includes(entry.status)) {
1176
+ reject('E_TRACKER_QUEUE_ACTIVE', `item ${id} has a live queue entry ${entry.entryId}`);
1177
+ }
1178
+ }
1179
+ for (const link of itemLinks) {
1180
+ fs.rmSync(linkFilePath(teamRoot, link.linkId), { force: true });
1181
+ fs.rmSync(linkPromptPath(teamRoot, link.linkId), { force: true });
1182
+ }
1183
+ fs.rmSync(itemFilePath(teamRoot, id), { force: true });
1184
+ for (const entry of readAllEntries(teamRoot).values()) {
1185
+ if (entry.itemId === id) fs.rmSync(entryFilePath(teamRoot, entry.entryId), { force: true });
1186
+ }
1187
+ return { id, removedLinks: itemLinks.length };
1188
+ });
1189
+ }
1190
+
1191
+ /**
1192
+ * One-time file migration from the shipped slug ids to the integer sequence.
1193
+ * The item files, links, queue entries and the monotonic sequence move as one
1194
+ * lock-held transaction; a mixed tree is left readable by mapping slugs after
1195
+ * the existing numeric ids.
1196
+ */
1197
+ export function migrateTrackerIds(teamRoot) {
1198
+ return withTrackerLock(teamRoot, () => {
1199
+ const trackerRoot = trackerPaths(teamRoot).root;
1200
+ const legacyRoot = path.join(teamRoot, LEGACY_TRACKER_DIR);
1201
+ if (fs.existsSync(legacyRoot)) {
1202
+ for (const name of [ITEMS_DIR, QUEUE_DIR]) {
1203
+ const from = path.join(legacyRoot, name);
1204
+ const to = path.join(trackerRoot, name);
1205
+ if (!fs.existsSync(from)) continue;
1206
+ if (!fs.existsSync(to)) {
1207
+ fs.renameSync(from, to);
1208
+ continue;
1209
+ }
1210
+ // A tree already touched by an earlier sync may carry an empty target
1211
+ // directory: merge file by file instead of abandoning the legacy store.
1212
+ for (const entry of fs.readdirSync(from)) {
1213
+ const target = path.join(to, entry);
1214
+ if (!fs.existsSync(target)) fs.renameSync(path.join(from, entry), target);
1215
+ }
1216
+ try {
1217
+ fs.rmdirSync(from);
1218
+ } catch {
1219
+ /* a name collision keeps the source file for the operator */
1220
+ }
1221
+ }
1222
+ try {
1223
+ fs.rmdirSync(legacyRoot);
1224
+ } catch {
1225
+ /* an unexpected extra file keeps the legacy directory in place */
1226
+ }
1227
+ }
1228
+ const items = readAllItemsIncludingLegacy(teamRoot);
1229
+ const slugItems = [...items.values()].filter((item) => !Number.isInteger(item.id));
1230
+ if (slugItems.length === 0) {
1231
+ const max = listItemIds(teamRoot).reduce((value, id) => Math.max(value, id), 0);
1232
+ if (max > 0) {
1233
+ writeAtomic(sequenceFilePath(teamRoot), `${JSON.stringify({ schemaVersion: 1, nextId: max + 1 }, null, 2)}\n`);
1234
+ }
1235
+ fs.rmSync(idMigrationFilePath(teamRoot), { force: true });
1236
+ return { migrated: 0, mapping: {} };
1237
+ }
1238
+ const numericMax = [...items.values()]
1239
+ .filter((item) => Number.isInteger(item.id))
1240
+ .reduce((value, item) => Math.max(value, item.id), 0);
1241
+ // A crash midway through the rename must not shift the mapping on resume:
1242
+ // the manifest is written before the first file and removed only at the end.
1243
+ let resumed = {};
1244
+ try {
1245
+ const parsed = JSON.parse(fs.readFileSync(idMigrationFilePath(teamRoot), 'utf8'));
1246
+ if (isRecord(parsed?.mapping)) resumed = parsed.mapping;
1247
+ } catch {
1248
+ /* the first run has no manifest */
1249
+ }
1250
+ const reserved = Object.values(resumed).filter((value) => Number.isInteger(value) && value > 0);
1251
+ const ordered = [...slugItems].sort(
1252
+ (left, right) =>
1253
+ String(left.createdAt).localeCompare(String(right.createdAt)) ||
1254
+ String(left.id).localeCompare(String(right.id)),
1255
+ );
1256
+ const mapping = new Map();
1257
+ let next = Math.max(numericMax, ...reserved, 0) + 1;
1258
+ for (const item of ordered) {
1259
+ const id = Number.isInteger(resumed[item.id]) ? resumed[item.id] : next;
1260
+ mapping.set(item.id, id);
1261
+ if (id >= next) next = id + 1;
1262
+ }
1263
+ writeAtomic(
1264
+ idMigrationFilePath(teamRoot),
1265
+ `${JSON.stringify({ schemaVersion: 1, mapping: Object.fromEntries(mapping), nextId: next }, null, 2)}\n`,
1266
+ );
1267
+ const allLinks = readAllLinks(teamRoot);
1268
+ const oldLinkToNew = new Map();
1269
+ for (const item of ordered) {
1270
+ const newId = mapping.get(item.id);
1271
+ const nextItem = {
1272
+ ...item,
1273
+ id: newId,
1274
+ dependsOn: (item.dependsOn ?? []).map((dep) => mapping.get(dep) ?? dep),
1275
+ supersededBy: item.supersededBy === null ? null : (mapping.get(item.supersededBy) ?? item.supersededBy),
1276
+ };
1277
+ validateItemSchema(nextItem);
1278
+ writeAtomic(itemFilePath(teamRoot, newId), `${JSON.stringify(nextItem, null, 2)}\n`);
1279
+ const legacyTaskSlug = String(item.id);
1280
+ if (fs.existsSync(path.join(teamRoot, 'tasks', legacyTaskSlug))) {
1281
+ const legacyLinkId = linkIdOf(newId, legacyTaskSlug);
1282
+ if (!readLinkFile(teamRoot, legacyLinkId)) {
1283
+ const now = nowIso();
1284
+ const legacyLink = {
1285
+ schemaVersion: LINK_SCHEMA_VERSION,
1286
+ linkId: legacyLinkId,
1287
+ itemId: newId,
1288
+ taskSlug: legacyTaskSlug,
1289
+ entryId: null,
1290
+ role: 'primary',
1291
+ decision: 'requested',
1292
+ promptPath: `${TRACKER_DIR}/${LINKS_DIR}/${legacyLinkId}.md`,
1293
+ language: null,
1294
+ revision: 1,
1295
+ createdAt: now,
1296
+ updatedAt: now,
1297
+ history: [{ at: now, type: 'adopted', actor: 'migration', detail: 'legacy tasks/<itemId>/ relation' }],
1298
+ };
1299
+ validateLinkSchema(legacyLink);
1300
+ writeLinkPrompt(teamRoot, legacyLinkId, item.description ?? item.title);
1301
+ writeLinkFile(teamRoot, legacyLink);
1302
+ }
1303
+ }
1304
+ for (const link of allLinks.values()) {
1305
+ if (link.itemId !== item.id) continue;
1306
+ const nextLinkId = linkIdOf(newId, link.taskSlug);
1307
+ const oldPrompt = linkPromptPath(teamRoot, link.linkId);
1308
+ const nextLink = {
1309
+ ...link,
1310
+ linkId: nextLinkId,
1311
+ itemId: newId,
1312
+ promptPath: `${TRACKER_DIR}/${LINKS_DIR}/${nextLinkId}.md`,
1313
+ };
1314
+ validateLinkSchema(nextLink);
1315
+ if (fs.existsSync(oldPrompt)) {
1316
+ fs.renameSync(oldPrompt, linkPromptPath(teamRoot, nextLinkId));
1317
+ }
1318
+ writeLinkFile(teamRoot, nextLink);
1319
+ fs.rmSync(linkFilePath(teamRoot, link.linkId), { force: true });
1320
+ oldLinkToNew.set(link.linkId, nextLinkId);
1321
+ }
1322
+ fs.rmSync(itemFilePath(teamRoot, item.id), { force: true });
1323
+ }
1324
+ for (const [entryId, entry] of readAllEntries(teamRoot)) {
1325
+ const mappedItem = mapping.get(entry.itemId);
1326
+ if (mappedItem === undefined) continue;
1327
+ const nextEntry = {
1328
+ ...entry,
1329
+ itemId: mappedItem,
1330
+ taskSlug: entry.taskSlug ?? String(entry.itemId),
1331
+ linkId: entry.linkId === null || entry.linkId === undefined
1332
+ ? null
1333
+ : (oldLinkToNew.get(entry.linkId) ?? entry.linkId),
1334
+ };
1335
+ validateEntrySchema(nextEntry);
1336
+ writeEntryFile(teamRoot, nextEntry);
1337
+ }
1338
+ writeAtomic(sequenceFilePath(teamRoot), `${JSON.stringify({ schemaVersion: 1, nextId: next }, null, 2)}\n`);
1339
+ fs.rmSync(idMigrationFilePath(teamRoot), { force: true });
1340
+ return { migrated: ordered.length, mapping: Object.fromEntries(mapping) };
1341
+ });
1342
+ }
1343
+
1344
+ /**
1345
+ * Materialize the legacy 1:1 relation (`tasks/<itemId>/`) as an explicit link
1346
+ * for one item or for every item that has no links. Reads stay honest without
1347
+ * this command; it exists so an operator can adopt the old shape deliberately.
1348
+ */
1349
+ export function adoptLegacyLinks(teamRoot, itemId = null, options = {}) {
1350
+ itemId = itemId === null ? null : parseItemId(itemId, 'itemId');
1351
+ return withTrackerLock(teamRoot, () => {
1352
+ const ids = itemId === null ? listItemIds(teamRoot) : [itemId];
1353
+ const adopted = [];
1354
+ for (const id of ids) {
1355
+ const item = readItemFile(teamRoot, id);
1356
+ if (!item) {
1357
+ if (itemId !== null) reject('E_TRACKER_UNKNOWN_DEP', `no tracker item "${id}"`);
1358
+ continue;
1359
+ }
1360
+ if (listLinksForItem(teamRoot, id).length > 0) continue;
1361
+ if (!fs.existsSync(path.join(teamRoot, 'tasks', String(id)))) continue;
1362
+ const linkId = linkIdOf(id, String(id));
1363
+ if (readLinkFile(teamRoot, linkId)) continue;
1364
+ const prompt = item.description ?? item.title;
1365
+ const now = nowIso();
1366
+ const link = {
1367
+ schemaVersion: LINK_SCHEMA_VERSION,
1368
+ linkId,
1369
+ itemId: id,
1370
+ taskSlug: String(id),
1371
+ entryId: null,
1372
+ role: 'primary',
1373
+ decision: 'requested',
1374
+ promptPath: `${TRACKER_DIR}/${LINKS_DIR}/${linkId}.md`,
1375
+ language: null,
1376
+ revision: 1,
1377
+ createdAt: now,
1378
+ updatedAt: now,
1379
+ history: [{ at: now, type: 'adopted', actor: options.actor ?? 'operator', detail: 'legacy tasks/<itemId>/ relation' }],
1380
+ };
1381
+ validateLinkSchema(link);
1382
+ validateLinkIdentity(link, linkId);
1383
+ writeLinkPrompt(teamRoot, linkId, prompt);
1384
+ writeLinkFile(teamRoot, link);
1385
+ adopted.push(linkId);
1386
+ }
1387
+ return { adopted };
1388
+ });
1389
+ }
1390
+
790
1391
  /* ------------------------------ launch queue ------------------------------ */
791
1392
 
792
1393
  const expireEntriesForItem = (teamRoot, itemId, detail, actor) => {
@@ -807,29 +1408,62 @@ const expireEntriesForItem = (teamRoot, itemId, detail, actor) => {
807
1408
  }
808
1409
  };
809
1410
 
810
- export function enqueueBacklogItem(teamRoot, payload, options = {}) {
811
- if (!isRecord(payload)) reject('E_SCHEMA', 'backlog enqueue payload must be an object');
812
- return withBacklogLock(teamRoot, () => {
813
- const itemId = payload.itemId;
814
- if (typeof itemId !== 'string' || !ITEM_ID_RE.test(itemId)) {
815
- reject('E_SCHEMA', 'itemId must match the slug grammar');
816
- }
1411
+ export function enqueueTrackerItem(teamRoot, payload, options = {}) {
1412
+ if (!isRecord(payload)) reject('E_SCHEMA', 'tracker enqueue payload must be an object');
1413
+ return withTrackerLock(teamRoot, () => {
1414
+ const itemId = parseItemId(payload.itemId, 'itemId');
817
1415
  const item = readItemFile(teamRoot, itemId);
818
- if (!item) reject('E_BACKLOG_UNKNOWN_DEP', `no backlog item "${itemId}"`);
1416
+ if (!item) reject('E_TRACKER_UNKNOWN_DEP', `no tracker item "${itemId}"`);
1417
+ const taskSlug = payload.taskSlug ?? `tracker-${itemId}`;
1418
+ if (typeof taskSlug !== 'string' || !TASK_SLUG_RE.test(taskSlug) || taskSlug.length < 3 || taskSlug.length > MAX_TASK_SLUG_CHARS) {
1419
+ reject('E_SCHEMA', `taskSlug must match ${TASK_SLUG_RE.source} with 3-${MAX_TASK_SLUG_CHARS} characters`);
1420
+ }
1421
+ const linkId = payload.linkId ?? linkIdOf(itemId, taskSlug);
1422
+ if (typeof linkId !== 'string' || linkId.length > 160) {
1423
+ reject('E_SCHEMA', 'linkId must be <itemId>--<taskSlug>');
1424
+ }
1425
+ const link = readLinkFile(teamRoot, linkId);
1426
+ if (link !== null && (link.itemId !== itemId || link.taskSlug !== taskSlug)) {
1427
+ reject('E_SCHEMA', `link ${linkId} does not belong to ${itemId} / ${taskSlug}`);
1428
+ }
1429
+ if (link !== null && link.decision === 'unlinked') {
1430
+ reject('E_TRACKER_TRANSITION', `link ${linkId} is unlinked`);
1431
+ }
1432
+
1433
+ // A backlog item is captured, not rejectable: starting work promotes it to
1434
+ // planned so the existing ready/drain rules apply without a second action.
1435
+ let currentItem = item;
1436
+ if (item.status === 'backlog') {
1437
+ const at = nowIso();
1438
+ currentItem = {
1439
+ ...item,
1440
+ status: 'planned',
1441
+ revision: item.revision + 1,
1442
+ updatedAt: at,
1443
+ history: capHistory(
1444
+ [...(item.history ?? []), { at, type: 'status-changed', actor: options.actor ?? 'operator', detail: 'backlog -> planned (launch)' }],
1445
+ MAX_ITEM_HISTORY,
1446
+ ),
1447
+ };
1448
+ validateItemSchema(currentItem);
1449
+ writeItemFile(teamRoot, currentItem);
1450
+ }
819
1451
  const taskStates = readTaskStates(teamRoot);
820
1452
  const entries = readAllEntries(teamRoot);
1453
+ const itemLinks = listLinksForItem(teamRoot, itemId).filter((candidate) => candidate.decision !== 'unlinked');
821
1454
  const openEntry = [...entries.values()].find((entry) => {
822
1455
  if (entry.itemId !== itemId) return false;
823
- return isNonTerminalEntryStatus(effectiveEntryStatus(entry, taskStates.get(itemId) ?? null));
1456
+ if ((entry.taskSlug ?? `tracker-${entry.itemId}`) !== taskSlug) return false;
1457
+ return isNonTerminalEntryStatus(effectiveEntryStatus(entry, taskStates.get(entry.taskSlug ?? `tracker-${entry.itemId}`) ?? null));
824
1458
  });
825
- const effective = effectiveItemStatus(item, taskStates.get(itemId) ?? null, openEntry !== undefined);
1459
+ const effective = effectiveItemStatus(currentItem, taskStates.get(taskSlug) ?? null, openEntry !== undefined, itemLinks, taskStates);
826
1460
  if (['completed', 'cancelled', 'superseded'].includes(effective)) {
827
- reject('E_BACKLOG_TRANSITION', `item ${itemId} is ${effective}; enqueue is refused`);
1461
+ reject('E_TRACKER_TRANSITION', `item ${itemId} is ${effective}; enqueue is refused`);
828
1462
  }
829
1463
  const actor = options.actor ?? 'operator';
830
1464
  if (openEntry) {
831
1465
  // R3-5: a duplicate enqueue appends the new reason to the history
832
- // instead of dropping it; enqueue stays idempotent per item.
1466
+ // instead of dropping it; enqueue stays idempotent per task link.
833
1467
  const reason = typeof payload.reason === 'string' && payload.reason.length >= 1 ? payload.reason : openEntry.reason;
834
1468
  const next = {
835
1469
  ...openEntry,
@@ -848,6 +1482,8 @@ export function enqueueBacklogItem(teamRoot, payload, options = {}) {
848
1482
  schemaVersion: ENTRY_SCHEMA_VERSION,
849
1483
  entryId: newEntryId(),
850
1484
  itemId,
1485
+ taskSlug,
1486
+ linkId,
851
1487
  status: 'queued',
852
1488
  reason: payload.reason,
853
1489
  requestedBy: payload.requestedBy,
@@ -860,18 +1496,32 @@ export function enqueueBacklogItem(teamRoot, payload, options = {}) {
860
1496
  };
861
1497
  validateEntrySchema(entry);
862
1498
  writeEntryFile(teamRoot, entry);
1499
+ if (link !== null && link.entryId !== entry.entryId) {
1500
+ const linked = {
1501
+ ...link,
1502
+ entryId: entry.entryId,
1503
+ revision: link.revision + 1,
1504
+ updatedAt: now,
1505
+ history: capHistory(
1506
+ [...(link.history ?? []), { at: now, type: 'linked', actor, detail: null }],
1507
+ MAX_LINK_HISTORY,
1508
+ ),
1509
+ };
1510
+ validateLinkSchema(linked);
1511
+ writeLinkFile(teamRoot, linked);
1512
+ }
863
1513
  return { entry, existing: false };
864
1514
  });
865
1515
  }
866
1516
 
867
- export function cancelBacklogEntry(teamRoot, entryId, options = {}) {
868
- return withBacklogLock(teamRoot, () => {
1517
+ export function cancelTrackerEntry(teamRoot, entryId, options = {}) {
1518
+ return withTrackerLock(teamRoot, () => {
869
1519
  const entry = readEntryFile(teamRoot, entryId);
870
- if (!entry) reject('E_BACKLOG_UNKNOWN_DEP', `no queue entry "${entryId}"`);
871
- const taskState = readTaskStates(teamRoot).get(entry.itemId) ?? null;
1520
+ if (!entry) reject('E_TRACKER_UNKNOWN_DEP', `no queue entry "${entryId}"`);
1521
+ const taskState = readTaskStates(teamRoot).get(entry.taskSlug ?? `tracker-${entry.itemId}`) ?? null;
872
1522
  const effective = effectiveEntryStatus(entry, taskState);
873
1523
  if (effective === 'active') {
874
- reject('E_BACKLOG_TRANSITION', `entry ${entryId} is active; an active run belongs to the hook`);
1524
+ reject('E_TRACKER_TRANSITION', `entry ${entryId} is active; an active run belongs to the hook`);
875
1525
  }
876
1526
  if (['cancelled', 'expired', 'done'].includes(effective)) return { entry, unchanged: true };
877
1527
  const at = nowIso();
@@ -902,7 +1552,7 @@ const releaseStaleClaims = (teamRoot, actor) => {
902
1552
  const taskStates = readTaskStates(teamRoot);
903
1553
  for (const [entryId, entry] of readAllEntries(teamRoot)) {
904
1554
  if (entry.status !== 'claimed' || entry.claimedAt === null) continue;
905
- if (taskStates.has(entry.itemId)) continue;
1555
+ if (taskStates.has(entry.taskSlug ?? `tracker-${entry.itemId}`)) continue;
906
1556
  if (Date.now() - Date.parse(entry.claimedAt) < CLAIM_STALE_MS) continue;
907
1557
  const at = nowIso();
908
1558
  const next = {
@@ -922,24 +1572,25 @@ const releaseStaleClaims = (teamRoot, actor) => {
922
1572
  return recovered;
923
1573
  };
924
1574
 
925
- export function recoverBacklogEntries(teamRoot, options = {}) {
926
- return withBacklogLock(teamRoot, () => ({ recovered: releaseStaleClaims(teamRoot, options.actor ?? 'operator') }));
1575
+ export function recoverTrackerEntries(teamRoot, options = {}) {
1576
+ return withTrackerLock(teamRoot, () => ({ recovered: releaseStaleClaims(teamRoot, options.actor ?? 'operator') }));
927
1577
  }
928
1578
 
929
- export function drainBacklog(teamRoot, { claim = false, actor = 'operator' } = {}) {
930
- return withBacklogLock(teamRoot, () => {
1579
+ export function drainTracker(teamRoot, { claim = false, actor = 'operator' } = {}) {
1580
+ return withTrackerLock(teamRoot, () => {
931
1581
  releaseStaleClaims(teamRoot, actor);
932
1582
  const snapshot = {
933
1583
  asOf: nowIso(),
934
1584
  items: readAllItems(teamRoot),
935
1585
  entries: readAllEntries(teamRoot),
1586
+ links: readAllLinks(teamRoot),
936
1587
  taskStates: readTaskStates(teamRoot),
937
1588
  };
938
- const ordering = deriveBacklogOrdering(snapshot);
939
- const config = readBacklogConfig(teamRoot);
1589
+ const ordering = deriveTrackerOrdering(snapshot);
1590
+ const config = readTrackerConfig(teamRoot);
940
1591
  const activeCount = countActiveTasks(snapshot.taskStates);
941
1592
  const claimedOrActiveCount = [...snapshot.entries.values()].filter((entry) =>
942
- ['claimed', 'active'].includes(effectiveEntryStatus(entry, snapshot.taskStates.get(entry.itemId) ?? null)),
1593
+ ['claimed', 'active'].includes(effectiveEntryStatus(entry, snapshot.taskStates.get(entry.taskSlug ?? `tracker-${entry.itemId}`) ?? null)),
943
1594
  ).length;
944
1595
  const claimable = activeCount < config.maxActive && claimedOrActiveCount < config.maxActive;
945
1596
  const base = {
@@ -968,12 +1619,12 @@ export function drainBacklog(teamRoot, { claim = false, actor = 'operator' } = {
968
1619
  };
969
1620
  validateEntrySchema(next);
970
1621
  writeEntryFile(teamRoot, next);
971
- return { ok: true, claim: { entryId: next.entryId, itemId: next.itemId, slug: next.itemId }, reason: null, ...base };
1622
+ return { ok: true, claim: { entryId: next.entryId, itemId: next.itemId, taskSlug: next.taskSlug ?? `tracker-${next.itemId}`, linkId: next.linkId ?? null, slug: next.taskSlug ?? `tracker-${next.itemId}` }, reason: null, ...base };
972
1623
  });
973
1624
  }
974
1625
 
975
- export function pruneBacklogEntries(teamRoot, { olderThanDays = DEFAULT_PRUNE_DAYS } = {}) {
976
- return withBacklogLock(teamRoot, () => {
1626
+ export function pruneTrackerEntries(teamRoot, { olderThanDays = DEFAULT_PRUNE_DAYS } = {}) {
1627
+ return withTrackerLock(teamRoot, () => {
977
1628
  const cutoff = Date.now() - olderThanDays * 24 * 60 * 60 * 1000;
978
1629
  let pruned = 0;
979
1630
  for (const [entryId, entry] of readAllEntries(teamRoot)) {
@@ -1028,7 +1679,7 @@ const envelopeFields = (item) => {
1028
1679
  * item passes — upserted by id, `--dry-run` writes nothing, and an idle
1029
1680
  * re-import (content-hash equality) writes nothing.
1030
1681
  */
1031
- export function importBacklogItems(teamRoot, envelope, options = {}) {
1682
+ export function importTrackerItems(teamRoot, envelope, options = {}) {
1032
1683
  if (!isRecord(envelope)) reject('E_SCHEMA', 'import envelope must be an object');
1033
1684
  if (envelope.schemaVersion !== ITEM_SCHEMA_VERSION) {
1034
1685
  reject('E_SCHEMA', `import envelope schemaVersion must be ${ITEM_SCHEMA_VERSION}`);
@@ -1042,7 +1693,7 @@ export function importBacklogItems(teamRoot, envelope, options = {}) {
1042
1693
  }
1043
1694
  if (!Array.isArray(envelope.items)) reject('E_SCHEMA', 'import envelope items must be an array');
1044
1695
  const dryRun = Boolean(options.dryRun);
1045
- return withBacklogLock(teamRoot, () => {
1696
+ return withTrackerLock(teamRoot, () => {
1046
1697
  const existing = readAllItems(teamRoot);
1047
1698
  const byId = new Map(existing);
1048
1699
  const plan = [];
@@ -1054,13 +1705,13 @@ export function importBacklogItems(teamRoot, envelope, options = {}) {
1054
1705
  reject('E_SCHEMA', `import items[${index}]: id is required`);
1055
1706
  }
1056
1707
  if (plan.some((entry) => entry.item.id === item.id)) {
1057
- reject('E_BACKLOG_DUPLICATE_ID', `import envelope: items[${index}] duplicates id "${item.id}"`);
1708
+ reject('E_TRACKER_DUPLICATE_ID', `import envelope: items[${index}] duplicates id "${item.id}"`);
1058
1709
  }
1059
1710
  validateItemSchema(item);
1060
1711
  const previous = byId.get(item.id) ?? null;
1061
1712
  if (!previous) {
1062
1713
  // D-2 collision guard applies to new ids, exactly as on `add`.
1063
- if (fs.existsSync(path.join(teamRoot, 'tasks', item.id))) {
1714
+ if (fs.existsSync(path.join(teamRoot, 'tasks', String(item.id)))) {
1064
1715
  reject('E_ID_COLLISION', `id "${item.id}" already names a tasks/${item.id}/ directory`);
1065
1716
  }
1066
1717
  } else {
@@ -1102,20 +1753,41 @@ export function importBacklogItems(teamRoot, envelope, options = {}) {
1102
1753
  else result.updated += 1;
1103
1754
  if (!dryRun) writeItemFile(teamRoot, step.item);
1104
1755
  }
1756
+ if (!dryRun) {
1757
+ const maxImported = plan.reduce((max, step) => Math.max(max, step.item.id), 0);
1758
+ let reserved = 0;
1759
+ try {
1760
+ const parsed = JSON.parse(fs.readFileSync(sequenceFilePath(teamRoot), 'utf8'));
1761
+ if (Number.isInteger(parsed?.nextId) && parsed.nextId > 0) reserved = parsed.nextId;
1762
+ } catch {
1763
+ /* the first import creates the sequence */
1764
+ }
1765
+ const nextId = Math.max(maxImported + 1, reserved, 1);
1766
+ writeAtomic(sequenceFilePath(teamRoot), `${JSON.stringify({ schemaVersion: 1, nextId }, null, 2)}\\n`);
1767
+ }
1105
1768
  return result;
1106
1769
  });
1107
1770
  }
1108
1771
 
1109
1772
  /* ------------------------ whole-tree validation --------------------------- */
1110
1773
 
1111
- export function validateBacklogTree(teamRoot) {
1112
- return withBacklogLock(teamRoot, () => {
1774
+ export function validateTrackerTree(teamRoot) {
1775
+ return withTrackerLock(teamRoot, () => {
1113
1776
  const errors = [];
1114
1777
  const items = readAllItems(teamRoot);
1115
- readBacklogConfig(teamRoot);
1778
+ readTrackerConfig(teamRoot);
1779
+ for (const stem of listAllItemStems(teamRoot)) {
1780
+ if (!ITEM_ID_RE.test(stem)) {
1781
+ errors.push({
1782
+ path: `tracker/items/${stem}.json`,
1783
+ code: 'E_SCHEMA',
1784
+ message: 'item file name must be a positive integer id; run `tracker migrate-ids` for a legacy store',
1785
+ });
1786
+ }
1787
+ }
1116
1788
  for (const id of listItemIds(teamRoot)) {
1117
1789
  const record = items.get(id);
1118
- const collect = (code, message) => errors.push({ path: `backlog/items/${id}.json`, code, message });
1790
+ const collect = (code, message) => errors.push({ path: `tracker/items/${id}.json`, code, message });
1119
1791
  if (!record) {
1120
1792
  collect('E_SCHEMA', 'item file is not readable');
1121
1793
  continue;
@@ -1149,7 +1821,7 @@ export function validateBacklogTree(teamRoot) {
1149
1821
  validateEntrySchema(readEntryFile(teamRoot, entryId));
1150
1822
  } catch (error) {
1151
1823
  errors.push({
1152
- path: `backlog/queue/${entryId}.json`,
1824
+ path: `tracker/queue/${entryId}.json`,
1153
1825
  code: error instanceof TeamDbError ? error.code : 'E_SCHEMA',
1154
1826
  message: error.message,
1155
1827
  });
@@ -1161,28 +1833,9 @@ export function validateBacklogTree(teamRoot) {
1161
1833
 
1162
1834
  /* --------------------------- projection seam ------------------------------ */
1163
1835
 
1164
- /**
1165
- * Best-effort bounded projection after a write, mirroring the manifest seam:
1166
- * the child is `SIGKILL`-bounded, failures are silent, and the kill switch or
1167
- * a missing `node:sqlite` skips it. Files stay authoritative; the next hook or
1168
- * manifest projection reconciles.
1169
- */
1170
- const projectAfterWrite = (teamRoot) => {
1171
- const env = process.env;
1172
- if (isTruthy(env.AI_RULES_TEAM_DB_DISABLE)) return;
1173
- const script = path.join(path.dirname(fileURLToPath(import.meta.url)), 'team-db.mjs');
1174
- if (!fs.existsSync(script)) return;
1175
- const result = spawnSync(
1176
- process.execPath,
1177
- [script, 'sync', '--quiet', '--no-rebuild', '--deadline-ms', '4500', '--root', teamRoot],
1178
- { env, encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL', stdio: ['ignore', 'pipe', 'pipe'] },
1179
- );
1180
- void result;
1181
- };
1182
-
1183
1836
  /* ------------------------------ CLI surface ------------------------------- */
1184
1837
 
1185
- export const BACKLOG_SUBCOMMANDS = new Set([
1838
+ export const TRACKER_SUBCOMMANDS = new Set([
1186
1839
  'add',
1187
1840
  'set',
1188
1841
  'show',
@@ -1195,6 +1848,10 @@ export const BACKLOG_SUBCOMMANDS = new Set([
1195
1848
  'drain',
1196
1849
  'recover',
1197
1850
  'prune',
1851
+ 'link',
1852
+ 'delete',
1853
+ 'adopt',
1854
+ 'migrate-ids',
1198
1855
  ]);
1199
1856
 
1200
1857
  const SUBCOMMAND_FLAGS = {
@@ -1210,16 +1867,20 @@ const SUBCOMMAND_FLAGS = {
1210
1867
  drain: new Set(['claim']),
1211
1868
  recover: new Set(),
1212
1869
  prune: new Set(['older-than']),
1870
+ link: new Set(['file']),
1871
+ delete: new Set(),
1872
+ adopt: new Set(['file']),
1873
+ 'migrate-ids': new Set(),
1213
1874
  };
1214
1875
 
1215
- const WITH_ID = new Set(['set', 'show', 'cancel']);
1216
- const WITH_FILE = new Set(['add', 'set', 'import', 'enqueue']);
1876
+ const WITH_ID = new Set(['set', 'show', 'cancel', 'delete']);
1877
+ const WITH_FILE = new Set(['add', 'set', 'import', 'enqueue', 'link', 'adopt']);
1217
1878
 
1218
- export function runBacklogCommand(subcommand, positionalId, options = {}) {
1879
+ export function runTrackerCommand(subcommand, positionalId, options = {}) {
1219
1880
  const teamRoot = path.resolve(options.root || DEFAULT_TEAM_ROOT);
1220
1881
  const json = Boolean(options.json);
1221
1882
  const quiet = Boolean(options.quiet);
1222
- if (!BACKLOG_SUBCOMMANDS.has(subcommand)) teamDbFail('E_USAGE', `unknown backlog subcommand "${subcommand}"`, 3);
1883
+ if (!TRACKER_SUBCOMMANDS.has(subcommand)) teamDbFail('E_USAGE', `unknown tracker subcommand "${subcommand}"`, 3);
1223
1884
  const allowed = SUBCOMMAND_FLAGS[subcommand];
1224
1885
  const present = [];
1225
1886
  if (options.file !== undefined) present.push('file');
@@ -1229,16 +1890,16 @@ export function runBacklogCommand(subcommand, positionalId, options = {}) {
1229
1890
  if (options.status !== undefined) present.push('status');
1230
1891
  if (options.ready) present.push('ready');
1231
1892
  for (const flag of present) {
1232
- if (!allowed.has(flag)) teamDbFail('E_USAGE', `flag --${flag} does not apply to backlog ${subcommand}`, 3);
1893
+ if (!allowed.has(flag)) teamDbFail('E_USAGE', `flag --${flag} does not apply to tracker ${subcommand}`, 3);
1233
1894
  }
1234
1895
  if (WITH_ID.has(subcommand) && (typeof positionalId !== 'string' || positionalId === '')) {
1235
- teamDbFail('E_USAGE', `backlog ${subcommand} needs an id`, 3);
1896
+ teamDbFail('E_USAGE', `tracker ${subcommand} needs an id`, 3);
1236
1897
  }
1237
1898
  if (!WITH_ID.has(subcommand) && positionalId !== null && positionalId !== undefined) {
1238
- teamDbFail('E_USAGE', `backlog ${subcommand} takes no id argument`, 3);
1899
+ teamDbFail('E_USAGE', `tracker ${subcommand} takes no id argument`, 3);
1239
1900
  }
1240
1901
  const readPayload = () => {
1241
- if (options.file === undefined) teamDbFail('E_USAGE', `backlog ${subcommand} needs --file <path|->`, 3);
1902
+ if (options.file === undefined) teamDbFail('E_USAGE', `tracker ${subcommand} needs --file <path|->`, 3);
1242
1903
  const text = options.file === '-' ? fs.readFileSync(0, 'utf8') : fs.readFileSync(path.resolve(options.file), 'utf8');
1243
1904
  try {
1244
1905
  return JSON.parse(text);
@@ -1252,8 +1913,8 @@ export function runBacklogCommand(subcommand, positionalId, options = {}) {
1252
1913
  if (!quiet) return `${text}\n`;
1253
1914
  return '';
1254
1915
  };
1255
- const itemLine = (item) => `backlog: id=${item.id} status=${item.status} revision=${item.revision}`;
1256
- const entryLine = (entry) => `backlog: entry=${entry.entryId} item=${entry.itemId} status=${entry.status}`;
1916
+ const itemLine = (item) => `tracker: id=${item.id} status=${item.status} revision=${item.revision}`;
1917
+ const entryLine = (entry) => `tracker: entry=${entry.entryId} item=${entry.itemId} status=${entry.status}`;
1257
1918
  const rankedItems = (ordering) =>
1258
1919
  [...ordering.byId.values()].sort((a, b) => rankCompare(a.item, b.item));
1259
1920
 
@@ -1261,21 +1922,22 @@ export function runBacklogCommand(subcommand, positionalId, options = {}) {
1261
1922
  let wrote = false;
1262
1923
 
1263
1924
  if (subcommand === 'add') {
1264
- const item = addBacklogItem(teamRoot, readPayload());
1925
+ const item = addTrackerItem(teamRoot, readPayload());
1265
1926
  wrote = true;
1266
1927
  output += out(json ? JSON.stringify({ ok: true, item }) : itemLine(item));
1267
1928
  } else if (subcommand === 'set') {
1268
- const item = setBacklogItem(teamRoot, positionalId, readPayload());
1929
+ const item = setTrackerItem(teamRoot, positionalId, readPayload());
1269
1930
  wrote = true;
1270
1931
  output += out(json ? JSON.stringify({ ok: true, item }) : itemLine(item));
1271
1932
  } else if (subcommand === 'show') {
1272
- const snapshot = readBacklogSnapshot(teamRoot);
1273
- const annotated = deriveBacklogOrdering(snapshot).byId.get(positionalId);
1274
- if (!annotated) reject('E_BACKLOG_UNKNOWN_DEP', `no backlog item "${positionalId}"`);
1933
+ const snapshot = readTrackerSnapshot(teamRoot);
1934
+ const annotated = deriveTrackerOrdering(snapshot).byId.get(parseItemId(positionalId, 'item id'));
1935
+ if (!annotated) reject('E_TRACKER_UNKNOWN_DEP', `no tracker item "${positionalId}"`);
1936
+ if (json) annotated.links = listLinksForItem(teamRoot, positionalId);
1275
1937
  output += out(JSON.stringify(annotated, null, json ? 0 : 2));
1276
1938
  } else if (subcommand === 'list') {
1277
- const snapshot = readBacklogSnapshot(teamRoot);
1278
- const ordering = deriveBacklogOrdering(snapshot);
1939
+ const snapshot = readTrackerSnapshot(teamRoot);
1940
+ const ordering = deriveTrackerOrdering(snapshot);
1279
1941
  const statuses = options.status !== undefined ? options.status.split(',').map((value) => value.trim()) : null;
1280
1942
  if (statuses) {
1281
1943
  for (const status of statuses) {
@@ -1306,61 +1968,102 @@ export function runBacklogCommand(subcommand, positionalId, options = {}) {
1306
1968
  if (quiet) output = '';
1307
1969
  }
1308
1970
  } else if (subcommand === 'ready') {
1309
- const snapshot = readBacklogSnapshot(teamRoot);
1310
- const ordering = deriveBacklogOrdering(snapshot);
1971
+ const snapshot = readTrackerSnapshot(teamRoot);
1972
+ const ordering = deriveTrackerOrdering(snapshot);
1311
1973
  output += json
1312
1974
  ? out(JSON.stringify({ asOf: snapshot.asOf, ready: ordering.readyIds }))
1313
1975
  : out(ordering.readyIds.join('\n') || '(no ready items)');
1314
1976
  } else if (subcommand === 'validate') {
1315
- const report = validateBacklogTree(teamRoot);
1977
+ const report = validateTrackerTree(teamRoot);
1316
1978
  if (!report.ok) {
1317
1979
  for (const error of report.errors) process.stderr.write(`${error.path}: ${error.code}: ${error.message}\n`);
1318
1980
  if (json) output += `${JSON.stringify({ ok: false, items: report.items, errors: report.errors })}\n`;
1319
1981
  return { output, exitCode: 1 };
1320
1982
  }
1321
- output += out(json ? JSON.stringify({ ok: true, items: report.items, errors: [] }) : `backlog validate: ${report.items} items, all valid`);
1983
+ output += out(json ? JSON.stringify({ ok: true, items: report.items, errors: [] }) : `tracker validate: ${report.items} items, all valid`);
1322
1984
  } else if (subcommand === 'import') {
1323
- const result = importBacklogItems(teamRoot, readPayload(), { dryRun: options.dryRun });
1985
+ const result = importTrackerItems(teamRoot, readPayload(), { dryRun: options.dryRun });
1324
1986
  if (!options.dryRun) wrote = true;
1325
1987
  output += json
1326
1988
  ? out(JSON.stringify({ ok: true, ...result }))
1327
- : out(`backlog import: inserted=${result.inserted} updated=${result.updated} unchanged=${result.unchanged}${result.dryRun ? ' (dry run)' : ''}`);
1989
+ : out(`tracker import: inserted=${result.inserted} updated=${result.updated} unchanged=${result.unchanged}${result.dryRun ? ' (dry run)' : ''}`);
1328
1990
  } else if (subcommand === 'enqueue') {
1329
- const { entry, existing } = enqueueBacklogItem(teamRoot, readPayload());
1991
+ const { entry, existing } = enqueueTrackerItem(teamRoot, readPayload());
1330
1992
  wrote = true;
1331
1993
  output += out(json ? JSON.stringify({ ok: true, entry, existing }) : `${entryLine(entry)}${existing ? ' (existing)' : ''}`);
1332
1994
  } else if (subcommand === 'cancel') {
1333
- const { entry, unchanged } = cancelBacklogEntry(teamRoot, positionalId);
1995
+ const { entry, unchanged } = cancelTrackerEntry(teamRoot, positionalId);
1334
1996
  wrote = true;
1335
1997
  output += out(json ? JSON.stringify({ ok: true, entry, unchanged }) : `${entryLine(entry)}${unchanged ? ' (unchanged)' : ''}`);
1336
1998
  } else if (subcommand === 'drain') {
1337
- const result = drainBacklog(teamRoot, { claim: options.claim });
1999
+ const result = drainTracker(teamRoot, { claim: options.claim });
1338
2000
  if (json) {
1339
2001
  output += out(JSON.stringify(result));
1340
2002
  } else if (result.claim !== undefined) {
1341
2003
  output += out(
1342
2004
  result.claim
1343
- ? `backlog drain: claimed ${result.claim.entryId} for ${result.claim.slug}`
1344
- : `backlog drain: no claim (${result.reason ?? 'nothing ready'})`,
2005
+ ? `tracker drain: claimed ${result.claim.entryId} for ${result.claim.slug}`
2006
+ : `tracker drain: no claim (${result.reason ?? 'nothing ready'})`,
1345
2007
  );
1346
2008
  } else {
1347
- output += out(`backlog drain: ready=${result.ready.length} drainOrder=${result.drainOrder.length} claimable=${result.claimable}`);
2009
+ output += out(`tracker drain: ready=${result.ready.length} drainOrder=${result.drainOrder.length} claimable=${result.claimable}`);
1348
2010
  }
1349
2011
  } else if (subcommand === 'recover') {
1350
- const { recovered } = recoverBacklogEntries(teamRoot);
2012
+ const { recovered } = recoverTrackerEntries(teamRoot);
1351
2013
  if (recovered > 0) wrote = true;
1352
- output += out(json ? JSON.stringify({ ok: true, recovered }) : `backlog recover: ${recovered} stale claim(s) released`);
2014
+ output += out(json ? JSON.stringify({ ok: true, recovered }) : `tracker recover: ${recovered} stale claim(s) released`);
1353
2015
  } else if (subcommand === 'prune') {
1354
2016
  const days = options.olderThanDays === undefined ? DEFAULT_PRUNE_DAYS : Number(options.olderThanDays);
1355
2017
  if (!Number.isInteger(days) || days < 1) teamDbFail('E_USAGE', '--older-than must be a positive integer number of days', 3);
1356
- const { pruned } = pruneBacklogEntries(teamRoot, { olderThanDays: days });
2018
+ const { pruned } = pruneTrackerEntries(teamRoot, { olderThanDays: days });
1357
2019
  if (pruned > 0) wrote = true;
1358
- output += out(json ? JSON.stringify({ ok: true, pruned }) : `backlog prune: ${pruned} terminal entr${pruned === 1 ? 'y' : 'ies'} deleted`);
1359
- }
1360
-
1361
- // The API's bounded child writes the file, then projects; the read-only
1362
- // server re-reads the fresh rows. `drain` is the hook seam's verb and skips
1363
- // this so the stop never pays a second projection child.
1364
- if (wrote && subcommand !== 'drain') projectAfterWrite(teamRoot);
1365
- return { output, exitCode: 0 };
2020
+ output += out(json ? JSON.stringify({ ok: true, pruned }) : `tracker prune: ${pruned} terminal entr${pruned === 1 ? 'y' : 'ies'} deleted`);
2021
+ } else if (subcommand === 'link') {
2022
+ const payload = readPayload();
2023
+ const action = payload.action ?? 'list';
2024
+ if (action === 'add') {
2025
+ const link = addTrackerLink(teamRoot, payload);
2026
+ wrote = true;
2027
+ output += out(json ? JSON.stringify({ ok: true, link }) : `tracker link: ${link.linkId} -> ${link.taskSlug}`);
2028
+ } else if (action === 'set') {
2029
+ const link = setTrackerLink(teamRoot, payload.linkId, payload);
2030
+ wrote = true;
2031
+ output += out(json ? JSON.stringify({ ok: true, link }) : `tracker link: ${link.linkId} ${link.decision} r${link.revision}`);
2032
+ } else if (action === 'remove') {
2033
+ const removed = removeTrackerLink(teamRoot, payload.linkId);
2034
+ wrote = true;
2035
+ output += out(json ? JSON.stringify({ ok: true, ...removed }) : `tracker link: removed ${removed.linkId}`);
2036
+ } else if (action === 'adopt') {
2037
+ const result = adoptLegacyLinks(teamRoot, payload.itemId ?? null);
2038
+ if (result.adopted.length > 0) wrote = true;
2039
+ output += out(json ? JSON.stringify({ ok: true, ...result }) : `tracker link: adopted ${result.adopted.length} legacy relation(s)`);
2040
+ } else if (action === 'list') {
2041
+ const links = payload.itemId ? listLinksForItem(teamRoot, payload.itemId) : [...readAllLinks(teamRoot).values()];
2042
+ output += out(json ? JSON.stringify({ ok: true, links }) : links.map((link) => `${link.linkId} ${link.decision}`).join('\n'));
2043
+ } else {
2044
+ teamDbFail('E_USAGE', `unknown tracker link action "${action}"`, 3);
2045
+ }
2046
+ } else if (subcommand === 'delete') {
2047
+ const result = deleteTrackerItem(teamRoot, parseItemId(positionalId, 'item id'));
2048
+ wrote = true;
2049
+ output += out(json ? JSON.stringify({ ok: true, ...result }) : `tracker delete: ${result.id} (${result.removedLinks} link(s))`);
2050
+ } else if (subcommand === 'adopt') {
2051
+ const result = adoptLegacyLinks(teamRoot, null);
2052
+ if (result.adopted.length > 0) wrote = true;
2053
+ output += out(json ? JSON.stringify({ ok: true, ...result }) : `tracker adopt: ${result.adopted.length} legacy relation(s)`);
2054
+ } else if (subcommand === 'migrate-ids') {
2055
+ const result = migrateTrackerIds(teamRoot);
2056
+ if (result.migrated > 0) wrote = true;
2057
+ output += out(
2058
+ json
2059
+ ? JSON.stringify({ ok: true, ...result })
2060
+ : result.migrated === 0
2061
+ ? 'tracker migrate-ids: already numeric'
2062
+ : `tracker migrate-ids: migrated ${result.migrated} item(s)`,
2063
+ );
2064
+ }
2065
+
2066
+ // The API's bounded child writes the file, then projects; `runTracker` in
2067
+ // `team-db.mjs` owns the scoped projection so this module stays file-only.
2068
+ return { output, exitCode: 0, wrote };
1366
2069
  }