@bonesofspring/ai-rules 0.2.63 → 0.2.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +10 -3
  3. package/bin/cli.js +7 -5
  4. package/bin/lib/ai-local-drift.js +7 -6
  5. package/bin/lib/engine-scripts.js +4 -0
  6. package/bin/lib/engine-upgrade.js +10 -2
  7. package/bin/lib/manifest-schema.js +12 -0
  8. package/bin/lib/seed-ai-local-team.js +13 -0
  9. package/bin/mavis-install.js +4 -3
  10. package/bin/opencode-install.js +22 -6
  11. package/bin/zcode-install.js +4 -3
  12. package/docs/MCP-CATALOG.md +1 -1
  13. package/docs/OPENCODE-COMPATIBILITY.md +3 -2
  14. package/docs/OPENCODE.md +22 -2
  15. package/docs/PRESET-CONTRIBUTION.md +2 -2
  16. package/docs/TEAM-DB.md +71 -4
  17. package/docs/openapi/team-db.v1.json +4817 -2795
  18. package/mcp/defectdojo-mcp.mjs +41 -11
  19. package/mcp/lib/defectdojo.mjs +45 -2
  20. package/package.json +8 -2
  21. package/presets/_shared/ai-local/scripts/aggregate-agent-task-metrics.mjs +279 -0
  22. package/presets/_shared/ai-local/scripts/team-db-api.mjs +471 -7
  23. package/presets/_shared/ai-local/scripts/team-db-backlog.mjs +1366 -0
  24. package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +573 -7
  25. package/presets/_shared/ai-local/scripts/team-db-project.mjs +288 -4
  26. package/presets/_shared/ai-local/scripts/team-db-scheduler.mjs +82 -10
  27. package/presets/_shared/ai-local/scripts/team-db-schema.mjs +83 -0
  28. package/presets/_shared/ai-local/scripts/team-db.mjs +69 -6
  29. package/presets/_shared/ai-local/scripts/upstream-research.mjs +3 -0
  30. package/presets/_shared/core/agent-team/agent-task-metrics.md +7 -2
  31. package/presets/_shared/core/agent-team/agent-team-orchestrator.md +1 -0
  32. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +225 -0
  33. package/presets/_shared/hooks/run-hook.mjs +2 -1
  34. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +225 -0
  35. package/presets/claude/android-kotlin/hooks/run-hook.mjs +2 -1
  36. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  37. package/presets/claude/go/hooks/chain-team-phases.sh +225 -0
  38. package/presets/claude/go/hooks/run-hook.mjs +2 -1
  39. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  40. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +225 -0
  41. package/presets/claude/ios-swift/hooks/run-hook.mjs +2 -1
  42. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  43. package/presets/claude/java/hooks/chain-team-phases.sh +225 -0
  44. package/presets/claude/java/hooks/run-hook.mjs +2 -1
  45. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  46. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +225 -0
  47. package/presets/claude/mcp-ts/hooks/run-hook.mjs +2 -1
  48. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  49. package/presets/claude/mol/hooks/chain-team-phases.sh +225 -0
  50. package/presets/claude/mol/hooks/run-hook.mjs +2 -1
  51. package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  52. package/presets/claude/next/agents/code-reviewer.md +1 -0
  53. package/presets/claude/next/agents/mockup-reviewer.md +2 -1
  54. package/presets/claude/next/agents/task-analyst.md +2 -0
  55. package/presets/claude/next/commands/task.md +7 -1
  56. package/presets/claude/next/commands/technical-retro.md +7 -1
  57. package/presets/claude/next/commands/upstream-research.md +1 -1
  58. package/presets/claude/next/hooks/chain-team-phases.sh +225 -0
  59. package/presets/claude/next/hooks/run-hook.mjs +2 -1
  60. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  61. package/presets/claude/next/skills/figma-fidelity/SKILL.md +4 -1
  62. package/presets/claude/next/skills/mockup-review/SKILL.md +4 -0
  63. package/presets/claude/next/team/README.md +5 -1
  64. package/presets/claude/next/team/upstream/jobs.json +34 -0
  65. package/presets/claude/nuxt/hooks/chain-team-phases.sh +225 -0
  66. package/presets/claude/nuxt/hooks/run-hook.mjs +2 -1
  67. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  68. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +225 -0
  69. package/presets/claude/php-hexagonal/hooks/run-hook.mjs +2 -1
  70. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  71. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +225 -0
  72. package/presets/claude/php-laravel/hooks/run-hook.mjs +2 -1
  73. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  74. package/presets/claude/svelte/hooks/chain-team-phases.sh +225 -0
  75. package/presets/claude/svelte/hooks/run-hook.mjs +2 -1
  76. package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +1 -0
  77. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +225 -0
  78. package/presets/cursor/android-kotlin/hooks/run-hook.mjs +2 -1
  79. package/presets/cursor/go/hooks/chain-team-phases.sh +225 -0
  80. package/presets/cursor/go/hooks/run-hook.mjs +2 -1
  81. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +225 -0
  82. package/presets/cursor/ios-swift/hooks/run-hook.mjs +2 -1
  83. package/presets/cursor/java/hooks/chain-team-phases.sh +225 -0
  84. package/presets/cursor/java/hooks/run-hook.mjs +2 -1
  85. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +225 -0
  86. package/presets/cursor/mcp-ts/hooks/run-hook.mjs +2 -1
  87. package/presets/cursor/mol/hooks/chain-team-phases.sh +225 -0
  88. package/presets/cursor/mol/hooks/run-hook.mjs +2 -1
  89. package/presets/cursor/next/agents/code-reviewer.md +1 -0
  90. package/presets/cursor/next/agents/mockup-reviewer.md +2 -1
  91. package/presets/cursor/next/agents/task-analyst.md +2 -0
  92. package/presets/cursor/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -0
  93. package/presets/cursor/next/ai-local/rules-library/ui-change-review-gate.md +1 -0
  94. package/presets/cursor/next/commands/task.md +7 -1
  95. package/presets/cursor/next/commands/technical-retro.md +7 -1
  96. package/presets/cursor/next/commands/upstream-research.md +1 -1
  97. package/presets/cursor/next/hooks/chain-team-phases.sh +225 -0
  98. package/presets/cursor/next/hooks/run-hook.mjs +2 -1
  99. package/presets/cursor/next/skills/figma-fidelity/SKILL.md +4 -1
  100. package/presets/cursor/next/skills/mockup-review/SKILL.md +4 -0
  101. package/presets/cursor/next/team/README.md +5 -1
  102. package/presets/cursor/next/team/upstream/jobs.json +34 -0
  103. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +225 -0
  104. package/presets/cursor/nuxt/hooks/run-hook.mjs +2 -1
  105. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +225 -0
  106. package/presets/cursor/php-hexagonal/hooks/run-hook.mjs +2 -1
  107. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +225 -0
  108. package/presets/cursor/php-laravel/hooks/run-hook.mjs +2 -1
  109. package/presets/cursor/svelte/hooks/chain-team-phases.sh +225 -0
  110. package/presets/cursor/svelte/hooks/run-hook.mjs +2 -1
  111. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  112. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +225 -0
  113. package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +1 -0
  114. package/presets/mavis/go/adapter-map.json +1 -1
  115. package/presets/mavis/go/hooks/chain-team-phases.sh +225 -0
  116. package/presets/mavis/go/rules/agent-team-orchestrator.md +1 -0
  117. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  118. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +225 -0
  119. package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +1 -0
  120. package/presets/mavis/java/adapter-map.json +1 -1
  121. package/presets/mavis/java/hooks/chain-team-phases.sh +225 -0
  122. package/presets/mavis/java/rules/agent-team-orchestrator.md +1 -0
  123. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  124. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +225 -0
  125. package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +1 -0
  126. package/presets/mavis/mol/adapter-map.json +1 -1
  127. package/presets/mavis/mol/hooks/chain-team-phases.sh +225 -0
  128. package/presets/mavis/mol/rules/agent-team-orchestrator.md +1 -0
  129. package/presets/mavis/next/adapter-map.json +9 -1
  130. package/presets/mavis/next/agents/code-reviewer.md +1 -0
  131. package/presets/mavis/next/agents/mockup-reviewer.md +2 -1
  132. package/presets/mavis/next/agents/task-analyst.md +2 -0
  133. package/presets/mavis/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -0
  134. package/presets/mavis/next/ai-local/rules-library/ui-change-review-gate.md +1 -0
  135. package/presets/mavis/next/commands/task.md +7 -1
  136. package/presets/mavis/next/commands/technical-retro.md +7 -1
  137. package/presets/mavis/next/commands/upstream-research.md +1 -1
  138. package/presets/mavis/next/hooks/chain-team-phases.sh +225 -0
  139. package/presets/mavis/next/rules/agent-team-orchestrator.md +1 -0
  140. package/presets/mavis/next/skills/figma-fidelity/SKILL.md +4 -1
  141. package/presets/mavis/next/skills/mockup-review/SKILL.md +4 -0
  142. package/presets/mavis/next/team/README.md +5 -1
  143. package/presets/mavis/next/team/upstream/jobs.json +34 -0
  144. package/presets/mavis/nuxt/adapter-map.json +1 -1
  145. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +225 -0
  146. package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +1 -0
  147. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  148. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +225 -0
  149. package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +1 -0
  150. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  151. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +225 -0
  152. package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +1 -0
  153. package/presets/mavis/svelte/adapter-map.json +1 -1
  154. package/presets/mavis/svelte/hooks/chain-team-phases.sh +225 -0
  155. package/presets/mavis/svelte/rules/agent-team-orchestrator.md +1 -0
  156. package/presets/opencode/android-kotlin/OPENCODE.md +4 -1
  157. package/presets/opencode/android-kotlin/README.md +1 -0
  158. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  159. package/presets/opencode/android-kotlin/hooks/README.md +4 -2
  160. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +225 -0
  161. package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +1 -0
  162. package/presets/opencode/go/OPENCODE.md +4 -1
  163. package/presets/opencode/go/README.md +1 -0
  164. package/presets/opencode/go/adapter-map.json +1 -1
  165. package/presets/opencode/go/hooks/README.md +4 -2
  166. package/presets/opencode/go/hooks/chain-team-phases.sh +225 -0
  167. package/presets/opencode/go/rules/agent-team-orchestrator.md +1 -0
  168. package/presets/opencode/ios-swift/OPENCODE.md +4 -1
  169. package/presets/opencode/ios-swift/README.md +1 -0
  170. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  171. package/presets/opencode/ios-swift/hooks/README.md +4 -2
  172. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +225 -0
  173. package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +1 -0
  174. package/presets/opencode/java/OPENCODE.md +4 -1
  175. package/presets/opencode/java/README.md +1 -0
  176. package/presets/opencode/java/adapter-map.json +1 -1
  177. package/presets/opencode/java/hooks/README.md +4 -2
  178. package/presets/opencode/java/hooks/chain-team-phases.sh +225 -0
  179. package/presets/opencode/java/rules/agent-team-orchestrator.md +1 -0
  180. package/presets/opencode/mcp-ts/OPENCODE.md +4 -1
  181. package/presets/opencode/mcp-ts/README.md +1 -0
  182. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  183. package/presets/opencode/mcp-ts/hooks/README.md +4 -2
  184. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +225 -0
  185. package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +1 -0
  186. package/presets/opencode/mol/OPENCODE.md +4 -1
  187. package/presets/opencode/mol/README.md +1 -0
  188. package/presets/opencode/mol/adapter-map.json +1 -1
  189. package/presets/opencode/mol/hooks/README.md +4 -2
  190. package/presets/opencode/mol/hooks/chain-team-phases.sh +225 -0
  191. package/presets/opencode/mol/rules/agent-team-orchestrator.md +1 -0
  192. package/presets/opencode/next/OPENCODE.md +4 -1
  193. package/presets/opencode/next/README.md +1 -0
  194. package/presets/opencode/next/adapter-map.json +9 -1
  195. package/presets/opencode/next/agents/code-reviewer.md +1 -0
  196. package/presets/opencode/next/agents/mockup-reviewer.md +2 -1
  197. package/presets/opencode/next/agents/task-analyst.md +2 -0
  198. package/presets/opencode/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -0
  199. package/presets/opencode/next/ai-local/rules-library/ui-change-review-gate.md +1 -0
  200. package/presets/opencode/next/commands/task.md +7 -1
  201. package/presets/opencode/next/commands/technical-retro.md +7 -1
  202. package/presets/opencode/next/commands/upstream-research.md +1 -1
  203. package/presets/opencode/next/hooks/README.md +4 -2
  204. package/presets/opencode/next/hooks/chain-team-phases.sh +225 -0
  205. package/presets/opencode/next/rules/agent-team-orchestrator.md +1 -0
  206. package/presets/opencode/next/skills/figma-fidelity/SKILL.md +4 -1
  207. package/presets/opencode/next/skills/mockup-review/SKILL.md +4 -0
  208. package/presets/opencode/next/team/README.md +5 -1
  209. package/presets/opencode/next/team/upstream/jobs.json +34 -0
  210. package/presets/opencode/nuxt/OPENCODE.md +4 -1
  211. package/presets/opencode/nuxt/README.md +1 -0
  212. package/presets/opencode/nuxt/adapter-map.json +1 -1
  213. package/presets/opencode/nuxt/hooks/README.md +4 -2
  214. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +225 -0
  215. package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +1 -0
  216. package/presets/opencode/php-hexagonal/OPENCODE.md +4 -1
  217. package/presets/opencode/php-hexagonal/README.md +1 -0
  218. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  219. package/presets/opencode/php-hexagonal/hooks/README.md +4 -2
  220. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +225 -0
  221. package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +1 -0
  222. package/presets/opencode/php-laravel/OPENCODE.md +4 -1
  223. package/presets/opencode/php-laravel/README.md +1 -0
  224. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  225. package/presets/opencode/php-laravel/hooks/README.md +4 -2
  226. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +225 -0
  227. package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +1 -0
  228. package/presets/opencode/platform-contract.json +6 -0
  229. package/presets/opencode/plugins/task-status/README.md +92 -0
  230. package/presets/opencode/plugins/task-status/details-data.ts +130 -0
  231. package/presets/opencode/plugins/task-status/details.tsx +84 -0
  232. package/presets/opencode/plugins/task-status/eta.ts +230 -0
  233. package/presets/opencode/plugins/task-status/index.ts +6 -0
  234. package/presets/opencode/plugins/task-status/package.json +10 -0
  235. package/presets/opencode/plugins/task-status/task-view.ts +606 -0
  236. package/presets/opencode/plugins/task-status/tui.tsx +139 -0
  237. package/presets/opencode/svelte/OPENCODE.md +4 -1
  238. package/presets/opencode/svelte/README.md +1 -0
  239. package/presets/opencode/svelte/adapter-map.json +1 -1
  240. package/presets/opencode/svelte/hooks/README.md +4 -2
  241. package/presets/opencode/svelte/hooks/chain-team-phases.sh +225 -0
  242. package/presets/opencode/svelte/rules/agent-team-orchestrator.md +1 -0
  243. package/presets/zcode/android-kotlin/adapter-map.json +1 -1
  244. package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +225 -0
  245. package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +1 -0
  246. package/presets/zcode/go/adapter-map.json +1 -1
  247. package/presets/zcode/go/hooks/chain-team-phases.sh +225 -0
  248. package/presets/zcode/go/rules/agent-team-orchestrator.md +1 -0
  249. package/presets/zcode/ios-swift/adapter-map.json +1 -1
  250. package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +225 -0
  251. package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +1 -0
  252. package/presets/zcode/java/adapter-map.json +1 -1
  253. package/presets/zcode/java/hooks/chain-team-phases.sh +225 -0
  254. package/presets/zcode/java/rules/agent-team-orchestrator.md +1 -0
  255. package/presets/zcode/mcp-ts/adapter-map.json +1 -1
  256. package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +225 -0
  257. package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +1 -0
  258. package/presets/zcode/mol/adapter-map.json +1 -1
  259. package/presets/zcode/mol/hooks/chain-team-phases.sh +225 -0
  260. package/presets/zcode/mol/rules/agent-team-orchestrator.md +1 -0
  261. package/presets/zcode/next/adapter-map.json +9 -1
  262. package/presets/zcode/next/agents/code-reviewer.md +1 -0
  263. package/presets/zcode/next/agents/mockup-reviewer.md +2 -1
  264. package/presets/zcode/next/agents/task-analyst.md +2 -0
  265. package/presets/zcode/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -0
  266. package/presets/zcode/next/ai-local/rules-library/ui-change-review-gate.md +1 -0
  267. package/presets/zcode/next/commands/task.md +7 -1
  268. package/presets/zcode/next/commands/technical-retro.md +7 -1
  269. package/presets/zcode/next/commands/upstream-research.md +1 -1
  270. package/presets/zcode/next/hooks/chain-team-phases.sh +225 -0
  271. package/presets/zcode/next/rules/agent-team-orchestrator.md +1 -0
  272. package/presets/zcode/next/skills/figma-fidelity/SKILL.md +4 -1
  273. package/presets/zcode/next/skills/mockup-review/SKILL.md +4 -0
  274. package/presets/zcode/next/team/README.md +5 -1
  275. package/presets/zcode/next/team/upstream/jobs.json +34 -0
  276. package/presets/zcode/nuxt/adapter-map.json +1 -1
  277. package/presets/zcode/nuxt/hooks/chain-team-phases.sh +225 -0
  278. package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +1 -0
  279. package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
  280. package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +225 -0
  281. package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +1 -0
  282. package/presets/zcode/php-laravel/adapter-map.json +1 -1
  283. package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +225 -0
  284. package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +1 -0
  285. package/presets/zcode/svelte/adapter-map.json +1 -1
  286. package/presets/zcode/svelte/hooks/chain-team-phases.sh +225 -0
  287. package/presets/zcode/svelte/rules/agent-team-orchestrator.md +1 -0
  288. package/scripts/aggregate-agent-task-metrics.mjs +48 -4
@@ -0,0 +1,606 @@
1
+ import fs from "node:fs"
2
+ import type { Dirent } from "node:fs"
3
+ import path from "node:path"
4
+ import { createEtaStats, estimateEta } from "./eta"
5
+ import type { EtaStats } from "./eta"
6
+
7
+ export type TaskTone = "success" | "warning" | "error" | "muted"
8
+
9
+ export type TaskField = { label: string; value: string; tone?: TaskTone }
10
+
11
+ export type TaskView = {
12
+ fields: TaskField[]
13
+ summary: string
14
+ tone: TaskTone
15
+ slug?: string
16
+ root?: string
17
+ stoppable?: boolean
18
+ }
19
+
20
+ export type TaskStore = { view: TaskView | null | undefined }
21
+
22
+ export type MemoryStorage = {
23
+ memory: <T>(key: string, options: { initial: T }) => [T, (mutate: (draft: T) => void) => void]
24
+ }
25
+
26
+ export type TaskWatcherOptions = {
27
+ directory: () => string | undefined
28
+ sessionID: () => string | undefined
29
+ sessionTitle: (sessionID: string) => string | undefined
30
+ userTexts: (sessionID: string) => Promise<string[]>
31
+ }
32
+
33
+ type Attempt = {
34
+ agent?: string
35
+ stepIndex?: number
36
+ attempt?: number
37
+ startedAt?: string
38
+ }
39
+
40
+ type Status = {
41
+ state?: string
42
+ pipelineIndex?: number
43
+ currentAgent?: string | null
44
+ awaitingHumanGate?: boolean
45
+ activeHumanGateEventId?: string | null
46
+ activeAttempts?: Record<string, Attempt>
47
+ lastCompletedAttempt?: { attemptId?: string; completedAt?: string }
48
+ updatedAt?: string
49
+ }
50
+
51
+ type Pipeline = {
52
+ steps?: { agent?: string | string[]; label?: string; parallel?: boolean }[]
53
+ }
54
+
55
+ type MetricEvent = {
56
+ type?: string
57
+ at?: string
58
+ eventId?: string
59
+ attemptId?: string
60
+ agent?: string
61
+ role?: string
62
+ durationMs?: number
63
+ stepIndex?: number
64
+ }
65
+
66
+ type Metrics = { events?: MetricEvent[] }
67
+
68
+ type PromptEntry = { slug: string; texts: string[]; updatedAt: number }
69
+
70
+ const TEAM_REL = path.join(".ai.local", "team")
71
+ const TICK_MS = 1000
72
+ const SYNC_MS = 5000
73
+ const INDEX_MS = 30000
74
+ const STALE_ATTEMPT_MS = 6 * 60 * 60 * 1000
75
+ const STALE_GATE_MS = 24 * 60 * 60 * 1000
76
+ const MIN_PARTIAL = 24
77
+ const TERMINAL = new Set(["completed"])
78
+
79
+ const MARKER: Record<string, string> = {
80
+ in_progress: "●",
81
+ awaiting_approval: "⏸",
82
+ awaiting_artifact_receipt: "◌",
83
+ changes_requested: "⚠",
84
+ validation_failed: "✕",
85
+ blocked: "■",
86
+ completed: "✓",
87
+ }
88
+
89
+ const LABEL: Record<string, string> = {
90
+ in_progress: "running",
91
+ awaiting_approval: "awaiting gate",
92
+ awaiting_artifact_receipt: "awaiting receipt",
93
+ changes_requested: "changes requested",
94
+ validation_failed: "validation failed",
95
+ blocked: "blocked",
96
+ completed: "done",
97
+ }
98
+
99
+ const cache = new Map<string, { mtimeMs: number; value: unknown }>()
100
+
101
+ const readJson = <T>(file: string): T | null => {
102
+ try {
103
+ const { mtimeMs } = fs.statSync(file)
104
+ const hit = cache.get(file)
105
+ if (hit && hit.mtimeMs === mtimeMs) return hit.value as T
106
+ const value = JSON.parse(fs.readFileSync(file, "utf8")) as T
107
+ cache.set(file, { mtimeMs, value })
108
+ return value
109
+ } catch {
110
+ cache.delete(file)
111
+ return null
112
+ }
113
+ }
114
+
115
+ const findTeamRoot = (start: string): string | null => {
116
+ let dir = path.resolve(start)
117
+ for (;;) {
118
+ const candidate = path.join(dir, TEAM_REL)
119
+ if (fs.existsSync(path.join(candidate, "active-task.json")) || fs.existsSync(path.join(candidate, "tasks"))) {
120
+ return candidate
121
+ }
122
+ const parent = path.dirname(dir)
123
+ if (parent === dir) return null
124
+ dir = parent
125
+ }
126
+ }
127
+
128
+ const statusFile = (root: string, slug: string) => path.join(root, "tasks", slug, "status.json")
129
+
130
+ const overlayDir = (root: string): string | null => {
131
+ const overlay = path.dirname(root)
132
+ return path.basename(overlay) === ".ai.local" ? overlay : null
133
+ }
134
+
135
+ const pauseSentinel = (root: string): boolean => {
136
+ const overlay = overlayDir(root)
137
+ if (!overlay) return false
138
+ return ["STOP", "ESTOP"].some((name) => {
139
+ try {
140
+ return fs.statSync(path.join(overlay, name)).isFile()
141
+ } catch (error) {
142
+ return (error as { code?: string }).code !== "ENOENT"
143
+ }
144
+ })
145
+ }
146
+
147
+ export const engagePause = (root: string): boolean => {
148
+ const overlay = overlayDir(root)
149
+ if (!overlay) return false
150
+ try {
151
+ fs.writeFileSync(
152
+ path.join(overlay, "STOP"),
153
+ JSON.stringify({ reason: "soft stop requested from the task sidebar" }),
154
+ "utf8",
155
+ )
156
+ return true
157
+ } catch {
158
+ return false
159
+ }
160
+ }
161
+
162
+ export const clearPause = (root: string): boolean => {
163
+ const overlay = overlayDir(root)
164
+ if (!overlay) return false
165
+ let cleared = false
166
+ for (const name of ["STOP", "ESTOP"]) {
167
+ const file = path.join(overlay, name)
168
+ if (!fs.existsSync(file)) continue
169
+ try {
170
+ fs.rmSync(file, { force: true })
171
+ cleared = true
172
+ } catch {
173
+ // leave an undeletable sentinel for the hook to report
174
+ }
175
+ }
176
+ return cleared
177
+ }
178
+
179
+ // <!-- i18n-keep: E4 — Russian resume keywords -->
180
+ const RESUME_WORD = /^\s*(продолжай|продолжить|continue|resume|дальше|го)\s*[.!]?\s*$/i
181
+ const RESUME_COMMAND = /(?:^|\s)\/task-continue(?:\s|$)/i
182
+
183
+ const resumeIntent = (text: string): boolean => RESUME_WORD.test(text) || RESUME_COMMAND.test(text)
184
+
185
+ const toMs = (value?: string): number | undefined => {
186
+ if (!value) return undefined
187
+ const parsed = Date.parse(value)
188
+ return Number.isFinite(parsed) ? parsed : undefined
189
+ }
190
+
191
+ const formatDuration = (ms: number): string => {
192
+ const seconds = Math.max(0, Math.floor(ms / 1000))
193
+ if (seconds < 60) return `${seconds}s`
194
+ const minutes = Math.floor(seconds / 60)
195
+ if (minutes < 60) return `${minutes}m`
196
+ const hours = Math.floor(minutes / 60)
197
+ if (hours < 48) return `${hours}h ${String(minutes % 60).padStart(2, "0")}m`
198
+ return `${Math.floor(hours / 24)}d ${hours % 24}h`
199
+ }
200
+
201
+ const formatAge = (ms: number): string => `${formatDuration(ms)} ago`
202
+
203
+ const formatEta = (eta: { p50Ms: number; p90Ms: number }): string =>
204
+ eta.p90Ms > eta.p50Ms * 1.5
205
+ ? `~${formatDuration(eta.p50Ms)} · p90 ${formatDuration(eta.p90Ms)}`
206
+ : `~${formatDuration(eta.p50Ms)}`
207
+
208
+ const progressBar = (value: number, total: number, width = 8): string => {
209
+ if (total <= 0) return ""
210
+ const filled = Math.max(0, Math.min(width, Math.round((value / total) * width)))
211
+ return `${"█".repeat(filled)}${"░".repeat(width - filled)}`
212
+ }
213
+
214
+ const truncate = (value: string, max: number): string =>
215
+ value.length > max ? `${value.slice(0, max - 1)}…` : value
216
+
217
+ const normalize = (text: string): string => text.toLowerCase().replace(/\s+/g, " ").trim()
218
+
219
+ const stripFrontmatter = (text: string): string =>
220
+ text.startsWith("---") ? text.replace(/^---[\s\S]*?\n---\s*/, "") : text
221
+
222
+ const promptText = (raw: string): string => {
223
+ const lines = stripFrontmatter(raw).split("\n")
224
+ const start = lines.findIndex((line) => /^#+\s*Verbatim prompt\s*$/i.test(line.trim()))
225
+ const slice = start >= 0 ? lines.slice(start + 1) : lines
226
+ const kept: string[] = []
227
+ for (const line of slice) {
228
+ if (/^#+\s/.test(line)) {
229
+ if (start >= 0) break
230
+ continue
231
+ }
232
+ const trimmed = line.trim()
233
+ const meta = /^(language|slug|created|source|command|capturedAt):/i.test(trimmed)
234
+ if (trimmed === "" || trimmed.startsWith("```") || meta) continue
235
+ kept.push(trimmed)
236
+ }
237
+ return kept.join("\n")
238
+ }
239
+
240
+ const logTexts = (raw: string): string[] =>
241
+ [...raw.matchAll(/```(?:text)?\n([\s\S]*?)```/g)].map((match) => match[1])
242
+
243
+ const buildPromptIndex = (root: string): PromptEntry[] => {
244
+ const dir = path.join(root, "tasks")
245
+ let entries: Dirent[]
246
+ try {
247
+ entries = fs.readdirSync(dir, { withFileTypes: true })
248
+ } catch {
249
+ return []
250
+ }
251
+ const index: PromptEntry[] = []
252
+ for (const entry of entries) {
253
+ if (!entry.isDirectory()) continue
254
+ const taskDir = path.join(dir, entry.name)
255
+ const texts: string[] = []
256
+ let updatedAt = 0
257
+ for (const file of ["prompt.md", "prompt-log.md"]) {
258
+ const filePath = path.join(taskDir, file)
259
+ try {
260
+ const stat = fs.statSync(filePath)
261
+ updatedAt = Math.max(updatedAt, stat.mtimeMs)
262
+ const raw = fs.readFileSync(filePath, "utf8")
263
+ const parts = file === "prompt.md" ? [promptText(raw)] : logTexts(raw)
264
+ for (const part of parts) {
265
+ const text = normalize(part)
266
+ if (text.length > 0) texts.push(text)
267
+ }
268
+ } catch {
269
+ // prompt files are optional
270
+ }
271
+ }
272
+ if (texts.length === 0) continue
273
+ const status = readJson<Status>(statusFile(root, entry.name))
274
+ updatedAt = Math.max(updatedAt, toMs(status?.updatedAt) ?? 0)
275
+ index.push({ slug: entry.name, texts, updatedAt })
276
+ }
277
+ return index
278
+ }
279
+
280
+ const matches = (message: string, prompt: string): boolean => {
281
+ if (message === prompt) return true
282
+ if (prompt.length >= MIN_PARTIAL && message.includes(prompt)) return true
283
+ if (message.length >= MIN_PARTIAL && prompt.includes(message)) return true
284
+ return false
285
+ }
286
+
287
+ const matchTask = (index: PromptEntry[], messages: string[]): string | undefined => {
288
+ const normalized = messages.map(normalize).filter(Boolean)
289
+ if (normalized.length === 0) return undefined
290
+
291
+ let continued: string | undefined
292
+ for (const message of normalized) {
293
+ const match = /(?:^|\s)\/task-continue\s+([a-z0-9][a-z0-9-]*)/i.exec(message)
294
+ if (match) continued = match[1]
295
+ }
296
+ if (continued) return continued
297
+
298
+ let best: PromptEntry | undefined
299
+ let bestScore = 0
300
+ for (const entry of index) {
301
+ let score = 0
302
+ for (const message of normalized) {
303
+ for (const prompt of entry.texts) {
304
+ if (matches(message, prompt)) score = Math.max(score, prompt.length)
305
+ }
306
+ }
307
+ if (score === 0) continue
308
+ if (!best || entry.updatedAt > best.updatedAt || (entry.updatedAt === best.updatedAt && score > bestScore)) {
309
+ best = entry
310
+ bestScore = score
311
+ }
312
+ }
313
+ return best?.slug
314
+ }
315
+
316
+ const roleForAgent = (agent: string): string => {
317
+ if (/analyst|architect|router|migration/.test(agent)) return "planning"
318
+ if (/verifier/.test(agent)) return "validation"
319
+ if (/reviewer|auditor/.test(agent)) return "review"
320
+ if (/test|qa/.test(agent)) return "testing"
321
+ if (/writer/.test(agent)) return "docs"
322
+ return "implementation"
323
+ }
324
+
325
+ const actorOf = (
326
+ events: MetricEvent[],
327
+ attemptId: string | undefined,
328
+ fallbackAgent: string | undefined,
329
+ ): { agent: string | undefined; role: string | null } => {
330
+ const event = attemptId
331
+ ? events.findLast((item) => item.type === "attempt_started" && item.attemptId === attemptId)
332
+ : undefined
333
+ const agent = event?.agent ?? fallbackAgent
334
+ return { agent, role: event?.role ?? (agent ? roleForAgent(agent) : null) }
335
+ }
336
+
337
+ // Agent-written metrics can carry a `task_started` in the future; a future clock would freeze elapsed at 0s.
338
+ const taskStartedAt = (events: MetricEvent[], status: Status, now: number): number | undefined => {
339
+ const times = [
340
+ ...events.map((event) => toMs(event.at)),
341
+ ...Object.values(status.activeAttempts ?? {}).map((attempt) => toMs(attempt.startedAt)),
342
+ toMs(status.updatedAt),
343
+ ].filter((value): value is number => value !== undefined && value <= now)
344
+ return times.length > 0 ? Math.min(...times) : undefined
345
+ }
346
+
347
+ const toneFor = (state: string, stale: boolean): TaskTone => {
348
+ if (stale) return "muted"
349
+ if (state === "in_progress" || state === "completed") return "success"
350
+ if (state === "awaiting_approval" || state === "awaiting_artifact_receipt") return "warning"
351
+ if (state === "changes_requested" || state === "validation_failed" || state === "blocked") return "error"
352
+ return "muted"
353
+ }
354
+
355
+ const buildTaskView = (
356
+ root: string,
357
+ slug: string,
358
+ status: Status,
359
+ now: number,
360
+ etaStats?: EtaStats,
361
+ ): TaskView => {
362
+ const taskDir = path.join(root, "tasks", slug)
363
+ const pipeline = readJson<Pipeline>(path.join(taskDir, "pipeline.json"))
364
+ const events = readJson<Metrics>(path.join(taskDir, "metrics.json"))?.events ?? []
365
+
366
+ const state = status.state ?? "in_progress"
367
+ const done = TERMINAL.has(state)
368
+ const sentinel = !done && pauseSentinel(root)
369
+ const paused = state === "paused" || sentinel
370
+
371
+ const attempts = Object.entries(status.activeAttempts ?? {})
372
+ .map(([id, attempt]) => ({ id, ...attempt }))
373
+ .sort((left, right) => (toMs(left.startedAt) ?? 0) - (toMs(right.startedAt) ?? 0))
374
+ const current = attempts.at(-1)
375
+
376
+ const currentStarted = toMs(current?.startedAt)
377
+ const currentStart = currentStarted === undefined ? undefined : Math.min(currentStarted, now)
378
+ const gateEvent = status.awaitingHumanGate
379
+ ? events.find((event) => event.type === "human_gate_started" && event.eventId === status.activeHumanGateEventId)
380
+ : undefined
381
+ const gateStarted = status.awaitingHumanGate ? toMs(gateEvent?.at) ?? toMs(status.updatedAt) : undefined
382
+ const gateStart = gateStarted === undefined ? undefined : Math.min(gateStarted, now)
383
+ const updatedAt = Math.min(toMs(status.updatedAt) ?? now, now)
384
+
385
+ const startedAt = taskStartedAt(events, status, now)
386
+ const finishedAt = done
387
+ ? Math.min(toMs(events.find((event) => event.type === "task_completed")?.at) ?? updatedAt, now)
388
+ : now
389
+ const elapsed = startedAt === undefined ? undefined : Math.max(0, finishedAt - startedAt)
390
+
391
+ const freshness = currentStart ?? gateStart ?? updatedAt
392
+ const stale = !done && !paused && now - freshness > (status.awaitingHumanGate ? STALE_GATE_MS : STALE_ATTEMPT_MS)
393
+
394
+ const actor = actorOf(
395
+ events,
396
+ current?.id ?? status.lastCompletedAttempt?.attemptId,
397
+ current?.agent ?? status.currentAgent ?? undefined,
398
+ )
399
+ const totalSteps = pipeline?.steps?.length
400
+ const stepNumber = done
401
+ ? totalSteps
402
+ : current?.stepIndex !== undefined
403
+ ? current.stepIndex + 1
404
+ : status.pipelineIndex !== undefined
405
+ ? status.pipelineIndex + 1
406
+ : undefined
407
+
408
+ const staleFor = now - freshness
409
+
410
+ const statusLine =
411
+ state === "paused"
412
+ ? `⏸ paused${elapsed === undefined ? "" : ` · ${formatDuration(elapsed)}`}`
413
+ : sentinel
414
+ ? "⏸ stopping · in-flight attempt finishes"
415
+ : stale
416
+ ? `◌ stale · ${formatAge(staleFor)}`
417
+ : [
418
+ `${MARKER[state] ?? "●"} ${LABEL[state] ?? state}`,
419
+ elapsed === undefined ? null : formatDuration(elapsed),
420
+ ]
421
+ .filter(Boolean)
422
+ .join(" · ")
423
+
424
+ const agents = attempts.map((attempt) => attempt.agent).filter((agent): agent is string => Boolean(agent))
425
+ const agentText = agents.length > 1 ? `${agents[0]} +${agents.length - 1}` : agents[0] ?? actor.agent
426
+
427
+ let stepLine: string
428
+ if (state === "paused") {
429
+ stepLine = `last update ${formatAge(now - updatedAt)}`
430
+ } else if (status.awaitingHumanGate && gateStart) {
431
+ stepLine = `gate · waiting ${formatDuration(now - gateStart)}`
432
+ } else if (stale) {
433
+ stepLine = `last update ${formatAge(now - updatedAt)}`
434
+ } else if (current && currentStart) {
435
+ const progress = stepNumber
436
+ ? `${stepNumber}/${totalSteps ?? "?"} ${progressBar(stepNumber, totalSteps ?? 0)}`
437
+ : "?"
438
+ stepLine = [
439
+ progress.trim(),
440
+ current.attempt ? `attempt ${current.attempt}` : null,
441
+ formatDuration(now - currentStart),
442
+ ]
443
+ .filter(Boolean)
444
+ .join(" · ")
445
+ } else {
446
+ stepLine = `updated ${formatAge(now - updatedAt)}`
447
+ }
448
+
449
+ const tone = paused ? "warning" : toneFor(state, stale)
450
+ const eta =
451
+ etaStats && !done && !paused && !stale && !status.awaitingHumanGate
452
+ ? estimateEta(pipeline?.steps ?? [], status, events, etaStats, now)
453
+ : null
454
+ const progressLabel = !done && totalSteps && stepNumber ? `${stepNumber}/${totalSteps}` : null
455
+ const summary =
456
+ state === "paused"
457
+ ? ["paused", elapsed === undefined ? null : formatDuration(elapsed)].filter(Boolean).join(" · ")
458
+ : sentinel
459
+ ? "stopping"
460
+ : stale
461
+ ? `stale · ${formatAge(staleFor)}`
462
+ : [LABEL[state] ?? state, progressLabel, elapsed === undefined ? null : formatDuration(elapsed)]
463
+ .filter(Boolean)
464
+ .join(" · ")
465
+
466
+ return {
467
+ fields: [
468
+ { label: "task", value: truncate(slug, 34) },
469
+ { label: "state", value: statusLine, tone },
470
+ { label: "role", value: actor.role ?? "—" },
471
+ { label: "agent", value: agentText ?? "—" },
472
+ { label: "step", value: stepLine },
473
+ ...(eta ? [{ label: "eta", value: formatEta(eta) }] : []),
474
+ ],
475
+ summary,
476
+ tone,
477
+ slug,
478
+ root,
479
+ stoppable: !done && !paused,
480
+ }
481
+ }
482
+
483
+ const buildNoteView = (root: string, slug: string, now: number): TaskView => {
484
+ let updatedAt = now
485
+ try {
486
+ updatedAt = fs.statSync(path.join(root, "tasks", slug, "prompt.md")).mtimeMs
487
+ } catch {
488
+ // prompt.md is optional
489
+ }
490
+ const elapsed = now - updatedAt
491
+ return {
492
+ fields: [
493
+ { label: "task", value: truncate(slug, 34) },
494
+ { label: "state", value: `note · ${formatDuration(elapsed)}`, tone: "muted" },
495
+ { label: "step", value: `prompt ${formatAge(elapsed)}` },
496
+ ],
497
+ summary: `note · ${formatDuration(elapsed)}`,
498
+ tone: "muted",
499
+ slug,
500
+ root,
501
+ }
502
+ }
503
+
504
+ const buildPromptView = (title: string, texts: string[]): TaskView => {
505
+ const named = title.trim() !== "" && title.trim().toLowerCase() !== "untitled session"
506
+ const value = named ? title.trim() : texts[0]?.replace(/\s+/g, " ").trim() || "no prompt"
507
+ return {
508
+ fields: [
509
+ { label: "prompt", value: truncate(value, 40) },
510
+ { label: "state", value: "no task" },
511
+ ],
512
+ summary: "no task",
513
+ tone: "muted",
514
+ }
515
+ }
516
+
517
+ const buildSessionView = (
518
+ root: string,
519
+ sessionID: string,
520
+ texts: string[],
521
+ now: number,
522
+ options: TaskWatcherOptions,
523
+ index: PromptEntry[],
524
+ etaStats?: EtaStats,
525
+ ): TaskView => {
526
+ const slug = matchTask(index, texts)
527
+ if (slug && fs.existsSync(path.join(root, "tasks", slug))) {
528
+ const status = readJson<Status>(statusFile(root, slug))
529
+ return status ? buildTaskView(root, slug, status, now, etaStats) : buildNoteView(root, slug, now)
530
+ }
531
+ return buildPromptView(options.sessionTitle(sessionID) ?? "", texts)
532
+ }
533
+
534
+ export const createTaskWatcher = (storage: MemoryStorage, options: TaskWatcherOptions) => {
535
+ const [state, update] = storage.memory<TaskStore>("view", { initial: { view: undefined } })
536
+ let index: PromptEntry[] = []
537
+ let indexAt = 0
538
+ let etaStats: EtaStats | undefined
539
+ let etaAt = 0
540
+ let session: { id: string; texts: string[]; fetchedAt: number; loading: boolean; resumeFor?: string } | undefined
541
+
542
+ const sessionState = (id: string) => {
543
+ if (!session || session.id !== id) session = { id, texts: [], fetchedAt: 0, loading: false }
544
+ return session
545
+ }
546
+
547
+ const syncSession = (root: string, id: string) => {
548
+ const current = sessionState(id)
549
+ if (current.loading || Date.now() - current.fetchedAt < SYNC_MS) return
550
+ current.loading = true
551
+ options
552
+ .userTexts(id)
553
+ .then((texts) => {
554
+ current.texts = texts
555
+ current.fetchedAt = Date.now()
556
+ const latest = texts.at(-1)?.trim() ?? ""
557
+ const key = `${texts.length}:${latest}`
558
+ if (latest && current.resumeFor !== key && resumeIntent(latest)) {
559
+ current.resumeFor = key
560
+ if (pauseSentinel(root)) clearPause(root)
561
+ }
562
+ })
563
+ .catch(() => {
564
+ current.fetchedAt = Date.now() - SYNC_MS + 1000
565
+ })
566
+ .finally(() => {
567
+ current.loading = false
568
+ })
569
+ }
570
+
571
+ const refresh = () => {
572
+ const start = options.directory()
573
+ const root = start ? findTeamRoot(start) : null
574
+ if (!root) {
575
+ update((draft) => {
576
+ draft.view = undefined
577
+ })
578
+ return
579
+ }
580
+ const now = Date.now()
581
+ if (now - indexAt > INDEX_MS) {
582
+ index = buildPromptIndex(root)
583
+ indexAt = now
584
+ }
585
+ if (now - etaAt > INDEX_MS) {
586
+ etaStats = createEtaStats(root, readJson)
587
+ etaAt = now
588
+ }
589
+ const sessionID = options.sessionID()
590
+ if (!sessionID) {
591
+ update((draft) => {
592
+ draft.view = undefined
593
+ })
594
+ return
595
+ }
596
+ const current = sessionState(sessionID)
597
+ syncSession(root, sessionID)
598
+ update((draft) => {
599
+ draft.view = buildSessionView(root, sessionID, current.texts, now, options, index, etaStats)
600
+ })
601
+ }
602
+
603
+ refresh()
604
+ const timer = setInterval(refresh, TICK_MS)
605
+ return { state, stop: () => clearInterval(timer) }
606
+ }