@apralabs/apra-fleet 0.3.6 → 0.4.1

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 (826) hide show
  1. package/README.md +378 -252
  2. package/dist/agents/backlog-groomer.md +303 -0
  3. package/dist/agents/ci-watcher.md +13 -1
  4. package/dist/agents/deployer.md +66 -13
  5. package/dist/agents/doer.md +67 -8
  6. package/dist/agents/harvester.md +22 -3
  7. package/dist/agents/integ-test-runner.md +166 -60
  8. package/dist/agents/kb-reconciler.md +216 -0
  9. package/dist/agents/plan-reviewer.md +88 -18
  10. package/dist/agents/planner.md +182 -19
  11. package/dist/agents/regression-test-runner.md +234 -0
  12. package/dist/agents/reviewer.md +125 -9
  13. package/dist/agents/schemas/backlog-groomer-input.json +35 -0
  14. package/dist/agents/schemas/backlog-groomer-output.json +164 -0
  15. package/dist/agents/schemas/doer-output.json +63 -3
  16. package/dist/agents/schemas/harvester-output.json +59 -2
  17. package/dist/agents/schemas/integ-test-runner-output.json +34 -0
  18. package/dist/agents/schemas/kb-reconciler-output.json +87 -0
  19. package/dist/agents/schemas/planner-output.json +65 -0
  20. package/dist/agents/schemas/regression-test-runner-input.json +15 -0
  21. package/dist/agents/schemas/regression-test-runner-output.json +50 -0
  22. package/dist/agents/schemas/reviewer-output.json +108 -7
  23. package/dist/cli/agent-transform.d.ts +1 -0
  24. package/dist/cli/agent-transform.d.ts.map +1 -1
  25. package/dist/cli/agent-transform.js +77 -0
  26. package/dist/cli/agent-transform.js.map +1 -1
  27. package/dist/cli/auth.d.ts +3 -0
  28. package/dist/cli/auth.d.ts.map +1 -1
  29. package/dist/cli/auth.js +181 -5
  30. package/dist/cli/auth.js.map +1 -1
  31. package/dist/cli/config.d.ts +5 -1
  32. package/dist/cli/config.d.ts.map +1 -1
  33. package/dist/cli/config.js +7 -1
  34. package/dist/cli/config.js.map +1 -1
  35. package/dist/cli/dolt-install.d.ts +91 -0
  36. package/dist/cli/dolt-install.d.ts.map +1 -0
  37. package/dist/cli/dolt-install.js +334 -0
  38. package/dist/cli/dolt-install.js.map +1 -0
  39. package/dist/cli/install-guard.d.ts +29 -0
  40. package/dist/cli/install-guard.d.ts.map +1 -0
  41. package/dist/cli/install-guard.js +153 -0
  42. package/dist/cli/install-guard.js.map +1 -0
  43. package/dist/cli/install.d.ts +45 -3
  44. package/dist/cli/install.d.ts.map +1 -1
  45. package/dist/cli/install.js +736 -109
  46. package/dist/cli/install.js.map +1 -1
  47. package/dist/cli/join.d.ts +12 -0
  48. package/dist/cli/join.d.ts.map +1 -0
  49. package/dist/cli/join.js +87 -0
  50. package/dist/cli/join.js.map +1 -0
  51. package/dist/cli/kb-commit.d.ts +12 -0
  52. package/dist/cli/kb-commit.d.ts.map +1 -0
  53. package/dist/cli/kb-commit.js +53 -0
  54. package/dist/cli/kb-commit.js.map +1 -0
  55. package/dist/cli/kb-directives.d.ts +17 -0
  56. package/dist/cli/kb-directives.d.ts.map +1 -0
  57. package/dist/cli/kb-directives.js +146 -0
  58. package/dist/cli/kb-directives.js.map +1 -0
  59. package/dist/cli/kb-import.d.ts +13 -0
  60. package/dist/cli/kb-import.d.ts.map +1 -0
  61. package/dist/cli/kb-import.js +56 -0
  62. package/dist/cli/kb-import.js.map +1 -0
  63. package/dist/cli/register-member.d.ts +2 -0
  64. package/dist/cli/register-member.d.ts.map +1 -0
  65. package/dist/cli/register-member.js +193 -0
  66. package/dist/cli/register-member.js.map +1 -0
  67. package/dist/cli/restart.d.ts +2 -0
  68. package/dist/cli/restart.d.ts.map +1 -0
  69. package/dist/cli/restart.js +7 -0
  70. package/dist/cli/restart.js.map +1 -0
  71. package/dist/cli/spoke.d.ts +35 -0
  72. package/dist/cli/spoke.d.ts.map +1 -0
  73. package/dist/cli/spoke.js +212 -0
  74. package/dist/cli/spoke.js.map +1 -0
  75. package/dist/cli/start.d.ts +2 -0
  76. package/dist/cli/start.d.ts.map +1 -0
  77. package/dist/cli/start.js +92 -0
  78. package/dist/cli/start.js.map +1 -0
  79. package/dist/cli/status.d.ts +2 -0
  80. package/dist/cli/status.d.ts.map +1 -0
  81. package/dist/cli/status.js +83 -0
  82. package/dist/cli/status.js.map +1 -0
  83. package/dist/cli/stop.d.ts +2 -0
  84. package/dist/cli/stop.d.ts.map +1 -0
  85. package/dist/cli/stop.js +51 -0
  86. package/dist/cli/stop.js.map +1 -0
  87. package/dist/cli/uninstall.d.ts.map +1 -1
  88. package/dist/cli/uninstall.js +120 -9
  89. package/dist/cli/uninstall.js.map +1 -1
  90. package/dist/cli/update.d.ts.map +1 -1
  91. package/dist/cli/update.js +10 -1
  92. package/dist/cli/update.js.map +1 -1
  93. package/dist/cli/watch.d.ts +53 -4
  94. package/dist/cli/watch.d.ts.map +1 -1
  95. package/dist/cli/watch.js +118 -17
  96. package/dist/cli/watch.js.map +1 -1
  97. package/dist/cli/workflow-assets.d.ts +37 -0
  98. package/dist/cli/workflow-assets.d.ts.map +1 -0
  99. package/dist/cli/workflow-assets.js +144 -0
  100. package/dist/cli/workflow-assets.js.map +1 -0
  101. package/dist/cli/workflow.d.ts +75 -0
  102. package/dist/cli/workflow.d.ts.map +1 -0
  103. package/dist/cli/workflow.js +397 -0
  104. package/dist/cli/workflow.js.map +1 -0
  105. package/dist/commands/kb-server.d.ts +8 -0
  106. package/dist/commands/kb-server.d.ts.map +1 -0
  107. package/dist/commands/kb-server.js +221 -0
  108. package/dist/commands/kb-server.js.map +1 -0
  109. package/dist/hub-service/activity.d.ts +30 -0
  110. package/dist/hub-service/activity.d.ts.map +1 -0
  111. package/dist/hub-service/activity.js +20 -0
  112. package/dist/hub-service/activity.js.map +1 -0
  113. package/dist/hub-service/audit-log.d.ts +19 -0
  114. package/dist/hub-service/audit-log.d.ts.map +1 -0
  115. package/dist/hub-service/audit-log.js +13 -0
  116. package/dist/hub-service/audit-log.js.map +1 -0
  117. package/dist/hub-service/db/pool.d.ts +19 -0
  118. package/dist/hub-service/db/pool.d.ts.map +1 -0
  119. package/dist/hub-service/db/pool.js +53 -0
  120. package/dist/hub-service/db/pool.js.map +1 -0
  121. package/dist/hub-service/enrollment.d.ts +29 -0
  122. package/dist/hub-service/enrollment.d.ts.map +1 -0
  123. package/dist/hub-service/enrollment.js +48 -0
  124. package/dist/hub-service/enrollment.js.map +1 -0
  125. package/dist/hub-service/envelope-routes.d.ts +46 -0
  126. package/dist/hub-service/envelope-routes.d.ts.map +1 -0
  127. package/dist/hub-service/envelope-routes.js +94 -0
  128. package/dist/hub-service/envelope-routes.js.map +1 -0
  129. package/dist/hub-service/handlers/installers.d.ts +14 -0
  130. package/dist/hub-service/handlers/installers.d.ts.map +1 -0
  131. package/dist/hub-service/handlers/installers.js +8 -0
  132. package/dist/hub-service/handlers/installers.js.map +1 -0
  133. package/dist/hub-service/http-server.d.ts +31 -0
  134. package/dist/hub-service/http-server.d.ts.map +1 -0
  135. package/dist/hub-service/http-server.js +711 -0
  136. package/dist/hub-service/http-server.js.map +1 -0
  137. package/dist/hub-service/hub-jwt.d.ts +30 -0
  138. package/dist/hub-service/hub-jwt.d.ts.map +1 -0
  139. package/dist/hub-service/hub-jwt.js +105 -0
  140. package/dist/hub-service/hub-jwt.js.map +1 -0
  141. package/dist/hub-service/jwt-revocation.d.ts +20 -0
  142. package/dist/hub-service/jwt-revocation.d.ts.map +1 -0
  143. package/dist/hub-service/jwt-revocation.js +18 -0
  144. package/dist/hub-service/jwt-revocation.js.map +1 -0
  145. package/dist/hub-service/machines.d.ts +16 -0
  146. package/dist/hub-service/machines.d.ts.map +1 -0
  147. package/dist/hub-service/machines.js +14 -0
  148. package/dist/hub-service/machines.js.map +1 -0
  149. package/dist/hub-service/main.d.ts +3 -0
  150. package/dist/hub-service/main.d.ts.map +1 -0
  151. package/dist/hub-service/main.js +64 -0
  152. package/dist/hub-service/main.js.map +1 -0
  153. package/dist/hub-service/member-tokens.d.ts +11 -0
  154. package/dist/hub-service/member-tokens.d.ts.map +1 -0
  155. package/dist/hub-service/member-tokens.js +49 -0
  156. package/dist/hub-service/member-tokens.js.map +1 -0
  157. package/dist/hub-service/member-view.d.ts +20 -0
  158. package/dist/hub-service/member-view.d.ts.map +1 -0
  159. package/dist/hub-service/member-view.js +76 -0
  160. package/dist/hub-service/member-view.js.map +1 -0
  161. package/dist/hub-service/members.d.ts +44 -0
  162. package/dist/hub-service/members.d.ts.map +1 -0
  163. package/dist/hub-service/members.js +25 -0
  164. package/dist/hub-service/members.js.map +1 -0
  165. package/dist/hub-service/presence.d.ts +40 -0
  166. package/dist/hub-service/presence.d.ts.map +1 -0
  167. package/dist/hub-service/presence.js +44 -0
  168. package/dist/hub-service/presence.js.map +1 -0
  169. package/dist/hub-service/project-view.d.ts +12 -0
  170. package/dist/hub-service/project-view.d.ts.map +1 -0
  171. package/dist/hub-service/project-view.js +34 -0
  172. package/dist/hub-service/project-view.js.map +1 -0
  173. package/dist/hub-service/projects.d.ts +48 -0
  174. package/dist/hub-service/projects.d.ts.map +1 -0
  175. package/dist/hub-service/projects.js +80 -0
  176. package/dist/hub-service/projects.js.map +1 -0
  177. package/dist/hub-service/relay-queue.d.ts +115 -0
  178. package/dist/hub-service/relay-queue.d.ts.map +1 -0
  179. package/dist/hub-service/relay-queue.js +148 -0
  180. package/dist/hub-service/relay-queue.js.map +1 -0
  181. package/dist/hub-service/session-jwt.d.ts +10 -0
  182. package/dist/hub-service/session-jwt.d.ts.map +1 -0
  183. package/dist/hub-service/session-jwt.js +69 -0
  184. package/dist/hub-service/session-jwt.js.map +1 -0
  185. package/dist/hub-service/usage.d.ts +40 -0
  186. package/dist/hub-service/usage.d.ts.map +1 -0
  187. package/dist/hub-service/usage.js +25 -0
  188. package/dist/hub-service/usage.js.map +1 -0
  189. package/dist/hub-service/users.d.ts +56 -0
  190. package/dist/hub-service/users.d.ts.map +1 -0
  191. package/dist/hub-service/users.js +72 -0
  192. package/dist/hub-service/users.js.map +1 -0
  193. package/dist/hub-service/workspaces.d.ts +20 -0
  194. package/dist/hub-service/workspaces.d.ts.map +1 -0
  195. package/dist/hub-service/workspaces.js +10 -0
  196. package/dist/hub-service/workspaces.js.map +1 -0
  197. package/dist/index.js +254 -132
  198. package/dist/index.js.map +1 -1
  199. package/dist/os/linux.d.ts +14 -0
  200. package/dist/os/linux.d.ts.map +1 -1
  201. package/dist/os/linux.js +80 -4
  202. package/dist/os/linux.js.map +1 -1
  203. package/dist/os/os-commands.d.ts +15 -0
  204. package/dist/os/os-commands.d.ts.map +1 -1
  205. package/dist/os/windows.d.ts +36 -0
  206. package/dist/os/windows.d.ts.map +1 -1
  207. package/dist/os/windows.js +74 -18
  208. package/dist/os/windows.js.map +1 -1
  209. package/dist/paths.d.ts +23 -0
  210. package/dist/paths.d.ts.map +1 -1
  211. package/dist/paths.js +29 -0
  212. package/dist/paths.js.map +1 -1
  213. package/dist/providers/agy.d.ts +20 -2
  214. package/dist/providers/agy.d.ts.map +1 -1
  215. package/dist/providers/agy.js +259 -21
  216. package/dist/providers/agy.js.map +1 -1
  217. package/dist/providers/claude.d.ts +16 -2
  218. package/dist/providers/claude.d.ts.map +1 -1
  219. package/dist/providers/claude.js +283 -16
  220. package/dist/providers/claude.js.map +1 -1
  221. package/dist/providers/codex.d.ts +13 -2
  222. package/dist/providers/codex.d.ts.map +1 -1
  223. package/dist/providers/codex.js +36 -6
  224. package/dist/providers/codex.js.map +1 -1
  225. package/dist/providers/copilot.d.ts +13 -2
  226. package/dist/providers/copilot.d.ts.map +1 -1
  227. package/dist/providers/copilot.js +34 -7
  228. package/dist/providers/copilot.js.map +1 -1
  229. package/dist/providers/email/headers.d.ts +15 -0
  230. package/dist/providers/email/headers.d.ts.map +1 -0
  231. package/dist/providers/email/headers.js +42 -0
  232. package/dist/providers/email/headers.js.map +1 -0
  233. package/dist/providers/email/index.d.ts +18 -0
  234. package/dist/providers/email/index.d.ts.map +1 -0
  235. package/dist/providers/email/index.js +60 -0
  236. package/dist/providers/email/index.js.map +1 -0
  237. package/dist/providers/email/provider.d.ts +49 -0
  238. package/dist/providers/email/provider.d.ts.map +1 -0
  239. package/dist/providers/email/provider.js +2 -0
  240. package/dist/providers/email/provider.js.map +1 -0
  241. package/dist/providers/email/sendgrid.d.ts +12 -0
  242. package/dist/providers/email/sendgrid.d.ts.map +1 -0
  243. package/dist/providers/email/sendgrid.js +67 -0
  244. package/dist/providers/email/sendgrid.js.map +1 -0
  245. package/dist/providers/email/smtp.d.ts +65 -0
  246. package/dist/providers/email/smtp.d.ts.map +1 -0
  247. package/dist/providers/email/smtp.js +373 -0
  248. package/dist/providers/email/smtp.js.map +1 -0
  249. package/dist/providers/gemini.d.ts +13 -2
  250. package/dist/providers/gemini.d.ts.map +1 -1
  251. package/dist/providers/gemini.js +49 -5
  252. package/dist/providers/gemini.js.map +1 -1
  253. package/dist/providers/index.d.ts +1 -0
  254. package/dist/providers/index.d.ts.map +1 -1
  255. package/dist/providers/index.js +3 -0
  256. package/dist/providers/index.js.map +1 -1
  257. package/dist/providers/none.d.ts +61 -0
  258. package/dist/providers/none.d.ts.map +1 -0
  259. package/dist/providers/none.js +124 -0
  260. package/dist/providers/none.js.map +1 -0
  261. package/dist/providers/opencode.d.ts +14 -2
  262. package/dist/providers/opencode.d.ts.map +1 -1
  263. package/dist/providers/opencode.js +104 -4
  264. package/dist/providers/opencode.js.map +1 -1
  265. package/dist/providers/provider.d.ts +156 -1
  266. package/dist/providers/provider.d.ts.map +1 -1
  267. package/dist/providers/provider.js +54 -0
  268. package/dist/providers/provider.js.map +1 -1
  269. package/dist/services/agent-provisioner.d.ts +3 -3
  270. package/dist/services/agent-provisioner.d.ts.map +1 -1
  271. package/dist/services/agent-provisioner.js +11 -7
  272. package/dist/services/agent-provisioner.js.map +1 -1
  273. package/dist/services/auth-socket.d.ts.map +1 -1
  274. package/dist/services/auth-socket.js +2 -0
  275. package/dist/services/auth-socket.js.map +1 -1
  276. package/dist/services/budget-awareness.d.ts +130 -0
  277. package/dist/services/budget-awareness.d.ts.map +1 -0
  278. package/dist/services/budget-awareness.js +129 -0
  279. package/dist/services/budget-awareness.js.map +1 -0
  280. package/dist/services/cloud/lifecycle.d.ts.map +1 -1
  281. package/dist/services/cloud/lifecycle.js +3 -0
  282. package/dist/services/cloud/lifecycle.js.map +1 -1
  283. package/dist/services/cloud/task-wrapper.d.ts +18 -0
  284. package/dist/services/cloud/task-wrapper.d.ts.map +1 -1
  285. package/dist/services/cloud/task-wrapper.js +157 -0
  286. package/dist/services/cloud/task-wrapper.js.map +1 -1
  287. package/dist/services/cloud-sync.d.ts +35 -0
  288. package/dist/services/cloud-sync.d.ts.map +1 -0
  289. package/dist/services/cloud-sync.js +90 -0
  290. package/dist/services/cloud-sync.js.map +1 -0
  291. package/dist/services/context-admission.d.ts +82 -0
  292. package/dist/services/context-admission.d.ts.map +1 -0
  293. package/dist/services/context-admission.js +136 -0
  294. package/dist/services/context-admission.js.map +1 -0
  295. package/dist/services/event-bus.d.ts +27 -0
  296. package/dist/services/event-bus.d.ts.map +1 -0
  297. package/dist/services/event-bus.js +20 -0
  298. package/dist/services/event-bus.js.map +1 -0
  299. package/dist/services/file-chunker.d.ts +38 -0
  300. package/dist/services/file-chunker.d.ts.map +1 -0
  301. package/dist/services/file-chunker.js +63 -0
  302. package/dist/services/file-chunker.js.map +1 -0
  303. package/dist/services/file-transfer-relay.d.ts +55 -0
  304. package/dist/services/file-transfer-relay.d.ts.map +1 -0
  305. package/dist/services/file-transfer-relay.js +115 -0
  306. package/dist/services/file-transfer-relay.js.map +1 -0
  307. package/dist/services/github-app.d.ts.map +1 -1
  308. package/dist/services/github-app.js +12 -2
  309. package/dist/services/github-app.js.map +1 -1
  310. package/dist/services/http-transport.d.ts +25 -0
  311. package/dist/services/http-transport.d.ts.map +1 -0
  312. package/dist/services/http-transport.js +371 -0
  313. package/dist/services/http-transport.js.map +1 -0
  314. package/dist/services/hub-client.d.ts +69 -0
  315. package/dist/services/hub-client.d.ts.map +1 -0
  316. package/dist/services/hub-client.js +217 -0
  317. package/dist/services/hub-client.js.map +1 -0
  318. package/dist/services/jwt.d.ts +17 -0
  319. package/dist/services/jwt.d.ts.map +1 -0
  320. package/dist/services/jwt.js +70 -0
  321. package/dist/services/jwt.js.map +1 -0
  322. package/dist/services/knowledge/audn.d.ts +37 -0
  323. package/dist/services/knowledge/audn.d.ts.map +1 -0
  324. package/dist/services/knowledge/audn.js +219 -0
  325. package/dist/services/knowledge/audn.js.map +1 -0
  326. package/dist/services/knowledge/file-hash.d.ts +11 -0
  327. package/dist/services/knowledge/file-hash.d.ts.map +1 -0
  328. package/dist/services/knowledge/file-hash.js +123 -0
  329. package/dist/services/knowledge/file-hash.js.map +1 -0
  330. package/dist/services/knowledge/http-provider.d.ts +46 -0
  331. package/dist/services/knowledge/http-provider.d.ts.map +1 -0
  332. package/dist/services/knowledge/http-provider.js +254 -0
  333. package/dist/services/knowledge/http-provider.js.map +1 -0
  334. package/dist/services/knowledge/kb-providers.d.ts +15 -0
  335. package/dist/services/knowledge/kb-providers.d.ts.map +1 -0
  336. package/dist/services/knowledge/kb-providers.js +92 -0
  337. package/dist/services/knowledge/kb-providers.js.map +1 -0
  338. package/dist/services/knowledge/kb-scope-input.d.ts +5 -0
  339. package/dist/services/knowledge/kb-scope-input.d.ts.map +1 -0
  340. package/dist/services/knowledge/kb-scope-input.js +11 -0
  341. package/dist/services/knowledge/kb-scope-input.js.map +1 -0
  342. package/dist/services/knowledge/kb-service.d.ts +3 -0
  343. package/dist/services/knowledge/kb-service.d.ts.map +1 -0
  344. package/dist/services/knowledge/kb-service.js +2 -0
  345. package/dist/services/knowledge/kb-service.js.map +1 -0
  346. package/dist/services/knowledge/path-validation.d.ts +2 -0
  347. package/dist/services/knowledge/path-validation.d.ts.map +1 -0
  348. package/dist/services/knowledge/path-validation.js +13 -0
  349. package/dist/services/knowledge/path-validation.js.map +1 -0
  350. package/dist/services/knowledge/pre-init.d.ts +14 -0
  351. package/dist/services/knowledge/pre-init.d.ts.map +1 -0
  352. package/dist/services/knowledge/pre-init.js +147 -0
  353. package/dist/services/knowledge/pre-init.js.map +1 -0
  354. package/dist/services/knowledge/project-slug.d.ts +2 -0
  355. package/dist/services/knowledge/project-slug.d.ts.map +1 -0
  356. package/dist/services/knowledge/project-slug.js +49 -0
  357. package/dist/services/knowledge/project-slug.js.map +1 -0
  358. package/dist/services/knowledge/sqlite-provider.d.ts +147 -0
  359. package/dist/services/knowledge/sqlite-provider.d.ts.map +1 -0
  360. package/dist/services/knowledge/sqlite-provider.js +1646 -0
  361. package/dist/services/knowledge/sqlite-provider.js.map +1 -0
  362. package/dist/services/knowledge/types.d.ts +163 -0
  363. package/dist/services/knowledge/types.d.ts.map +1 -0
  364. package/dist/services/knowledge/types.js +9 -0
  365. package/dist/services/knowledge/types.js.map +1 -0
  366. package/dist/services/known-sessions.d.ts +8 -0
  367. package/dist/services/known-sessions.d.ts.map +1 -0
  368. package/dist/services/known-sessions.js +40 -0
  369. package/dist/services/known-sessions.js.map +1 -0
  370. package/dist/services/member-home.d.ts +89 -0
  371. package/dist/services/member-home.d.ts.map +1 -0
  372. package/dist/services/member-home.js +256 -0
  373. package/dist/services/member-home.js.map +1 -0
  374. package/dist/services/member-remote-url.d.ts +34 -0
  375. package/dist/services/member-remote-url.d.ts.map +1 -0
  376. package/dist/services/member-remote-url.js +39 -0
  377. package/dist/services/member-remote-url.js.map +1 -0
  378. package/dist/services/model-pricing.d.ts +36 -0
  379. package/dist/services/model-pricing.d.ts.map +1 -0
  380. package/dist/services/model-pricing.js +108 -0
  381. package/dist/services/model-pricing.js.map +1 -0
  382. package/dist/services/orphan-recovery.d.ts +59 -0
  383. package/dist/services/orphan-recovery.d.ts.map +1 -0
  384. package/dist/services/orphan-recovery.js +122 -0
  385. package/dist/services/orphan-recovery.js.map +1 -0
  386. package/dist/services/pending-responses.d.ts +23 -0
  387. package/dist/services/pending-responses.d.ts.map +1 -0
  388. package/dist/services/pending-responses.js +52 -0
  389. package/dist/services/pending-responses.js.map +1 -0
  390. package/dist/services/preflight-check.d.ts +56 -0
  391. package/dist/services/preflight-check.d.ts.map +1 -0
  392. package/dist/services/preflight-check.js +277 -0
  393. package/dist/services/preflight-check.js.map +1 -0
  394. package/dist/services/registry.d.ts +4 -1
  395. package/dist/services/registry.d.ts.map +1 -1
  396. package/dist/services/registry.js +3 -0
  397. package/dist/services/registry.js.map +1 -1
  398. package/dist/services/relay-context.d.ts +23 -0
  399. package/dist/services/relay-context.d.ts.map +1 -0
  400. package/dist/services/relay-context.js +8 -0
  401. package/dist/services/relay-context.js.map +1 -0
  402. package/dist/services/relay-executor.d.ts +68 -0
  403. package/dist/services/relay-executor.d.ts.map +1 -0
  404. package/dist/services/relay-executor.js +70 -0
  405. package/dist/services/relay-executor.js.map +1 -0
  406. package/dist/services/relay-request.d.ts +65 -0
  407. package/dist/services/relay-request.d.ts.map +1 -0
  408. package/dist/services/relay-request.js +129 -0
  409. package/dist/services/relay-request.js.map +1 -0
  410. package/dist/services/relay-strategy.d.ts +19 -0
  411. package/dist/services/relay-strategy.d.ts.map +1 -0
  412. package/dist/services/relay-strategy.js +111 -0
  413. package/dist/services/relay-strategy.js.map +1 -0
  414. package/dist/services/service-manager/index.d.ts +5 -0
  415. package/dist/services/service-manager/index.d.ts.map +1 -0
  416. package/dist/services/service-manager/index.js +66 -0
  417. package/dist/services/service-manager/index.js.map +1 -0
  418. package/dist/services/service-manager/linux.d.ts +10 -0
  419. package/dist/services/service-manager/linux.d.ts.map +1 -0
  420. package/dist/services/service-manager/linux.js +97 -0
  421. package/dist/services/service-manager/linux.js.map +1 -0
  422. package/dist/services/service-manager/macos.d.ts +10 -0
  423. package/dist/services/service-manager/macos.d.ts.map +1 -0
  424. package/dist/services/service-manager/macos.js +94 -0
  425. package/dist/services/service-manager/macos.js.map +1 -0
  426. package/dist/services/service-manager/types.d.ts +18 -0
  427. package/dist/services/service-manager/types.d.ts.map +1 -0
  428. package/dist/services/service-manager/types.js +5 -0
  429. package/dist/services/service-manager/types.js.map +1 -0
  430. package/dist/services/service-manager/windows.d.ts +10 -0
  431. package/dist/services/service-manager/windows.d.ts.map +1 -0
  432. package/dist/services/service-manager/windows.js +73 -0
  433. package/dist/services/service-manager/windows.js.map +1 -0
  434. package/dist/services/session-registry.d.ts +70 -0
  435. package/dist/services/session-registry.d.ts.map +1 -0
  436. package/dist/services/session-registry.js +91 -0
  437. package/dist/services/session-registry.js.map +1 -0
  438. package/dist/services/singleton.d.ts +15 -0
  439. package/dist/services/singleton.d.ts.map +1 -0
  440. package/dist/services/singleton.js +98 -0
  441. package/dist/services/singleton.js.map +1 -0
  442. package/dist/services/sprint-coordination.d.ts +168 -0
  443. package/dist/services/sprint-coordination.d.ts.map +1 -0
  444. package/dist/services/sprint-coordination.js +564 -0
  445. package/dist/services/sprint-coordination.js.map +1 -0
  446. package/dist/services/ssh.d.ts.map +1 -1
  447. package/dist/services/ssh.js +70 -3
  448. package/dist/services/ssh.js.map +1 -1
  449. package/dist/services/stall/log-path-resolver.d.ts +11 -8
  450. package/dist/services/stall/log-path-resolver.d.ts.map +1 -1
  451. package/dist/services/stall/log-path-resolver.js +17 -33
  452. package/dist/services/stall/log-path-resolver.js.map +1 -1
  453. package/dist/services/stall/stall-detector.d.ts +32 -0
  454. package/dist/services/stall/stall-detector.d.ts.map +1 -1
  455. package/dist/services/stall/stall-detector.js +187 -12
  456. package/dist/services/stall/stall-detector.js.map +1 -1
  457. package/dist/services/stall/stall-poller.d.ts +50 -0
  458. package/dist/services/stall/stall-poller.d.ts.map +1 -1
  459. package/dist/services/stall/stall-poller.js +268 -18
  460. package/dist/services/stall/stall-poller.js.map +1 -1
  461. package/dist/services/strategy.d.ts.map +1 -1
  462. package/dist/services/strategy.js +57 -7
  463. package/dist/services/strategy.js.map +1 -1
  464. package/dist/services/substitution-engine.d.ts +20 -0
  465. package/dist/services/substitution-engine.d.ts.map +1 -0
  466. package/dist/services/substitution-engine.js +92 -0
  467. package/dist/services/substitution-engine.js.map +1 -0
  468. package/dist/services/task-cleanup.d.ts.map +1 -1
  469. package/dist/services/task-cleanup.js +1 -9
  470. package/dist/services/task-cleanup.js.map +1 -1
  471. package/dist/services/token-issuer.d.ts +47 -0
  472. package/dist/services/token-issuer.d.ts.map +1 -0
  473. package/dist/services/token-issuer.js +63 -0
  474. package/dist/services/token-issuer.js.map +1 -0
  475. package/dist/services/tool-registry.d.ts +3 -0
  476. package/dist/services/tool-registry.d.ts.map +1 -0
  477. package/dist/services/tool-registry.js +225 -0
  478. package/dist/services/tool-registry.js.map +1 -0
  479. package/dist/services/user-config.d.ts +14 -0
  480. package/dist/services/user-config.d.ts.map +1 -1
  481. package/dist/services/user-config.js +55 -0
  482. package/dist/services/user-config.js.map +1 -1
  483. package/dist/services/vcs/github.d.ts.map +1 -1
  484. package/dist/services/vcs/github.js +32 -1
  485. package/dist/services/vcs/github.js.map +1 -1
  486. package/dist/services/vcs/types.d.ts +44 -0
  487. package/dist/services/vcs/types.d.ts.map +1 -1
  488. package/dist/services/version-check.d.ts +22 -0
  489. package/dist/services/version-check.d.ts.map +1 -0
  490. package/dist/services/version-check.js +103 -0
  491. package/dist/services/version-check.js.map +1 -0
  492. package/dist/skills/fleet-sprint-cli/SKILL.md +114 -0
  493. package/dist/skills/pm/beads.md +6 -0
  494. package/dist/skills/pm/cost.md +3 -0
  495. package/dist/skills/pm/doer-reviewer-loop.md +3 -0
  496. package/dist/skills/pm/fleet-addendum.md +6 -0
  497. package/dist/skills/pm/index.md +56 -0
  498. package/dist/skills/pm/kb-reconcile.md +132 -0
  499. package/dist/skills/pm/kb-review.md +109 -0
  500. package/dist/tools/check-status.d.ts +47 -0
  501. package/dist/tools/check-status.d.ts.map +1 -1
  502. package/dist/tools/check-status.js +250 -2
  503. package/dist/tools/check-status.js.map +1 -1
  504. package/dist/tools/child-id-allocator.d.ts +45 -0
  505. package/dist/tools/child-id-allocator.d.ts.map +1 -0
  506. package/dist/tools/child-id-allocator.js +62 -0
  507. package/dist/tools/child-id-allocator.js.map +1 -0
  508. package/dist/tools/cloud-control.d.ts +2 -2
  509. package/dist/tools/code-intelligence-codebase-memory.d.ts +11 -0
  510. package/dist/tools/code-intelligence-codebase-memory.d.ts.map +1 -0
  511. package/dist/tools/code-intelligence-codebase-memory.js +270 -0
  512. package/dist/tools/code-intelligence-codebase-memory.js.map +1 -0
  513. package/dist/tools/code-intelligence-freshness.d.ts +2 -0
  514. package/dist/tools/code-intelligence-freshness.d.ts.map +1 -0
  515. package/dist/tools/code-intelligence-freshness.js +26 -0
  516. package/dist/tools/code-intelligence-freshness.js.map +1 -0
  517. package/dist/tools/code-intelligence-gitnexus.d.ts +14 -0
  518. package/dist/tools/code-intelligence-gitnexus.d.ts.map +1 -0
  519. package/dist/tools/code-intelligence-gitnexus.js +475 -0
  520. package/dist/tools/code-intelligence-gitnexus.js.map +1 -0
  521. package/dist/tools/code-intelligence-kb-enrich.d.ts +2 -0
  522. package/dist/tools/code-intelligence-kb-enrich.d.ts.map +1 -0
  523. package/dist/tools/code-intelligence-kb-enrich.js +65 -0
  524. package/dist/tools/code-intelligence-kb-enrich.js.map +1 -0
  525. package/dist/tools/code-intelligence-reindex.d.ts +7 -0
  526. package/dist/tools/code-intelligence-reindex.d.ts.map +1 -0
  527. package/dist/tools/code-intelligence-reindex.js +106 -0
  528. package/dist/tools/code-intelligence-reindex.js.map +1 -0
  529. package/dist/tools/code-intelligence-telemetry.d.ts +5 -0
  530. package/dist/tools/code-intelligence-telemetry.d.ts.map +1 -0
  531. package/dist/tools/code-intelligence-telemetry.js +52 -0
  532. package/dist/tools/code-intelligence-telemetry.js.map +1 -0
  533. package/dist/tools/code-intelligence-tests.d.ts +2 -0
  534. package/dist/tools/code-intelligence-tests.d.ts.map +1 -0
  535. package/dist/tools/code-intelligence-tests.js +24 -0
  536. package/dist/tools/code-intelligence-tests.js.map +1 -0
  537. package/dist/tools/code-intelligence.d.ts +114 -0
  538. package/dist/tools/code-intelligence.d.ts.map +1 -0
  539. package/dist/tools/code-intelligence.js +124 -0
  540. package/dist/tools/code-intelligence.js.map +1 -0
  541. package/dist/tools/compose-permissions.d.ts +38 -4
  542. package/dist/tools/compose-permissions.d.ts.map +1 -1
  543. package/dist/tools/compose-permissions.js +295 -33
  544. package/dist/tools/compose-permissions.js.map +1 -1
  545. package/dist/tools/dolt-push-mutex.d.ts +44 -0
  546. package/dist/tools/dolt-push-mutex.d.ts.map +1 -0
  547. package/dist/tools/dolt-push-mutex.js +83 -0
  548. package/dist/tools/dolt-push-mutex.js.map +1 -0
  549. package/dist/tools/execute-command.d.ts +13 -1
  550. package/dist/tools/execute-command.d.ts.map +1 -1
  551. package/dist/tools/execute-command.js +108 -21
  552. package/dist/tools/execute-command.js.map +1 -1
  553. package/dist/tools/execute-prompt.d.ts +84 -12
  554. package/dist/tools/execute-prompt.d.ts.map +1 -1
  555. package/dist/tools/execute-prompt.js +1191 -88
  556. package/dist/tools/execute-prompt.js.map +1 -1
  557. package/dist/tools/get-member-model-pricing.d.ts +21 -0
  558. package/dist/tools/get-member-model-pricing.d.ts.map +1 -0
  559. package/dist/tools/get-member-model-pricing.js +29 -0
  560. package/dist/tools/get-member-model-pricing.js.map +1 -0
  561. package/dist/tools/kb-capture.d.ts +53 -0
  562. package/dist/tools/kb-capture.d.ts.map +1 -0
  563. package/dist/tools/kb-capture.js +130 -0
  564. package/dist/tools/kb-capture.js.map +1 -0
  565. package/dist/tools/kb-context.d.ts +17 -0
  566. package/dist/tools/kb-context.d.ts.map +1 -0
  567. package/dist/tools/kb-context.js +29 -0
  568. package/dist/tools/kb-context.js.map +1 -0
  569. package/dist/tools/kb-export.d.ts +19 -0
  570. package/dist/tools/kb-export.d.ts.map +1 -0
  571. package/dist/tools/kb-export.js +344 -0
  572. package/dist/tools/kb-export.js.map +1 -0
  573. package/dist/tools/kb-feedback.d.ts +23 -0
  574. package/dist/tools/kb-feedback.d.ts.map +1 -0
  575. package/dist/tools/kb-feedback.js +43 -0
  576. package/dist/tools/kb-feedback.js.map +1 -0
  577. package/dist/tools/kb-freshness-sweep.d.ts +14 -0
  578. package/dist/tools/kb-freshness-sweep.d.ts.map +1 -0
  579. package/dist/tools/kb-freshness-sweep.js +29 -0
  580. package/dist/tools/kb-freshness-sweep.js.map +1 -0
  581. package/dist/tools/kb-harvest.d.ts +20 -0
  582. package/dist/tools/kb-harvest.d.ts.map +1 -0
  583. package/dist/tools/kb-harvest.js +143 -0
  584. package/dist/tools/kb-harvest.js.map +1 -0
  585. package/dist/tools/kb-import.d.ts +44 -0
  586. package/dist/tools/kb-import.d.ts.map +1 -0
  587. package/dist/tools/kb-import.js +239 -0
  588. package/dist/tools/kb-import.js.map +1 -0
  589. package/dist/tools/kb-invalidate.d.ts +19 -0
  590. package/dist/tools/kb-invalidate.d.ts.map +1 -0
  591. package/dist/tools/kb-invalidate.js +34 -0
  592. package/dist/tools/kb-invalidate.js.map +1 -0
  593. package/dist/tools/kb-list.d.ts +32 -0
  594. package/dist/tools/kb-list.d.ts.map +1 -0
  595. package/dist/tools/kb-list.js +43 -0
  596. package/dist/tools/kb-list.js.map +1 -0
  597. package/dist/tools/kb-promote.d.ts +20 -0
  598. package/dist/tools/kb-promote.d.ts.map +1 -0
  599. package/dist/tools/kb-promote.js +20 -0
  600. package/dist/tools/kb-promote.js.map +1 -0
  601. package/dist/tools/kb-query.d.ts +35 -0
  602. package/dist/tools/kb-query.d.ts.map +1 -0
  603. package/dist/tools/kb-query.js +111 -0
  604. package/dist/tools/kb-query.js.map +1 -0
  605. package/dist/tools/kb-reconcile-prefilter.d.ts +14 -0
  606. package/dist/tools/kb-reconcile-prefilter.d.ts.map +1 -0
  607. package/dist/tools/kb-reconcile-prefilter.js +26 -0
  608. package/dist/tools/kb-reconcile-prefilter.js.map +1 -0
  609. package/dist/tools/kb-resolve-contradiction.d.ts +23 -0
  610. package/dist/tools/kb-resolve-contradiction.d.ts.map +1 -0
  611. package/dist/tools/kb-resolve-contradiction.js +37 -0
  612. package/dist/tools/kb-resolve-contradiction.js.map +1 -0
  613. package/dist/tools/kb-session-prime.d.ts +26 -0
  614. package/dist/tools/kb-session-prime.d.ts.map +1 -0
  615. package/dist/tools/kb-session-prime.js +392 -0
  616. package/dist/tools/kb-session-prime.js.map +1 -0
  617. package/dist/tools/kb-setup.d.ts +20 -0
  618. package/dist/tools/kb-setup.d.ts.map +1 -0
  619. package/dist/tools/kb-setup.js +49 -0
  620. package/dist/tools/kb-setup.js.map +1 -0
  621. package/dist/tools/kb-stats.d.ts +20 -0
  622. package/dist/tools/kb-stats.d.ts.map +1 -0
  623. package/dist/tools/kb-stats.js +115 -0
  624. package/dist/tools/kb-stats.js.map +1 -0
  625. package/dist/tools/list-members.d.ts.map +1 -1
  626. package/dist/tools/list-members.js +39 -7
  627. package/dist/tools/list-members.js.map +1 -1
  628. package/dist/tools/member-detail.d.ts +1 -1
  629. package/dist/tools/member-detail.d.ts.map +1 -1
  630. package/dist/tools/member-detail.js +16 -2
  631. package/dist/tools/member-detail.js.map +1 -1
  632. package/dist/tools/member-reservation.d.ts +29 -0
  633. package/dist/tools/member-reservation.d.ts.map +1 -0
  634. package/dist/tools/member-reservation.js +71 -0
  635. package/dist/tools/member-reservation.js.map +1 -0
  636. package/dist/tools/monitor-task.d.ts.map +1 -1
  637. package/dist/tools/monitor-task.js +21 -3
  638. package/dist/tools/monitor-task.js.map +1 -1
  639. package/dist/tools/provision-auth.d.ts.map +1 -1
  640. package/dist/tools/provision-auth.js +10 -3
  641. package/dist/tools/provision-auth.js.map +1 -1
  642. package/dist/tools/provision-vcs-auth.d.ts +7 -7
  643. package/dist/tools/provision-vcs-auth.js +1 -1
  644. package/dist/tools/provision-vcs-auth.js.map +1 -1
  645. package/dist/tools/register-member.d.ts +20 -5
  646. package/dist/tools/register-member.d.ts.map +1 -1
  647. package/dist/tools/register-member.js +174 -6
  648. package/dist/tools/register-member.js.map +1 -1
  649. package/dist/tools/remove-member.d.ts +1 -1
  650. package/dist/tools/remove-member.d.ts.map +1 -1
  651. package/dist/tools/remove-member.js +17 -3
  652. package/dist/tools/remove-member.js.map +1 -1
  653. package/dist/tools/report-status.d.ts +33 -0
  654. package/dist/tools/report-status.d.ts.map +1 -0
  655. package/dist/tools/report-status.js +45 -0
  656. package/dist/tools/report-status.js.map +1 -0
  657. package/dist/tools/respond-to-message.d.ts +21 -0
  658. package/dist/tools/respond-to-message.d.ts.map +1 -0
  659. package/dist/tools/respond-to-message.js +23 -0
  660. package/dist/tools/respond-to-message.js.map +1 -0
  661. package/dist/tools/send-email.d.ts +69 -0
  662. package/dist/tools/send-email.d.ts.map +1 -0
  663. package/dist/tools/send-email.js +177 -0
  664. package/dist/tools/send-email.js.map +1 -0
  665. package/dist/tools/send-files.d.ts +3 -0
  666. package/dist/tools/send-files.d.ts.map +1 -1
  667. package/dist/tools/send-files.js +88 -8
  668. package/dist/tools/send-files.js.map +1 -1
  669. package/dist/tools/send-message.d.ts +27 -0
  670. package/dist/tools/send-message.d.ts.map +1 -0
  671. package/dist/tools/send-message.js +46 -0
  672. package/dist/tools/send-message.js.map +1 -0
  673. package/dist/tools/setup-ssh-key.d.ts.map +1 -1
  674. package/dist/tools/setup-ssh-key.js +2 -0
  675. package/dist/tools/setup-ssh-key.js.map +1 -1
  676. package/dist/tools/shutdown-server.d.ts +2 -0
  677. package/dist/tools/shutdown-server.d.ts.map +1 -1
  678. package/dist/tools/shutdown-server.js +19 -0
  679. package/dist/tools/shutdown-server.js.map +1 -1
  680. package/dist/tools/update-member.d.ts +11 -8
  681. package/dist/tools/update-member.d.ts.map +1 -1
  682. package/dist/tools/update-member.js +36 -2
  683. package/dist/tools/update-member.js.map +1 -1
  684. package/dist/types.d.ts +16 -3
  685. package/dist/types.d.ts.map +1 -1
  686. package/dist/utils/agent-helpers.d.ts +2 -1
  687. package/dist/utils/agent-helpers.d.ts.map +1 -1
  688. package/dist/utils/agent-helpers.js +7 -2
  689. package/dist/utils/agent-helpers.js.map +1 -1
  690. package/dist/utils/pid-helpers.d.ts +15 -0
  691. package/dist/utils/pid-helpers.d.ts.map +1 -1
  692. package/dist/utils/pid-helpers.js +23 -0
  693. package/dist/utils/pid-helpers.js.map +1 -1
  694. package/dist/utils/process-utils.d.ts +3 -0
  695. package/dist/utils/process-utils.d.ts.map +1 -0
  696. package/dist/utils/process-utils.js +42 -0
  697. package/dist/utils/process-utils.js.map +1 -0
  698. package/dist/utils/prompt-errors.d.ts +2 -1
  699. package/dist/utils/prompt-errors.d.ts.map +1 -1
  700. package/dist/utils/prompt-errors.js +13 -3
  701. package/dist/utils/prompt-errors.js.map +1 -1
  702. package/dist/utils/session-caller.d.ts +28 -0
  703. package/dist/utils/session-caller.d.ts.map +1 -0
  704. package/dist/utils/session-caller.js +24 -0
  705. package/dist/utils/session-caller.js.map +1 -0
  706. package/dist/utils/work-folder-validation.d.ts +39 -0
  707. package/dist/utils/work-folder-validation.d.ts.map +1 -0
  708. package/dist/utils/work-folder-validation.js +60 -0
  709. package/dist/utils/work-folder-validation.js.map +1 -0
  710. package/dist/utils/workspace-trust.d.ts +24 -0
  711. package/dist/utils/workspace-trust.d.ts.map +1 -0
  712. package/dist/utils/workspace-trust.js +35 -0
  713. package/dist/utils/workspace-trust.js.map +1 -0
  714. package/dist/workflows/auto-sprint.js +994 -91
  715. package/package.json +40 -9
  716. package/packages/apra-fleet-client/package.json +26 -0
  717. package/packages/apra-fleet-client/src/client/api.mjs +510 -0
  718. package/packages/apra-fleet-client/src/client/client.mjs +146 -0
  719. package/packages/apra-fleet-client/src/client/errors.mjs +71 -0
  720. package/packages/apra-fleet-client/src/client/factory.mjs +65 -0
  721. package/packages/apra-fleet-client/src/client/server-resolution.mjs +265 -0
  722. package/packages/apra-fleet-client/src/client/transport.mjs +327 -0
  723. package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +303 -0
  724. package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +101 -0
  725. package/packages/apra-fleet-se/apra-pm/agents/deployer.md +151 -0
  726. package/packages/apra-fleet-se/apra-pm/agents/doer.md +259 -0
  727. package/packages/apra-fleet-se/apra-pm/agents/harvester.md +188 -0
  728. package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +332 -0
  729. package/packages/apra-fleet-se/apra-pm/agents/kb-reconciler.md +216 -0
  730. package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +201 -0
  731. package/packages/apra-fleet-se/apra-pm/agents/planner.md +322 -0
  732. package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +234 -0
  733. package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +275 -0
  734. package/packages/apra-fleet-se/apra-pm/agents/schemas/backlog-groomer-input.json +35 -0
  735. package/packages/apra-fleet-se/apra-pm/agents/schemas/backlog-groomer-output.json +164 -0
  736. package/packages/apra-fleet-se/apra-pm/agents/schemas/ci-watcher-input.json +26 -0
  737. package/packages/apra-fleet-se/apra-pm/agents/schemas/ci-watcher-output.json +18 -0
  738. package/packages/apra-fleet-se/apra-pm/agents/schemas/deployer-input.json +19 -0
  739. package/packages/apra-fleet-se/apra-pm/agents/schemas/deployer-output.json +17 -0
  740. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-input.json +25 -0
  741. package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +82 -0
  742. package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-input.json +31 -0
  743. package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-output.json +75 -0
  744. package/packages/apra-fleet-se/apra-pm/agents/schemas/integ-test-runner-input.json +20 -0
  745. package/packages/apra-fleet-se/apra-pm/agents/schemas/integ-test-runner-output.json +61 -0
  746. package/packages/apra-fleet-se/apra-pm/agents/schemas/kb-reconciler-output.json +87 -0
  747. package/packages/apra-fleet-se/apra-pm/agents/schemas/plan-reviewer-input.json +15 -0
  748. package/packages/apra-fleet-se/apra-pm/agents/schemas/plan-reviewer-output.json +30 -0
  749. package/packages/apra-fleet-se/apra-pm/agents/schemas/planner-output.json +65 -0
  750. package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-input.json +15 -0
  751. package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-output.json +50 -0
  752. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-input.json +25 -0
  753. package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +135 -0
  754. package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +402 -0
  755. package/packages/apra-fleet-se/apra-pm/skills/pm/beads.md +148 -0
  756. package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +157 -0
  757. package/packages/apra-fleet-se/apra-pm/skills/pm/doer-reviewer-loop.md +300 -0
  758. package/packages/apra-fleet-se/apra-pm/skills/pm/fleet-addendum.md +127 -0
  759. package/packages/apra-fleet-se/apra-pm/skills/pm/index.md +56 -0
  760. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-reconcile.md +132 -0
  761. package/packages/apra-fleet-se/apra-pm/skills/pm/kb-review.md +109 -0
  762. package/packages/apra-fleet-se/apra-pm/skills/pm/simple-sprint.md +65 -0
  763. package/packages/apra-fleet-se/apra-pm/skills/pm/sprint.md +327 -0
  764. package/packages/apra-fleet-se/apra-pm/skills/pm/worktrees.md +92 -0
  765. package/packages/apra-fleet-se/apra-pm/version.json +3 -0
  766. package/packages/apra-fleet-se/bin/cli.mjs +864 -0
  767. package/packages/apra-fleet-se/bin/serve.mjs +395 -0
  768. package/packages/apra-fleet-se/fleet-sprint/conflict-ladder.mjs +178 -0
  769. package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +940 -0
  770. package/packages/apra-fleet-se/fleet-sprint/dispatch-safety-guard.mjs +177 -0
  771. package/packages/apra-fleet-se/fleet-sprint/docs/README.md +191 -0
  772. package/packages/apra-fleet-se/fleet-sprint/docs/coach-role-design.md +23 -0
  773. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-manual-recovery-verified.md +256 -0
  774. package/packages/apra-fleet-se/fleet-sprint/docs/dolt-sync-redesign.md +1482 -0
  775. package/packages/apra-fleet-se/fleet-sprint/docs/escalate-to-llm-design.md +908 -0
  776. package/packages/apra-fleet-se/fleet-sprint/docs/fleet-sprint-diagram.md +94 -0
  777. package/packages/apra-fleet-se/fleet-sprint/docs/shared-orchestrator-reservation-design.md +399 -0
  778. package/packages/apra-fleet-se/fleet-sprint/docs/stabilization-log.md +1125 -0
  779. package/packages/apra-fleet-se/fleet-sprint/dolt-literal-guard.mjs +72 -0
  780. package/packages/apra-fleet-se/fleet-sprint/dolt-settle.mjs +972 -0
  781. package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +1310 -0
  782. package/packages/apra-fleet-se/fleet-sprint/errors.mjs +616 -0
  783. package/packages/apra-fleet-se/fleet-sprint/full-db-fetch-guard.mjs +118 -0
  784. package/packages/apra-fleet-se/fleet-sprint/runner.js +10747 -0
  785. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +114 -0
  786. package/packages/apra-fleet-se/fleet-sprint/skills/fleet-supervisor/SKILL.md +350 -0
  787. package/packages/apra-fleet-se/fleet-sprint/sprint-lock.mjs +140 -0
  788. package/packages/apra-fleet-se/fleet-sprint/sprint-progress.mjs +101 -0
  789. package/packages/apra-fleet-se/fleet-sprint/vcs-module.mjs +435 -0
  790. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/azure-devops.mjs +68 -0
  791. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +53 -0
  792. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/dolt.mjs +146 -0
  793. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/generic-git.mjs +176 -0
  794. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +235 -0
  795. package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +218 -0
  796. package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +942 -0
  797. package/packages/apra-fleet-se/package.json +29 -0
  798. package/packages/apra-fleet-se/workflow.json +1 -0
  799. package/packages/apra-fleet-workflow/package.json +30 -0
  800. package/packages/apra-fleet-workflow/src/viewer/command-output-cap.mjs +112 -0
  801. package/packages/apra-fleet-workflow/src/viewer/debounced-writer.mjs +153 -0
  802. package/packages/apra-fleet-workflow/src/viewer/html-utils.mjs +31 -0
  803. package/packages/apra-fleet-workflow/src/viewer/index.mjs +1439 -0
  804. package/packages/apra-fleet-workflow/src/viewer/lean-state.mjs +237 -0
  805. package/packages/apra-fleet-workflow/src/viewer/run-state-paths.mjs +130 -0
  806. package/packages/apra-fleet-workflow/src/viewer/run-title.mjs +60 -0
  807. package/packages/apra-fleet-workflow/src/viewer/sprint-state-paths.mjs +29 -0
  808. package/packages/apra-fleet-workflow/src/workflow/engine.mjs +200 -0
  809. package/packages/apra-fleet-workflow/src/workflow/errors.mjs +146 -0
  810. package/packages/apra-fleet-workflow/src/workflow/index.mjs +1727 -0
  811. package/packages/apra-fleet-workflow/src/workflow/journal.mjs +291 -0
  812. package/packages/apra-fleet-workflow/src/workflow/pricing.mjs +99 -0
  813. package/packages/apra-fleet-workflow/src/workflow/vetting.mjs +111 -0
  814. package/scripts/agy-transcript-reader.js +1 -0
  815. package/scripts/fleet-statusline.sh +17 -13
  816. package/skills/fleet/SKILL.md +37 -2
  817. package/skills/fleet/beads.md +14 -7
  818. package/skills/fleet/knowledge-agent.md +66 -0
  819. package/skills/fleet/permissions.md +76 -2
  820. package/skills/fleet/profiles/base-dev.json +11 -1
  821. package/skills/fleet/profiles/base-reviewer.json +9 -1
  822. package/skills/fleet/profiles/node.json +2 -2
  823. package/skills/fleet/profiles/tag-kb-reconciler.json +20 -0
  824. package/version.json +1 -1
  825. package/scripts/agy-settings-merge.js +0 -27
  826. /package/{dist → packages/apra-fleet-se/apra-pm}/agents/_shared/GRAPH-SEMANTICS.md +0 -0
@@ -0,0 +1,1439 @@
1
+ import http from 'http';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { randomUUID } from 'crypto';
5
+ import { escapeHtml } from './html-utils.mjs';
6
+ import { DebouncedStateWriter, DEFAULT_DEBOUNCE_MS, writeJsonFileAtomic } from './debounced-writer.mjs';
7
+ import { getRunningRunStatePath, getTerminalRunStatePath } from './run-state-paths.mjs';
8
+ import { buildListStatePayload, resolveStringRefs } from './lean-state.mjs';
9
+ import { capCommandActivityMeta, getFullOutput } from './command-output-cap.mjs';
10
+ import { buildRunTitle } from './run-title.mjs';
11
+
12
+ // apra-fleet-eft.6.5: the SAME template serves both the live view and the
13
+ // process-free History view -- `opts.history` (true) feeds a FROZEN state
14
+ // object directly into the page instead of the live view's
15
+ // fetch('/state') + EventSource('/events') polling loop, and hides the Save
16
+ // / Stop controls (there is no live workflow left to save/stop, and nothing
17
+ // to stream: a finished run's child process, and therefore those
18
+ // endpoints, no longer exists). `opts.state` is embedded as a JSON literal;
19
+ // any literal `</script>`-like sequence inside it is escaped so it can never
20
+ // terminate the embedding <script> tag early.
21
+ const HTML_TEMPLATE = (dashboardExtensions, opts = {}) => {
22
+ const isHistory = !!opts.history;
23
+ const frozenStateLiteral = isHistory
24
+ ? JSON.stringify(opts.state ?? null).replace(/</g, '\\u003c')
25
+ : 'null';
26
+ return `<!DOCTYPE html>
27
+ <html lang="en">
28
+ <head>
29
+ <meta charset="UTF-8">
30
+ <meta name="viewport" content="width=device-width,initial-scale=1">
31
+ <title>Workflow Dashboard</title>
32
+ <style>
33
+ :root {
34
+ --bg: #09090b; --bg-glass: rgba(24, 24, 27, 0.6); --border: rgba(255, 255, 255, 0.1);
35
+ --text: #e4e4e7; --text-muted: #a1a1aa; --accent: #3b82f6; --accent-glow: rgba(59, 130, 246, 0.2);
36
+ --success: #10b981; --warning: #f59e0b; --danger: #ef4444;
37
+ }
38
+ * { box-sizing: border-box; margin: 0; padding: 0; }
39
+ /* apra-fleet-eft.43 (measured live, Chrome, 799px window): without an
40
+ explicit height on <html>, and with only overflow: hidden on <body>,
41
+ the whole page grew to fit every activity (documentElement.scrollHeight
42
+ ended up EQUAL to clientHeight -- the window itself could never scroll,
43
+ body's overflow: hidden made sure of that -- while #stream-list's own
44
+ scrollHeight/clientHeight were also equal, because ITS height was
45
+ unbounded too: nothing above it in the ancestor chain actually pinned
46
+ it to the viewport). html,body height: 100% plus body's own 100dvh
47
+ (falls back to 100vh in browsers that predate dvh) is what makes the
48
+ flex-column layout below a fixed-size box in the first place -- only
49
+ then does #stream-list's flex: 1; min-height: 0; overflow-y: auto
50
+ actually have a bounded parent to scroll inside of. */
51
+ html, body { height: 100%; }
52
+ body { background: var(--bg); color: var(--text); font-family: sans-serif; height: 100vh; height: 100dvh; overflow: hidden; display: flex; flex-direction: column; }
53
+ .header { flex-shrink: 0; display: flex; justify-content: space-between; align-items: center; padding: 12px 24px; background: var(--bg-glass); border-bottom: 1px solid var(--border); }
54
+ .header h1 { font-size: 16px; font-weight: 600; margin: 0; }
55
+ .header-title { display: flex; flex-direction: column; gap: 4px; }
56
+ .run-title { font-size: 12px; color: var(--text-muted); background: var(--bg-glass); padding: 2px 8px; border-radius: 4px; width: fit-content; }
57
+ .header-actions { display: flex; gap: 12px; align-items: center; }
58
+
59
+ .stats-banner { display: flex; gap: 16px; font-size: 12px; color: var(--text-muted); background: rgba(0,0,0,0.3); padding: 4px 12px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.05); }
60
+ .stats-banner span strong { color: var(--text); font-weight: 600; }
61
+ .stats-banner span strong.spent { color: var(--success); }
62
+
63
+ .btn { padding: 4px 12px; font-size: 12px; border-radius: 4px; border: none; cursor: pointer; font-weight: 600; transition: opacity 0.2s; }
64
+ .btn:hover { opacity: 0.8; }
65
+ .btn-save { background: var(--accent); color: #fff; }
66
+ .btn-stop { background: var(--danger); color: #fff; }
67
+ .btn-secondary { background: rgba(255,255,255,0.1); color: var(--text); }
68
+
69
+ /* min-height: 0 on every rung of the flex chain: a flex item's default
70
+ min-height is content-sized, which lets a tall Activity list push the
71
+ panel past its parent instead of the inner .stream-list scrolling.
72
+ overflow: hidden alone is not reliable across the nested flex levels
73
+ here -- without the explicit 0, large runs ended up with a clipped,
74
+ unscrollable activity widget. */
75
+ .main-content { display: flex; flex: 1; overflow: hidden; min-height: 0; }
76
+
77
+ .content-area { flex: 1; padding: 20px; display: flex; flex-direction: column; overflow: hidden; min-height: 0; }
78
+ .panel { background: var(--bg-glass); border: 1px solid var(--border); border-radius: 6px; display: flex; flex-direction: column; flex: 1; overflow: hidden; min-height: 0; }
79
+ .panel-header { flex-shrink: 0; padding: 10px 16px; font-size: 12px; font-weight: 600; color: var(--text-muted); border-bottom: 1px solid var(--border); background: rgba(255,255,255,0.02); text-transform: uppercase; letter-spacing: 0.5px; }
80
+
81
+ .stream-list { flex: 1; min-height: 0; padding: 12px; overflow-y: auto; display: flex; flex-direction: column; gap: 12px; background: #000; }
82
+
83
+ /* Tree Group */
84
+ /* apra-fleet-7lk / apra-fleet-eft.43: .tree-group and .tree-phase are
85
+ both flex ITEMS of an ancestor display: flex; flex-direction: column
86
+ container (#stream-list, .group-body) with no explicit height of their
87
+ own -- a flex item's default flex-shrink: 1 lets the browser squish it
88
+ below its content's natural size whenever the column tries to fit more
89
+ rows than its bounded parent has room for, instead of just letting the
90
+ (already scrollable, overflow-y: auto) ancestor grow past the fold and
91
+ scroll. flex-shrink: 0 pins each row to its content size so the bounded
92
+ pane scrolls, rather than crushing its children to fit. */
93
+ .tree-group { background: rgba(255,255,255,0.02); border: 1px solid var(--border); border-radius: 8px; overflow: hidden; flex-shrink: 0; }
94
+ .group-header { padding: 12px 16px; background: rgba(0,0,0,0.4); cursor: pointer; display: flex; justify-content: space-between; align-items: center; user-select: none; outline: none; list-style: none; }
95
+ .group-header h3 { font-size: 14px; font-weight: 700; color: var(--accent); margin: 0; }
96
+ .group-header:hover { background: rgba(0,0,0,0.6); }
97
+ .group-header::-webkit-details-marker { display: none; }
98
+ .group-body { padding: 12px; display: flex; flex-direction: column; gap: 8px; }
99
+
100
+ /* Tree Phase */
101
+ .tree-phase { background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.05); border-radius: 6px; overflow: hidden; flex-shrink: 0; }
102
+ .phase-header { padding: 8px 12px; cursor: pointer; display: flex; justify-content: space-between; align-items: center; user-select: none; border-bottom: 1px solid rgba(255,255,255,0.02); outline: none; list-style: none; }
103
+ .phase-header h4 { font-size: 13px; font-weight: 600; color: #e4e4e7; margin: 0; }
104
+ .phase-header:hover { background: rgba(255,255,255,0.05); }
105
+ .phase-header::-webkit-details-marker { display: none; }
106
+ /* apra-fleet-eft.53.2: mirrors .activity-meta -- the single flex item on
107
+ the right-hand side of the header's space-between row, so the phase
108
+ duration always sits flush right next to the toggle icon exactly like
109
+ an activity row's duration sits next to its status badge. */
110
+ .phase-meta { display: flex; gap: 12px; align-items: center; font-size: 11px; color: #a1a1aa; flex-shrink: 0; }
111
+ .phase-body { padding: 8px; display: flex; flex-direction: column; gap: 4px; }
112
+
113
+ .event-log { display: flex; gap: 8px; font-family: monospace; font-size: 12px; color: #d4d4d8; padding: 2px 4px; border-radius: 4px; }
114
+ .event-log:hover { background: rgba(255,255,255,0.05); }
115
+ .log-time { color: #52525b; width: 60px; flex-shrink: 0; user-select: none; }
116
+ .log-msg { white-space: pre-wrap; word-break: break-word; }
117
+
118
+ details.event-activity { border: 1px solid rgba(255,255,255,0.05); border-radius: 4px; background: rgba(255,255,255,0.02); font-family: monospace; margin: 2px 0; }
119
+ details.event-activity.log-multiline { border-color: rgba(255,255,255,0.02); background: transparent; }
120
+ details.event-activity.log-multiline summary { padding: 4px 8px; }
121
+
122
+ summary.activity-header { display: flex; align-items: center; padding: 6px 8px; font-size: 12px; gap: 8px; cursor: pointer; user-select: none; list-style: none; outline: none; }
123
+ summary.activity-header::-webkit-details-marker { display: none; }
124
+ summary.activity-header:hover { background: rgba(255,255,255,0.04); }
125
+
126
+ .activity-title { flex: 1; color: #e4e4e7; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
127
+ .activity-title .muted { color: #a1a1aa; font-weight: normal; font-size: 11px; margin-left: 6px; }
128
+ .activity-meta { display: flex; gap: 12px; align-items: center; font-size: 11px; color: #a1a1aa; flex-shrink: 0; }
129
+
130
+ .toggle-icon { margin-left: 8px; font-family: monospace; font-size: 14px; color: var(--text-muted); width: 14px; text-align: center; }
131
+ details:not([open]) > summary .toggle-icon::after { content: "+"; }
132
+ details[open] > summary .toggle-icon::after { content: "-"; }
133
+
134
+ .activity-body { padding: 0; background: #050505; border-top: 1px solid rgba(255,255,255,0.05); }
135
+ .activity-child { padding: 12px; font-size: 12px; white-space: pre-wrap; word-break: break-word; max-height: 400px; overflow-y: auto; }
136
+ .activity-child.output { color: #a1a1aa; border-left: 2px solid var(--accent); }
137
+ .activity-child.error { background: rgba(239, 68, 68, 0.05); color: var(--danger); border-left: 2px solid var(--danger); }
138
+
139
+ /* apra-fleet-eft.38: on-demand full-output button for a capped command
140
+ activity (GET /activities/:id/output, wired up in eft.27.4 but never
141
+ surfaced client-side until now). Deliberately its own small element,
142
+ never the activity's summary/header -- headers/titles stay a plain
143
+ expand/collapse toggle only. */
144
+ .more-btn { margin-left: 8px; padding: 1px 8px; font-size: 11px; font-family: sans-serif; border-radius: 4px; border: 1px solid var(--border); background: rgba(255,255,255,0.06); color: var(--accent); cursor: pointer; }
145
+ .more-btn:hover { background: rgba(255,255,255,0.12); }
146
+ .more-btn:disabled { cursor: default; opacity: 0.6; }
147
+
148
+ .status-badge { padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
149
+ .status-running { background: var(--accent-glow); color: var(--accent); animation: pulse 2s infinite; }
150
+ .status-success { background: rgba(16, 185, 129, 0.1); color: var(--success); }
151
+ .status-error { background: rgba(239, 68, 68, 0.1); color: var(--danger); }
152
+ .status-offline { background: rgba(239, 68, 68, 0.1); color: var(--danger); }
153
+
154
+ .status-live-indicator { display: inline-flex; align-items: center; gap: 6px; color: var(--success); font-weight: 700; letter-spacing: 0.5px; }
155
+ .led { width: 8px; height: 8px; border-radius: 50%; background: var(--success); box-shadow: 0 0 8px var(--success); animation: pulse 2s infinite; }
156
+
157
+ @keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.6; } 100% { opacity: 1; } }
158
+
159
+ .tab-bar { display: flex; gap: 8px; margin-bottom: 16px; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 8px; }
160
+ .tab-btn { background: transparent; color: #a1a1aa; border: none; padding: 6px 12px; cursor: pointer; border-radius: 4px; font-size: 13px; }
161
+ .tab-btn:hover { background: rgba(255,255,255,0.05); }
162
+ .tab-btn.active { color: #fff; background: rgba(255,255,255,0.1); }
163
+ .tab-content { display: none; }
164
+ /* apra-fleet-m0c: both #tab-core and #tab-beads also carry .panel
165
+ (flex column, flex:1, overflow:hidden), which is what lets
166
+ .stream-list's flex:1 + overflow-y:auto bound its height and scroll
167
+ on its own. A plain block display here had higher specificity
168
+ (.tab-content.active = 2 classes vs .panel = 1) and silently
169
+ overrode that to a plain block, so the whole page grew to fit every
170
+ activity instead of the inner list scrolling -- collapsing items was
171
+ the only way to shrink total height. Flex here still wins on
172
+ specificity but no longer conflicts with .panel's own flex layout. */
173
+ .tab-content.active { display: flex; min-height: 0; }
174
+
175
+ /* apra-fleet-4yr.1: in-page replacements for window.confirm()/alert()
176
+ on the Stop path -- native OS dialogs clash with the dark-glass UI.
177
+ Modal reuses .btn-stop's danger color for its Stop action; toast is
178
+ non-blocking and auto-dismisses. */
179
+ .modal-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.6); align-items: center; justify-content: center; z-index: 1000; }
180
+ .modal-overlay.open { display: flex; }
181
+ .modal-box { background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 20px; max-width: 360px; width: 90%; box-shadow: 0 8px 24px rgba(0,0,0,0.5); }
182
+ .modal-box p { color: var(--text); font-size: 13px; margin-bottom: 16px; line-height: 1.4; }
183
+ .modal-actions { display: flex; justify-content: flex-end; gap: 8px; }
184
+ .toast { position: fixed; bottom: 24px; right: 24px; background: var(--bg-glass); border: 1px solid var(--border); color: var(--text); padding: 10px 16px; border-radius: 6px; font-size: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.4); opacity: 0; transform: translateY(8px); transition: opacity 0.2s, transform 0.2s; pointer-events: none; z-index: 1001; }
185
+ .toast.show { opacity: 1; transform: translateY(0); }
186
+ </style>
187
+ </head>
188
+ <body data-view="${isHistory ? 'history' : 'live'}">
189
+ <div class="header">
190
+ <div class="header-title">
191
+ <h1><span id="workflow-name">Loading...</span></h1>
192
+ <!-- apra-fleet-dm5.1: short human "run title" sentence (workflow-
193
+ specific fields such as members/issue-ids/goal, when the running
194
+ workflow publishes them), rendered by renderState() below via
195
+ buildRunTitle(state). Falls back to the plain workflow name
196
+ (still non-empty, never blank) whenever the relevant fields
197
+ aren't populated. -->
198
+ <div id="run-title" class="run-title"></div>
199
+ </div>
200
+ <div class="header-actions">
201
+ <!-- apra-fleet-eft.37.3: generic, workflow-agnostic display of
202
+ state.result's top-level SCALAR fields -- populated (or hidden,
203
+ when empty) by renderState() below. Core never knows what keys
204
+ live inside 'result'; any richer, workflow-specific rendering
205
+ (e.g. auto-sprint's verdict badge/PR link) is layered on by a
206
+ dashboard extension's own js, not here. -->
207
+ <div class="stats-banner" id="result-strip" style="display: none;"></div>
208
+ <div class="stats-banner" id="stats-banner"></div>
209
+ <div id="status-indicator" style="font-size: 12px; font-weight: 600; min-width: 70px; text-align: center;"></div>
210
+ ${isHistory ? '' : '<button class="btn btn-save" onclick="saveState()">Save</button>'}
211
+ ${isHistory ? '' : '<button class="btn btn-stop" onclick="stopWorkflow()">Stop</button>'}
212
+ </div>
213
+ </div>
214
+ ${isHistory ? '' : `<div class="modal-overlay" id="stop-modal-overlay">
215
+ <div class="modal-box">
216
+ <p>Are you sure you want to forcibly stop the workflow?</p>
217
+ <div class="modal-actions">
218
+ <button class="btn btn-secondary" onclick="closeStopModal()">Cancel</button>
219
+ <button class="btn btn-stop" onclick="confirmStopWorkflow()">Stop</button>
220
+ </div>
221
+ </div>
222
+ </div>
223
+ <div class="toast" id="stop-toast">Stop signal sent.</div>`}
224
+ <div class="main-content">
225
+ <div class="content-area">
226
+ <div class="tab-bar" id="tab-bar">
227
+ <button class="tab-btn active" onclick="switchTab('core')">Activity Tree</button>
228
+ ${dashboardExtensions.map(ext => `<button class="tab-btn" onclick="switchTab('${ext.id}')">${ext.title}</button>`).join('\\n')}
229
+ </div>
230
+ <div id="tab-core" class="tab-content active panel">
231
+ <div class="panel-header" style="display: flex; justify-content: space-between; align-items: center;">
232
+ <span>Activity</span>
233
+ <button id="btn-toggle-all" onclick="toggleAllGlobal()" style="background: transparent; border: none; color: var(--text-muted); cursor: pointer; font-family: monospace; font-size: 14px; font-weight: bold; transition: color 0.2s;">[+]</button>
234
+ </div>
235
+ <div class="stream-list" id="stream-list"></div>
236
+ </div>
237
+ ${dashboardExtensions.map(ext => `
238
+ <div id="tab-${ext.id}" class="tab-content panel">
239
+ <div class="panel-header">${ext.title}</div>
240
+ <div id="extension-${ext.id}" style="flex: 1; min-height: 0; padding: 12px; overflow-y: auto;"></div>
241
+ </div>
242
+ `).join('\\n')}
243
+ </div>
244
+ </div>
245
+ ${dashboardExtensions.map(ext => `<script>\n${ext.js}\n</script>`).join('\\n')}
246
+ <script>
247
+ let globalState = null;
248
+ function switchTab(id) {
249
+ document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
250
+ document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
251
+ event.currentTarget.classList.add('active');
252
+ document.getElementById('tab-' + id).classList.add('active');
253
+ }
254
+
255
+ // apra-fleet-4wr.1: the ONE shared h/m/s duration formatter -- every
256
+ // duration display in this viewer (live elapsed, closed/frozen phase and
257
+ // activity durations, the stats-banner Uptime) goes through this, so a
258
+ // closed row and a live row of the same elapsed value render identically
259
+ // instead of one showing raw/decimal seconds and the other h/m/s.
260
+ // ms == null (missing -- not yet known) is the ONLY case that renders
261
+ // the '-' placeholder; a genuine zero or sub-second duration renders
262
+ // '0s', never '-'.
263
+ function formatTime(ms) {
264
+ if (ms === null || ms === undefined) return '-';
265
+ // apra-fleet-x8r.6: a frozen phase carrying an end timestamp but no/
266
+ // invalid start timestamp (or any other NaN-producing input) must fall
267
+ // back to the same '-' placeholder as the missing-value case above,
268
+ // never the literal string 'NaNs'.
269
+ if (!Number.isFinite(ms)) return '-';
270
+ if (ms < 0) return '0s';
271
+ let secs = Math.floor(ms / 1000);
272
+ let mins = Math.floor(secs / 60);
273
+ let hrs = Math.floor(mins / 60);
274
+ secs = secs % 60;
275
+ mins = mins % 60;
276
+
277
+ let out = [];
278
+ if (hrs > 0) out.push(hrs + 'hr');
279
+ if (mins > 0) out.push(mins + 'm');
280
+ out.push(secs + 's');
281
+ return out.join(' ');
282
+ }
283
+
284
+ // Live (still-running) elapsed durations, ticked forward on every
285
+ // render/poll from Date.now() - startTime -- delegates to formatTime()
286
+ // for the actual h/m/s formatting (the shared formatter above), only
287
+ // differing in that a falsy/negative/missing ms (nothing meaningful to
288
+ // show yet) renders '0s' rather than formatTime's own '-' missing-value
289
+ // case, since a live row always has SOME elapsed value once it starts.
290
+ function formatUptime(ms) {
291
+ if (!ms || ms < 0) return '0s';
292
+ return formatTime(ms);
293
+ }
294
+
295
+ // Shared with dashboard extensions -- see src/viewer/html-utils.mjs for
296
+ // why this is embedded via escapeHtml.toString() instead of duplicated.
297
+ ${escapeHtml.toString()}
298
+
299
+ // apra-fleet-dm5.1: buildRunTitle() references escapeHtml by bare name
300
+ // (not an import) -- embedded here, right after escapeHtml itself, so
301
+ // that identifier resolves in this plain <script> tag exactly as it
302
+ // does in run-title.mjs's real ES-module scope.
303
+ ${buildRunTitle.toString()}
304
+
305
+ // apra-fleet-eft.27.1: GET /state's lean list-state payload dedupes
306
+ // repeated strings into a shared \`_strings\` table (see
307
+ // src/viewer/lean-state.mjs) -- this is that module's resolveStringRefs()
308
+ // embedded verbatim (same .toString() pattern as escapeHtml above) so the
309
+ // browser can undo the same transform before rendering. Safe to run on
310
+ // ANY state object, including a History view's frozen literal that never
311
+ // went through dedupeStrings(): with no \`{ $ref }\` markers present it's a
312
+ // no-op pass-through.
313
+ ${resolveStringRefs.toString()}
314
+
315
+ function saveState() {
316
+ if (!globalState) return;
317
+ const blob = new Blob([JSON.stringify(globalState, null, 2)], { type: "application/json" });
318
+ const url = URL.createObjectURL(blob);
319
+ const a = document.createElement('a');
320
+ a.href = url;
321
+ a.download = 'workflow-state.json';
322
+ a.click();
323
+ }
324
+
325
+ // apra-fleet-4yr.1: in-page modal replaces window.confirm() for the
326
+ // Stop confirmation step (the safety check itself stays -- only the
327
+ // native dialog is replaced), and a non-blocking toast replaces
328
+ // window.alert() once /stop resolves.
329
+ function stopWorkflow() {
330
+ const overlay = document.getElementById('stop-modal-overlay');
331
+ if (overlay) overlay.classList.add('open');
332
+ }
333
+
334
+ function closeStopModal() {
335
+ const overlay = document.getElementById('stop-modal-overlay');
336
+ if (overlay) overlay.classList.remove('open');
337
+ }
338
+
339
+ function showStopToast() {
340
+ const toast = document.getElementById('stop-toast');
341
+ if (!toast) return;
342
+ toast.classList.add('show');
343
+ setTimeout(() => toast.classList.remove('show'), 3000);
344
+ }
345
+
346
+ async function confirmStopWorkflow() {
347
+ closeStopModal();
348
+ await fetch('/stop', { method: 'POST' });
349
+ showStopToast();
350
+ }
351
+
352
+ document.addEventListener('keydown', (ev) => {
353
+ if (ev.key === 'Escape') closeStopModal();
354
+ });
355
+
356
+ let allExpanded = true;
357
+ function toggleAllGlobal() {
358
+ allExpanded = !allExpanded;
359
+ document.querySelectorAll('details').forEach(d => {
360
+ if (allExpanded) d.setAttribute('open', '');
361
+ else d.removeAttribute('open');
362
+ });
363
+ const btn = document.getElementById('btn-toggle-all');
364
+ btn.textContent = allExpanded ? '[-]' : '[+]';
365
+ btn.style.color = allExpanded ? 'var(--text)' : 'var(--text-muted)';
366
+ }
367
+
368
+ let isAutoScrolling = true;
369
+ const streamEl = document.getElementById('stream-list');
370
+
371
+ streamEl.addEventListener('scroll', () => {
372
+ isAutoScrolling = (streamEl.scrollTop + streamEl.clientHeight >= streamEl.scrollHeight - 30);
373
+ });
374
+
375
+ // apra-fleet-eft.38: on-demand full-output fetch for a capped command
376
+ // activity's 'more...' button (see fieldBlock() above). Delegated on
377
+ // streamEl (not one listener per button) since renderTreeIncremental()
378
+ // keeps appending new activity elements as the run progresses.
379
+ // Deliberately scoped to .more-btn clicks only -- never the activity's
380
+ // own <summary> header, which keeps its native <details> expand/collapse
381
+ // behavior untouched.
382
+ let expandedMoreBtn = null;
383
+ function collapseMoreBtn(btn) {
384
+ if (!btn) return;
385
+ const span = btn.previousElementSibling;
386
+ if (span && span.dataset.truncatedText !== undefined) {
387
+ span.textContent = span.dataset.truncatedText;
388
+ }
389
+ btn.dataset.state = '';
390
+ btn.disabled = false;
391
+ btn.textContent = btn.dataset.label || 'more...';
392
+ if (expandedMoreBtn === btn) expandedMoreBtn = null;
393
+ }
394
+ streamEl.addEventListener('click', async (e) => {
395
+ const btn = e.target.closest('.more-btn');
396
+ if (!btn) return;
397
+ const span = btn.previousElementSibling;
398
+ if (!span) return;
399
+
400
+ if (btn.dataset.state === 'expanded') {
401
+ // Toggle back to the capped preview -- no re-fetch needed.
402
+ collapseMoreBtn(btn);
403
+ return;
404
+ }
405
+ if (btn.dataset.state === 'loading') return;
406
+
407
+ // apra-fleet-eft.38: only ONE activity's full output is ever held
408
+ // expanded in the DOM at a time. Fetched command output can run to
409
+ // many MB, and keeping several fully expanded simultaneously is
410
+ // exactly the kind of unbounded-DOM growth apra-fleet-eft.27/27.4
411
+ // already fixed for the initial render -- a new 'more...' click
412
+ // collapses whichever block was previously expanded back to its
413
+ // capped preview first.
414
+ if (expandedMoreBtn && expandedMoreBtn !== btn) {
415
+ collapseMoreBtn(expandedMoreBtn);
416
+ }
417
+
418
+ if (span.dataset.truncatedText === undefined) {
419
+ span.dataset.truncatedText = span.textContent;
420
+ }
421
+ const activityId = btn.dataset.activityId;
422
+ const field = btn.dataset.field;
423
+ btn.dataset.state = 'loading';
424
+ btn.disabled = true;
425
+ btn.textContent = 'loading...';
426
+ try {
427
+ const res = await fetch('/activities/' + encodeURIComponent(activityId) + '/output');
428
+ if (!res.ok) throw new Error('request failed: ' + res.status);
429
+ const data = await res.json();
430
+ const full = data[field];
431
+ if (typeof full !== 'string') throw new Error('missing ' + field + ' in response');
432
+ span.textContent = full;
433
+ btn.dataset.state = 'expanded';
434
+ btn.disabled = false;
435
+ btn.textContent = 'less';
436
+ expandedMoreBtn = btn;
437
+ } catch (err) {
438
+ btn.dataset.state = '';
439
+ btn.disabled = false;
440
+ btn.textContent = 'failed to load (retry?)';
441
+ }
442
+ });
443
+
444
+ ${isHistory ? '' : `
445
+ // Coalesce SSE-triggered refreshes: a busy run broadcasts one event
446
+ // per log line / activity tick, and refetching + re-rendering the full
447
+ // (potentially multi-MB) /state payload for each of them is what made
448
+ // large runs sluggish. One trailing refresh per window is enough --
449
+ // renderState() always paints the latest snapshot, not a delta.
450
+ const POLL_COALESCE_MS = 400;
451
+ let pollTimer = null;
452
+ function schedulePoll() {
453
+ if (pollTimer) return;
454
+ pollTimer = setTimeout(() => { pollTimer = null; poll(); }, POLL_COALESCE_MS);
455
+ }
456
+ const source = new EventSource('/events');
457
+ source.onmessage = (e) => {
458
+ const ev = JSON.parse(e.data);
459
+ if (ev.type === 'state') {
460
+ const extEvent = new CustomEvent('workflow:state:' + ev.payload.namespace, { detail: ev.payload.data });
461
+ document.dispatchEvent(extEvent);
462
+ }
463
+ schedulePoll();
464
+ };
465
+
466
+ // apra-fleet-36l.1: during a quiet period (no SSE messages at all --
467
+ // e.g. a long-running agent activity with no intermediate log/activity
468
+ // events) the EventSource-driven schedulePoll() above never fires, so
469
+ // the dashboard can sit on a stale /state snapshot indefinitely with no
470
+ // visible sign it's still alive. This client-side heartbeat interval is
471
+ // a second, independent trigger for the SAME schedulePoll()/poll() path
472
+ // (not a separate fetch), so it naturally coalesces with -- and never
473
+ // double-fires alongside -- a real event-driven poll: schedulePoll()'s
474
+ // own pollTimer guard (POLL_COALESCE_MS above) already no-ops if a poll
475
+ // is already scheduled/in flight when the heartbeat tick lands.
476
+ const HEARTBEAT_INTERVAL_MS = 7000;
477
+ setInterval(() => { schedulePoll(); }, HEARTBEAT_INTERVAL_MS);
478
+ `}
479
+
480
+ function renderTreeIncremental(tree) {
481
+ tree.forEach((group, gIdx) => {
482
+ let groupEl = document.getElementById('group-' + gIdx);
483
+ if (!groupEl) {
484
+ groupEl = document.createElement('details');
485
+ groupEl.id = 'group-' + gIdx;
486
+ groupEl.className = 'tree-group';
487
+ groupEl.open = true;
488
+ groupEl.innerHTML = \`<summary class="group-header"><h3>\${escapeHtml(group.title)}</h3><span class="toggle-icon"></span></summary><div class="group-body"></div>\`;
489
+ streamEl.appendChild(groupEl);
490
+ }
491
+ const groupBody = groupEl.querySelector('.group-body');
492
+
493
+ group.phases.forEach((phase, pIdx) => {
494
+ const phaseId = \`phase-\${gIdx}-\${pIdx}\`;
495
+ let phaseEl = document.getElementById(phaseId);
496
+ if (!phaseEl) {
497
+ phaseEl = document.createElement('details');
498
+ phaseEl.id = phaseId;
499
+ phaseEl.className = 'tree-phase';
500
+ phaseEl.open = true;
501
+ phaseEl.innerHTML = \`<summary class="phase-header"><h4>\${escapeHtml(phase.title)}</h4><div class="phase-meta"><span class="phase-duration"></span><span class="toggle-icon"></span></div></summary><div class="phase-body"></div>\`;
502
+ groupBody.appendChild(phaseEl);
503
+ }
504
+
505
+ // apra-fleet-eft.53.2: phase-header duration, mirroring the
506
+ // activity-duration convention (eft.45.1) -- while the phase
507
+ // is LIVE (phaseStartedAt set, no phaseEndedAt yet) show
508
+ // elapsed-since-start via formatUptime, recomputed from
509
+ // Date.now() on every renderTreeIncremental() call so it
510
+ // ticks forward on the normal refresh/SSE cadence with no
511
+ // dedicated timer. Once the phase EXITS (phaseEndedAt set)
512
+ // the frozen total is rendered via formatTime exactly like a
513
+ // completed activity's duration, and dataset.rendered is set
514
+ // so later re-renders (including of earlier-cycle phases
515
+ // after a resume/reload) never recompute it again.
516
+ const phaseDurationEl = phaseEl.querySelector('.phase-duration');
517
+ if (phaseDurationEl && phaseDurationEl.dataset.rendered !== 'done') {
518
+ let phaseDurationHtml = '';
519
+ if (phase.phaseEndedAt) {
520
+ phaseDurationHtml = formatTime(new Date(phase.phaseEndedAt).getTime() - new Date(phase.phaseStartedAt).getTime());
521
+ phaseDurationEl.dataset.rendered = 'done';
522
+ } else if (phase.phaseStartedAt) {
523
+ phaseDurationHtml = formatUptime(Date.now() - new Date(phase.phaseStartedAt).getTime());
524
+ }
525
+ phaseDurationEl.textContent = phaseDurationHtml;
526
+ }
527
+
528
+ const phaseBody = phaseEl.querySelector('.phase-body');
529
+
530
+ phase.events.forEach((ev, eIdx) => {
531
+ const evId = \`ev-\${gIdx}-\${pIdx}-\${eIdx}\`;
532
+ let evEl = document.getElementById(evId);
533
+
534
+ if (ev.type === 'log') {
535
+ if (!evEl) {
536
+ evEl = document.createElement('div');
537
+ evEl.id = evId;
538
+ const dateObj = new Date(ev.time || Date.now());
539
+ const t = isNaN(dateObj.getTime()) ? '-' : dateObj.toLocaleTimeString([], { hour12: false });
540
+
541
+ // apra-fleet-aqq: a log message needs truncation
542
+ // + drill-down whenever it would run past one row
543
+ // -- not just multiline ones. A single-line
544
+ // JSON.stringify'd verdict (e.g. the Plan
545
+ // Reviewer's) has no '\\n' at all but can easily
546
+ // run past a thousand characters, and used to
547
+ // render via the plain .log-msg path below, which
548
+ // has no length cap and just wraps across many
549
+ // rows with the full text always visible inline
550
+ // (no truncation, but also nothing to "drill
551
+ // into" -- it was simply always fully expanded).
552
+ // Both cases now share the same truncate-with-
553
+ // ellipsis + expandable-details treatment; only
554
+ // how the preview/full-text split is computed
555
+ // differs (by line vs. by character count).
556
+ const LOG_PREVIEW_CHARS = 200;
557
+ const isMultiline = ev.msg && ev.msg.includes('\\n');
558
+ const isLongSingleLine = ev.msg && !isMultiline && ev.msg.length > LOG_PREVIEW_CHARS;
559
+ if (isMultiline || isLongSingleLine) {
560
+ let firstLine, rest;
561
+ if (isMultiline) {
562
+ const lines = ev.msg.split('\\n');
563
+ firstLine = lines[0];
564
+ rest = lines.slice(1).join('\\n');
565
+ } else {
566
+ firstLine = ev.msg.slice(0, LOG_PREVIEW_CHARS);
567
+ rest = ev.msg.slice(LOG_PREVIEW_CHARS);
568
+ }
569
+ evEl.innerHTML = \`<details class="event-activity log-multiline">
570
+ <summary class="activity-header">
571
+ <span class="log-time">\${t}</span>
572
+ <span class="activity-title" style="font-family:monospace; font-size:12px; color:#d4d4d8; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
573
+ \${escapeHtml(firstLine)} <em style="color:#a1a1aa">...</em>
574
+ </span>
575
+ <div class="activity-meta"><span class="toggle-icon"></span></div>
576
+ </summary>
577
+ <div class="activity-body">
578
+ <div class="activity-child" style="color:#d4d4d8;">\${escapeHtml(isMultiline ? rest : ev.msg)}</div>
579
+ </div>
580
+ </details>\`;
581
+ } else {
582
+ evEl.className = 'event-log';
583
+ evEl.innerHTML = \`<span class="log-time">\${t}</span><span class="log-msg">\${escapeHtml(ev.msg)}</span>\`;
584
+ }
585
+ phaseBody.appendChild(evEl);
586
+ }
587
+ } else if (ev.type === 'activity') {
588
+ const act = ev.data;
589
+ if (!evEl) {
590
+ evEl = document.createElement('details');
591
+ evEl.id = evId;
592
+ evEl.className = 'event-activity';
593
+ if (act.isRunning) {
594
+ evEl.open = true;
595
+ }
596
+ phaseBody.appendChild(evEl);
597
+ }
598
+
599
+ // A finished activity's data never changes again
600
+ // (activity:end merges its meta exactly once), so
601
+ // re-render it exactly once. Rewriting every
602
+ // activity's innerHTML on every tick -- thousands of
603
+ // DOM subtrees, some holding megabyte agent outputs
604
+ // -- is the other half of what made large runs
605
+ // sluggish, and the constant churn also fought the
606
+ // user's own scrolling and text selection.
607
+ if (evEl.dataset.rendered === 'done') return;
608
+
609
+ // Update contents every tick to catch status changes
610
+ const dateObj = new Date(act.startTime || Date.now());
611
+ const t = isNaN(dateObj.getTime()) ? '-' : dateObj.toLocaleTimeString([], { hour12: false });
612
+
613
+ let badge = '';
614
+ if (act.isRunning) badge = '<span class="status-badge status-running">Running</span>';
615
+ else if (act.success) badge = '<span class="status-badge status-success">Success</span>';
616
+ else badge = '<span class="status-badge status-error">Failed</span>';
617
+
618
+ let childrenHtml = '';
619
+ if (!act.isRunning) {
620
+ // apra-fleet-eft.69.1: THE UNIFORM COMMAND/AGENT
621
+ // ROW-BODY RULE (bug item 3 -- "some command rows
622
+ // carry details in the body while many others
623
+ // show only a title; make the rule uniform and
624
+ // documented"). There is exactly ONE rule, and it
625
+ // is keyed ONLY on the two generic fields every
626
+ // completed activity may carry -- never on
627
+ // act.type, act.label, act.member, or any
628
+ // role/phase name (the HARD CONSTRAINT from
629
+ // apra-fleet-eft.69: no auto-sprint-specific
630
+ // special-casing in viewer code):
631
+ // 1. hasField('error') true -> render the error
632
+ // block (plus Output: underneath, if any).
633
+ // 2. else hasField('output') true -> render the
634
+ // output block.
635
+ // 3. else -> no body at all; the row is title
636
+ // only.
637
+ // hasField() below is true when the field is
638
+ // either a non-empty inline string OR carries the
639
+ // <field>Truncated/<field>ByteLength markers
640
+ // (lean-state.mjs / command-output-cap.mjs). This
641
+ // applies IDENTICALLY to every activity type --
642
+ // 'agent', 'command', 'transform', or any future
643
+ // generic type -- so a command that legitimately
644
+ // produced no output and no error (e.g. a plain
645
+ // 'git add', a successful 'bd update --claim')
646
+ // showing only its title is the CORRECT,
647
+ // consistent result of this one rule applied to
648
+ // different data, not a special case or a bug --
649
+ // the same command with real output/error would
650
+ // render a body exactly the same way an agent
651
+ // dispatch does. (The full invoked command text
652
+ // itself is NOT part of this rule -- it lives in
653
+ // the row's title/label, capped to 60 chars at
654
+ // dispatch time; the runner.js command() caller
655
+ // is responsible for choosing a diagnostic label
656
+ // when the command text alone would not be, same
657
+ // as agent()'s label.)
658
+ //
659
+ // apra-fleet-eft.38 (reopened): a REAL capped
660
+ // activity ships NO inline text field at all --
661
+ // only the markers (\${field}Truncated + the TRUE
662
+ // original \${field}ByteLength) plus a short
663
+ // \`summary\` string (see command-output-cap.mjs for
664
+ // \`command\` activities, and lean-state.mjs's
665
+ // summarizeHeavyFields() for every other activity
666
+ // type, e.g. \`agent\`). The previous version of this
667
+ // fix keyed the button on act.output/act.error
668
+ // being truthy, which a real capped payload never
669
+ // is -- 0 buttons ever rendered. hasField()/
670
+ // fieldBlock() below key on the MARKERS instead:
671
+ // present inline text wins as the preview when
672
+ // available (e.g. an uncapped History-view state),
673
+ // otherwise the leaned \`summary\` is the preview,
674
+ // and the 'more...' button (never on the
675
+ // activity's own summary/header, which stays a
676
+ // plain expand/collapse toggle only) fetches the
677
+ // full text on demand from GET
678
+ // /activities/:id/output.
679
+ const hasField = (field) =>
680
+ typeof act[field] === 'string' ||
681
+ act[field + 'Truncated'] ||
682
+ act[field + 'ByteLength'] !== undefined;
683
+ const fieldBlock = (prefix, field) => {
684
+ const truncated = act[field + 'Truncated'];
685
+ const bytes = act[field + 'ByteLength'];
686
+ const text = typeof act[field] === 'string'
687
+ ? act[field]
688
+ : (typeof act.summary === 'string' ? act.summary : '');
689
+ const label = truncated
690
+ ? \`more... (\${(bytes || 0).toLocaleString()} bytes total)\`
691
+ : '';
692
+ const btn = truncated
693
+ ? \` <button type="button" class="more-btn" data-activity-id="\${escapeHtml(String(act.id))}" data-field="\${field}" data-label="\${escapeHtml(label)}">\${escapeHtml(label)}</button>\`
694
+ : '';
695
+ return \`\${prefix}<span class="output-text" data-field="\${field}">\${escapeHtml(text)}</span>\${btn}\`;
696
+ };
697
+ if (hasField('error')) {
698
+ childrenHtml = \`<div class="activity-child error">\${fieldBlock('', 'error')}\\n\\n\${act.input ? 'Input:\\n' + escapeHtml(act.input) + '\\n\\n' : ''}\${hasField('output') ? fieldBlock('Output:\\n', 'output') : ''}</div>\`;
699
+ } else if (hasField('output')) {
700
+ childrenHtml = \`<div class="activity-child output">\${act.input && act.type === 'transform' ? 'Input:\\n' + escapeHtml(act.input) + '\\n\\nOutput:\\n' : ''}\${fieldBlock('', 'output')}</div>\`;
701
+ }
702
+ }
703
+
704
+ // Token count and model tier are two DISTINCT pieces of
705
+ // information -- previously only tokensHtml existed,
706
+ // so a finished agent activity with no usage data (see
707
+ // apra-fleet-13o) rendered a bare "n/a" that was easy
708
+ // to misread as a missing model tier, when the model
709
+ // tier was never displayed at all. modelHtml surfaces
710
+ // act.model (e.g. "premium"/"standard", already
711
+ // present on every agent activity) explicitly.
712
+ let tokensHtml = act.usage ? \`<span style="color:var(--text-muted)">\${act.usage.total_tokens.toLocaleString()} tkns</span>\` : (act.type === 'agent' && !act.isRunning ? \`<span style="color:var(--text-muted)">n/a</span>\` : '');
713
+ const modelHtml = (act.type === 'agent' && act.model) ? \`<span style="color:var(--text-muted)">[\${escapeHtml(act.model)}]</span>\` : '';
714
+ const memberDisplay = act.member ? escapeHtml(act.member) : (act.type === 'transform' ? 'js' : '');
715
+ const memberHtml = memberDisplay ? \`<span class="muted">(\${memberDisplay})</span>\` : '';
716
+
717
+ // apra-fleet-eft.45.1: while an activity is still
718
+ // running (isRunning true, no final act.duration
719
+ // yet), render elapsed-since-start at the same right-
720
+ // edge slot the final duration occupies, using the
721
+ // same short-form ('0s'/'5s'/'1m 20s') as
722
+ // formatUptime -- not formatTime's '1.5s' decimal
723
+ // form, which is reserved for the completed-duration
724
+ // label. Recomputed from act.startTime on every
725
+ // render call, so each poll/refresh naturally ticks
726
+ // it forward without a dedicated timer (out of scope
727
+ // per eft.45). On completion this branch stops
728
+ // firing (act.isRunning goes false) and the existing
729
+ // act.duration branch below takes over unchanged.
730
+ let durationHtml = '';
731
+ if (act.isRunning) {
732
+ if (act.startTime) durationHtml = formatUptime(Date.now() - act.startTime);
733
+ } else if (act.duration) {
734
+ durationHtml = formatTime(act.duration);
735
+ }
736
+
737
+ evEl.innerHTML = \`
738
+ <summary class="activity-header">
739
+ <span class="log-time">\${t}</span>
740
+ <span class="activity-title"><strong>\${escapeHtml(act.type.toUpperCase())}</strong>: \${escapeHtml(act.label)} \${memberHtml}</span>
741
+ <div class="activity-meta">
742
+ \${modelHtml}
743
+ \${tokensHtml}
744
+ \${durationHtml} \${badge}
745
+ <span class="toggle-icon"></span>
746
+ </div>
747
+ </summary>
748
+ \${childrenHtml ? \`<div class="activity-body">\${childrenHtml}</div>\` : ''}
749
+ \`;
750
+ if (!act.isRunning) evEl.dataset.rendered = 'done';
751
+ }
752
+ });
753
+ });
754
+ });
755
+ }
756
+
757
+ // apra-fleet-eft.6.5: the DOM-update half of what used to be poll()'s try
758
+ // block, factored out so the History view can feed it a FROZEN state
759
+ // object directly (see the bottom of this script) without ever calling
760
+ // fetch('/state') itself -- poll() (live view only) still drives it from
761
+ // the network.
762
+ function renderState(state) {
763
+ globalState = state;
764
+
765
+ document.getElementById('workflow-name').textContent = state.workflowName;
766
+
767
+ // apra-fleet-dm5.1: buildRunTitle() returns an ALREADY-ESCAPED HTML
768
+ // fragment (every user-supplied piece -- member names, bead ids,
769
+ // goal -- individually run through escapeHtml before being embedded
770
+ // into the sentence), safe to assign directly here.
771
+ const runTitleEl = document.getElementById('run-title');
772
+ if (runTitleEl) runTitleEl.innerHTML = buildRunTitle(state);
773
+
774
+ const ind = document.getElementById('status-indicator');
775
+ if (state.status === 'running') { ind.innerHTML = '<div class="status-live-indicator"><div class="led"></div> LIVE</div>'; }
776
+ else if (state.status === 'success') { ind.innerHTML = '<span style="color:var(--success)">DONE</span>'; }
777
+ else if (state.status === 'cancelled') { ind.innerHTML = '<span style="color:var(--warning)">CANCELLED</span>'; }
778
+ else { ind.innerHTML = '<span style="color:var(--danger)">FAILED</span>'; }
779
+
780
+ const dur = state.status === 'running' ? Date.now() - state.stats.startTime : state.stats.durationMs;
781
+ const unknownCostSuffix = state.stats.unknownCostCount > 0 ? \` <span style="color:var(--warning)">(+\${state.stats.unknownCostCount} unknown)</span>\` : '';
782
+ document.getElementById('stats-banner').innerHTML =
783
+ \`<span><strong>\${state.stats.activitiesCount}</strong> Activities</span>
784
+ <span><strong class="spent">$\${state.stats.totalCost.toFixed(3)}</strong> Spent\${unknownCostSuffix}</span>
785
+ <span><strong>\${state.stats.totalTokens.toLocaleString()}</strong> Tokens</span>
786
+ <span><strong>\${formatUptime(dur)}</strong> Uptime</span>\`;
787
+
788
+ // apra-fleet-eft.37.3: generic Result strip -- every workflow gets
789
+ // its terminal result's top-level SCALAR (string/number/boolean/
790
+ // null) fields rendered as a plain key/value strip, no per-workflow
791
+ // registration needed. Core does not know or care what these keys
792
+ // mean; it only knows how to display a scalar. \`workflow:result\`
793
+ // is also dispatched (below) so a dashboard extension can layer
794
+ // richer, workflow-specific rendering (e.g. auto-sprint's verdict
795
+ // badge/PR link) on top of the same \`state.result\` object.
796
+ const resultStrip = document.getElementById('result-strip');
797
+ if (resultStrip) {
798
+ const result = state.result;
799
+ const scalarEntries = (result && typeof result === 'object' && !Array.isArray(result))
800
+ ? Object.entries(result).filter(([, v]) => v === null || ['string', 'number', 'boolean'].includes(typeof v))
801
+ : [];
802
+ if (scalarEntries.length > 0) {
803
+ resultStrip.innerHTML = scalarEntries
804
+ .map(([k, v]) => \`<span><strong>\${escapeHtml(k)}</strong>: \${escapeHtml(String(v))}</span>\`)
805
+ .join('');
806
+ resultStrip.style.display = 'flex';
807
+ } else {
808
+ resultStrip.innerHTML = '';
809
+ resultStrip.style.display = 'none';
810
+ }
811
+ document.dispatchEvent(new CustomEvent('workflow:result', { detail: result ?? null }));
812
+ }
813
+
814
+ renderTreeIncremental(state.tree);
815
+
816
+ if (state.extensions) {
817
+ for (const [ns, data] of Object.entries(state.extensions)) {
818
+ const extEvent = new CustomEvent('workflow:state:' + ns, { detail: data });
819
+ document.dispatchEvent(extEvent);
820
+ }
821
+ }
822
+
823
+ if (isAutoScrolling) {
824
+ streamEl.scrollTop = streamEl.scrollHeight;
825
+ }
826
+ }
827
+
828
+ async function poll() {
829
+ try {
830
+ const res = await fetch('/state?_t=' + Date.now(), { cache: 'no-store' });
831
+ const raw = await res.json();
832
+ // apra-fleet-eft.27.1: undo the server's string-table dedup before
833
+ // handing the state to renderState()/renderTreeIncremental(), which
834
+ // both expect plain, already-resolved strings.
835
+ const state = resolveStringRefs(raw, raw._strings || []);
836
+ renderState(state);
837
+ } catch(e) {
838
+ console.error("Poll Error:", e);
839
+ if (globalState && (globalState.status === 'success' || globalState.status === 'failed' || globalState.status === 'cancelled')) {
840
+ // already done, ignore
841
+ } else {
842
+ document.getElementById('status-indicator').innerHTML = '<span class="status-badge status-offline">OFFLINE</span>';
843
+ }
844
+ }
845
+ }
846
+
847
+ ${isHistory
848
+ ? `// History view: render the frozen state ONCE, directly -- no
849
+ // fetch('/state') and no EventSource('/events') (asserted: zero polling
850
+ // requests for a finished run with zero running processes).
851
+ renderState(${frozenStateLiteral});`
852
+ : 'poll();'}
853
+ </script>
854
+ </body>
855
+ </html>`;
856
+ };
857
+
858
+ // apra-fleet-eft.37.4 (M3, docs/workflow-core-boundary-refactoring.md): the
859
+ // on-demand FULL-TEXT lookup used to live here as findBeadById(), a
860
+ // core function that reached into `state.extensions.beads.sprintTasks/
861
+ // backlogTasks` by name -- the one deliberate domain leak the eft.27.2
862
+ // comment it replaced used to call out explicitly. Core has no business
863
+ // knowing an extension's internal shape, so that function moved verbatim
864
+ // into the beads extension module itself
865
+ // (packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs, as
866
+ // `beadsExtension.detailLookup`). Core now only knows the GENERIC hook
867
+ // surface: any dashboard extension may register
868
+ // `detailLookup?: (state, id) => {text, updatedAt} | null`, and core serves
869
+ // GET /extensions/:extId/detail/:itemId (route below) by delegating to
870
+ // whichever extension's `id` matches `:extId` -- a template-method default
871
+ // of "no such extension/no hook -> 404", never a crash, for extensions that
872
+ // don't opt in.
873
+
874
+ // apra-fleet-eft.38 (reopened): fallback lookup for GET /activities/:id/output
875
+ // (see the route below) when command-output-cap.mjs's own store has nothing
876
+ // for the id -- true for every activity type it never caps (most notably
877
+ // `agent`: its full LLM response text is never trimmed at storage time, only
878
+ // at GET /state's wire-shaping stage by lean-state.mjs's summarizeHeavyFields(),
879
+ // which now stamps the same <field>Truncated markers on it -- see that
880
+ // module). Reads from the LIVE, full-fidelity in-memory `state.tree` (never
881
+ // the leaned /state payload), which is where an uncapped activity's complete
882
+ // output/error text still lives.
883
+ function findActivityById(state, id) {
884
+ for (const g of state.tree || []) {
885
+ for (const p of g.phases || []) {
886
+ const ev = (p.events || []).find((e) => e.type === 'activity' && String(e.id) === String(id));
887
+ if (ev) return ev.data;
888
+ }
889
+ }
890
+ return null;
891
+ }
892
+
893
+ // apra-fleet-eft.6.5: exported so the supervisor's process-free History view
894
+ // (packages/apra-fleet-se/src/supervisor/history-view.mjs) can render a
895
+ // finished run's persisted terminal state through the SAME template the
896
+ // live viewer serves, fed a frozen state object (opts.history / opts.state)
897
+ // instead of standing up a whole createDashboardViewer() (which owns a live
898
+ // http.createServer + workflow event wiring this read-only view has no use
899
+ // for).
900
+ export { HTML_TEMPLATE };
901
+
902
+ /**
903
+ * Creates a live dashboard viewer HTTP server for a workflow run.
904
+ * @param {import('../workflow/index.mjs').FleetWorkflow} workflow
905
+ * @param {Object} opts - Options object
906
+ * @param {number} [opts.port=8080] - HTTP server port
907
+ * @param {string} [opts.runId] - Stable per-run identifier (generated if not provided)
908
+ * @param {string} [opts.name] - Workflow display name
909
+ * @param {string} [opts.debouncedStatePath] - Path to write state JSON (uses default if not provided)
910
+ * @param {*} [opts.launchArgs] - Opaque, free-form per-workflow metadata (NOT argv).
911
+ * `launchArgs` is passed through unchanged into state.args and is never inspected
912
+ * or interpreted by core -- consumers must feature-detect the fields they need
913
+ * rather than assuming a type. Examples: argv array from test callers
914
+ * (['--track', 'eft-service'], ['--foo', 'bar']), or a structured object from
915
+ * fleet-sprint (e.g., { members, targetIssues, goal }). Defaults to null if omitted.
916
+ * @param {Array} [opts.dashboardExtensions] - Dashboard widget extensions
917
+ * @param {Object} [opts.env] - Environment variables (defaults to process.env)
918
+ */
919
+ export function createDashboardViewer(workflow, opts = {}) {
920
+ const port = (typeof opts.port === 'number') ? opts.port : 8080;
921
+ const dashboardExtensions = opts.dashboardExtensions || [];
922
+
923
+ // apra-fleet-eft.2.3 (renamed under eft.37.1): stable per-run id, NOT an
924
+ // HHMMSS-style clock key (see run-state-paths.mjs) -- this is what
925
+ // running/<id>.json / old_runs/<id>.json are keyed by, so two runs started
926
+ // in the same second on different days never collide. Callers that already
927
+ // know a meaningful id (e.g. the auto-sprint runner's own runId) can pass
928
+ // opts.runId; otherwise one is generated here.
929
+ const env = opts.env || process.env;
930
+ // BOUNDARY-COMPAT: opts.sprintId is the pre-rename alias for opts.runId.
931
+ // Accept it for one release with a deprecation warning so callers migrate
932
+ // to opts.runId without a flag day; sprintId appears in core code only on
933
+ // this line. Remove this shim one release after the se consumers pass
934
+ // opts.runId directly.
935
+ const legacyRunId = opts.sprintId;
936
+ if (legacyRunId !== undefined && opts.runId === undefined) {
937
+ console.warn('[Viewer] opts.sprintId is deprecated; pass opts.runId instead.');
938
+ }
939
+ const runId = opts.runId || legacyRunId || randomUUID();
940
+
941
+ // apra-fleet-eft.2.3: the debounced writer's target defaults to
942
+ // <serviceDataDir>/running/<runId>.json (outside the repo checkout --
943
+ // see getFleetDataDir()/APRA_FLEET_DATA_DIR), NOT the snapshot dir. Only
944
+ // when a caller passes an explicit opts.debouncedStatePath (tests, or a
945
+ // future caller with its own layout) do we skip the running/-> old_runs/
946
+ // move-on-completion below, since we can no longer assume that path lives
947
+ // under a running/ directory we're allowed to rename out of.
948
+ const usingDefaultStatePath = !opts.debouncedStatePath;
949
+ const runningStatePath = opts.debouncedStatePath || getRunningRunStatePath(runId, env);
950
+
951
+ const nowIso = () => new Date().toISOString();
952
+ const startedAtIso = nowIso();
953
+
954
+ const state = {
955
+ workflowName: opts.name || 'Apra Fleet Workflow',
956
+ status: 'running',
957
+ // apra-fleet-eft.2.2: fields enriching the persisted state file
958
+ // beyond the terminal-only crash-net snapshot -- populated (where
959
+ // known) from construction, and updated as the run progresses so
960
+ // a mid-run read of the file shows in-progress state, not just
961
+ // the terminal shape.
962
+ runId,
963
+ // apra-fleet-x8r.10: launchArgs is opaque, free-form, per-workflow
964
+ // metadata (NOT argv). Core never inspects or interprets it; consumers
965
+ // must feature-detect the fields they need rather than assuming a type.
966
+ // Examples: argv array from test callers (['--track', 'eft-service'],
967
+ // ['--foo', 'bar']), or a structured object from fleet-sprint
968
+ // ({ members, targetIssues, goal }).
969
+ args: opts.launchArgs ?? null,
970
+ // apra-fleet-eft.37.3: `result` is the workflow script's own return
971
+ // value, stored WHOLESALE and OPAQUELY -- core never inspects or
972
+ // mints individual keys inside it (that used to be `verdict`/`prUrl`,
973
+ // auto-sprint domain concepts that have no business in the generic
974
+ // engine). Null until the run ends; see the 'end' handler below and
975
+ // the generic Result-strip renderer in HTML_TEMPLATE's client script.
976
+ result: null,
977
+ terminalReason: null,
978
+ startedAt: startedAtIso,
979
+ updatedAt: startedAtIso,
980
+ endedAt: null,
981
+ stats: {
982
+ activitiesCount: 0,
983
+ totalTokens: 0,
984
+ totalCost: 0,
985
+ // apra-fleet-unw.4: count of completed activities whose usage/
986
+ // cost could not be determined (fleet result lacked usage, or
987
+ // calculateCost() couldn't price the model). These are excluded
988
+ // from totalCost/totalTokens rather than fabricated.
989
+ unknownCostCount: 0,
990
+ startTime: Date.now(),
991
+ durationMs: 0
992
+ },
993
+ tree: [],
994
+ extensions: {}
995
+ };
996
+
997
+ // Note: group/phase tracking is single-run by design (single-tenant usage).
998
+ let currentGroup = { title: 'Workflow', phases: [] };
999
+ // apra-fleet-eft.53.1: every phase entry is stamped with phaseStartedAt on
1000
+ // entry and phaseEndedAt (initially null) on exit, so the dashboard can
1001
+ // render a live elapsed-time tick for the in-progress phase and a frozen
1002
+ // duration for exited ones (apra-fleet-eft.53.2). Both fields live
1003
+ // directly on the plain phase object pushed into state.tree, so they are
1004
+ // written to disk unchanged by the existing debounced/terminal
1005
+ // persistence paths (debounced-writer.mjs / persistState() below) and
1006
+ // survive a reload/History-view replay for free -- no separate
1007
+ // persistence wiring needed.
1008
+ let currentPhase = { title: 'Initialization', phaseStartedAt: startedAtIso, phaseEndedAt: null, events: [] };
1009
+ currentGroup.phases.push(currentPhase);
1010
+ state.tree.push(currentGroup);
1011
+
1012
+ const clients = new Set();
1013
+ const broadcast = (data) => {
1014
+ const msg = `data: ${JSON.stringify(data)}\n\n`;
1015
+ clients.forEach(c => c.write(msg));
1016
+ // apra-fleet-eft.2.2: every event that already drives the SSE
1017
+ // broadcast (group:start, phase, activity:start/end, log, state)
1018
+ // also schedules a debounced state write and bumps updatedAt, so a
1019
+ // mid-run read of the persisted file reflects in-progress state
1020
+ // rather than only the terminal snapshot.
1021
+ state.updatedAt = nowIso();
1022
+ debouncedWriter.schedule();
1023
+ };
1024
+
1025
+ // apra-fleet-eft.2.1/2.3: debounced writer, additive to persistState()
1026
+ // above -- that write-once-on-end path (the terminal snapshot dir's
1027
+ // run_<HHMMSS>.json) stays exactly as-is as the child crash-safety net.
1028
+ // This one coalesces bursts of rapid state changes into a single write
1029
+ // per debounce window (default DEFAULT_DEBOUNCE_MS, configurable via
1030
+ // opts.debounceMs, must be within 200-500ms), is flushed synchronously
1031
+ // on every exit path below, and (apra-fleet-eft.2.3) targets
1032
+ // running/<runId>.json under the service data directory by default --
1033
+ // never the repo checkout.
1034
+ const debouncedWriter = new DebouncedStateWriter({
1035
+ getState: () => state,
1036
+ filePath: runningStatePath,
1037
+ debounceMs: opts.debounceMs || DEFAULT_DEBOUNCE_MS
1038
+ });
1039
+
1040
+ // apra-fleet-eft.27.4: configurable head/tail cap applied to a `command`
1041
+ // activity's captured output/error BEFORE it's ever stored into
1042
+ // state.tree (command-output-cap.mjs) -- undefined fields fall back to
1043
+ // that module's own defaults.
1044
+ const commandOutputCapOpts = {
1045
+ headChars: opts.commandOutputHeadChars,
1046
+ tailChars: opts.commandOutputTailChars
1047
+ };
1048
+
1049
+ // apra-fleet-eft.2.3: on terminal completion, move (not copy) the live
1050
+ // running/<runId>.json to old_runs/<runId>.json so "is this run live" is a
1051
+ // directory-membership check, never a stale field on the state object
1052
+ // itself. Only applies to the default path layout -- see
1053
+ // usingDefaultStatePath above.
1054
+ function moveStateToOldRuns() {
1055
+ if (!usingDefaultStatePath) return;
1056
+ try {
1057
+ if (!fs.existsSync(runningStatePath)) return;
1058
+ const oldPath = getTerminalRunStatePath(runId, env);
1059
+ fs.mkdirSync(path.dirname(oldPath), { recursive: true });
1060
+ fs.renameSync(runningStatePath, oldPath);
1061
+ } catch (e) {
1062
+ // Must never crash or block the run's own normal exit behavior --
1063
+ // log and move on, same contract as persistState() and the
1064
+ // debounced writer itself.
1065
+ console.warn(`[Viewer] Warning: failed to move run state to old_runs/: ${e.message}`);
1066
+ }
1067
+ }
1068
+
1069
+ // Server-side persistence of the dashboard `state` object to
1070
+ // <stateSnapshotDir>/<stateSnapshotPrefix><HHMMSS>.json on every
1071
+ // run-ending event (normal finish, cooperative /stop-triggered
1072
+ // cancellation, or the CLI process itself being interrupted). This is the
1073
+ // server-side equivalent of the client-side saveState() button
1074
+ // (HTML_TEMPLATE above) -- that one only works if a human has the
1075
+ // dashboard open in a browser; this one runs unconditionally so a run's
1076
+ // final state is never lost just because nobody was watching. `saved`
1077
+ // guards against writing twice for the same run (e.g. 'end' fires, then a
1078
+ // SIGINT arrives moments later during the bin/cli.mjs failure grace-period
1079
+ // wait).
1080
+ //
1081
+ // apra-fleet-eft.37.1: the crash-net snapshot location is configurable so
1082
+ // core stays domain-neutral -- opts.stateSnapshotDir (default
1083
+ // `workflow-logs`, resolved under process.cwd() when relative) and
1084
+ // opts.stateSnapshotPrefix (default `run_`, giving `run_<HHMMSS>.json`).
1085
+ // auto-sprint passes `sprint-logs`/`sprint_` explicitly so its user-facing
1086
+ // convention is unchanged.
1087
+ const stateSnapshotDir = opts.stateSnapshotDir || 'workflow-logs';
1088
+ const stateSnapshotPrefix = opts.stateSnapshotPrefix || 'run_';
1089
+ let saved = false;
1090
+ function persistState() {
1091
+ if (saved) return;
1092
+ saved = true;
1093
+ try {
1094
+ const dir = path.isAbsolute(stateSnapshotDir)
1095
+ ? stateSnapshotDir
1096
+ : path.join(process.cwd(), stateSnapshotDir);
1097
+ const now = new Date();
1098
+ const pad2 = (n) => String(n).padStart(2, '0');
1099
+ const hhmmss = `${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}`;
1100
+ const filePath = path.join(dir, `${stateSnapshotPrefix}${hhmmss}.json`);
1101
+ // apra-fleet-eft.20.1: route through the same single-pass
1102
+ // JSON.stringify + atomic temp-file-then-rename primitive the
1103
+ // debounced writer uses (writeJsonFileAtomic, debounced-writer.mjs)
1104
+ // instead of a direct writeFileSync, so this terminal snapshot can
1105
+ // never be observed half-written and its bytes always round-trip
1106
+ // through JSON.parse().
1107
+ writeJsonFileAtomic(filePath, state);
1108
+ console.log(`[Viewer] Run state saved to ${filePath}`);
1109
+ } catch (e) {
1110
+ // A failed save must never crash or block the run's own normal
1111
+ // exit behavior -- log and move on.
1112
+ console.warn(`[Viewer] Warning: failed to save run state: ${e.message}`);
1113
+ }
1114
+ }
1115
+
1116
+ // Covers reason 3 (CLI process interrupted): SIGINT/SIGTERM had NO
1117
+ // handler at all today for a still-running or successfully-finished
1118
+ // run (bin/cli.mjs only registers a SIGINT handler inside its
1119
+ // failure-grace-window Promise). Registering a listener here removes
1120
+ // Node's default immediate-exit behavior for the signal, so the handler
1121
+ // must explicitly call process.exit() itself after the best-effort save
1122
+ // to preserve that same "the process ultimately terminates" contract --
1123
+ // it does not swallow the signal or turn it into a no-op.
1124
+ // NOTE: signal listeners registered via process.on('SIGINT'/'SIGTERM', fn)
1125
+ // do NOT receive the signal name as an argument (unlike a manually
1126
+ // dispatched process.emit(name, ...args)), so a single shared handler
1127
+ // can't tell them apart -- hence two small wrappers instead of one
1128
+ // handler branching on an argument that would never actually arrive.
1129
+ const handleSigint = () => {
1130
+ // apra-fleet-eft.53.1: same close-out as the normal 'end' path -- a
1131
+ // SIGINT-interrupted run must not leave its final phase's
1132
+ // phaseEndedAt dangling null in the persisted snapshot.
1133
+ if (currentPhase && currentPhase.phaseEndedAt == null) {
1134
+ currentPhase.phaseEndedAt = nowIso();
1135
+ }
1136
+ state.endedAt = nowIso();
1137
+ state.terminalReason = state.terminalReason || 'SIGINT';
1138
+ persistState();
1139
+ // apra-fleet-eft.2.1: flush any coalesced-but-not-yet-written
1140
+ // debounced state synchronously before the process actually exits,
1141
+ // so at most one debounce window of progress is ever lost.
1142
+ debouncedWriter.flushSync();
1143
+ // apra-fleet-eft.2.3: SIGINT/SIGTERM are a graceful (not hard-kill)
1144
+ // shutdown path, so the file is still moved to old_runs/ here --
1145
+ // it's only an unhandled SIGKILL/OOM that leaves it behind in
1146
+ // running/ (that gap is what apra-fleet-eft.2.4's hard-kill test
1147
+ // covers).
1148
+ moveStateToOldRuns();
1149
+ process.exit(130);
1150
+ };
1151
+ const handleSigterm = () => {
1152
+ // apra-fleet-eft.53.1: see handleSigint's identical stamp above.
1153
+ if (currentPhase && currentPhase.phaseEndedAt == null) {
1154
+ currentPhase.phaseEndedAt = nowIso();
1155
+ }
1156
+ state.endedAt = nowIso();
1157
+ state.terminalReason = state.terminalReason || 'SIGTERM';
1158
+ persistState();
1159
+ debouncedWriter.flushSync();
1160
+ moveStateToOldRuns();
1161
+ process.exit(143);
1162
+ };
1163
+ process.on('SIGINT', handleSigint);
1164
+ process.on('SIGTERM', handleSigterm);
1165
+
1166
+ workflow.on('group:start', (data) => {
1167
+ currentGroup = { title: data.title, phases: [] };
1168
+ state.tree.push(currentGroup);
1169
+ broadcast({ type: 'update' });
1170
+ });
1171
+
1172
+ workflow.on('phase', (title) => {
1173
+ // apra-fleet-eft.53.1: stamp phaseEndedAt on the phase being exited
1174
+ // (guarded so an already-ended phase -- e.g. one closed by the 'end'
1175
+ // handler below -- is never overwritten) before starting the new one.
1176
+ if (currentPhase && currentPhase.phaseEndedAt == null) {
1177
+ currentPhase.phaseEndedAt = nowIso();
1178
+ }
1179
+ currentPhase = { title, phaseStartedAt: nowIso(), phaseEndedAt: null, events: [] };
1180
+ if (!currentGroup) {
1181
+ currentGroup = { title: 'Workflow', phases: [] };
1182
+ state.tree.push(currentGroup);
1183
+ }
1184
+ currentGroup.phases.push(currentPhase);
1185
+ broadcast({ type: 'update' });
1186
+ });
1187
+
1188
+ workflow.on('activity:start', (meta) => {
1189
+ state.stats.activitiesCount++;
1190
+ currentPhase.events.push({ type: 'activity', id: meta.id, data: { ...meta, isRunning: true } });
1191
+ broadcast({ type: 'update' });
1192
+ });
1193
+
1194
+ workflow.on('activity:end', (meta) => {
1195
+ // apra-fleet-eft.27.4: cap a `command` activity's output/error to a
1196
+ // head+tail excerpt + byte count BEFORE it lands in state.tree --
1197
+ // this is the object persisted (debounced running/<runId>.json,
1198
+ // terminal snapshot) and read by GET /state's
1199
+ // buildListStatePayload() transform, so an uncapped multi-MB command
1200
+ // dump written here bloats all three regardless of that transform.
1201
+ // Returns the SAME `meta` reference unchanged when there's nothing
1202
+ // to cap (non-command activities, or output already under the cap),
1203
+ // and never mutates the original `meta` object -- other
1204
+ // `activity:end` listeners (e.g. journal.mjs's replay cache) still
1205
+ // need the complete, uncapped text.
1206
+ const storedMeta = capCommandActivityMeta(meta, commandOutputCapOpts);
1207
+ for (const g of state.tree) {
1208
+ for (const p of g.phases) {
1209
+ const ev = p.events.find(e => e.type === 'activity' && e.id === meta.id);
1210
+ if (ev) {
1211
+ ev.data = { ...ev.data, ...storedMeta, isRunning: false };
1212
+ }
1213
+ }
1214
+ }
1215
+ if (meta.usage?.total_tokens) state.stats.totalTokens += meta.usage.total_tokens;
1216
+ // apra-fleet-unw.4: `cost` is only added to the running total when
1217
+ // it's a known number. When agent() explicitly reported cost: null
1218
+ // (fleet result had no usage, or the model wasn't in the pricing
1219
+ // table), tally it separately instead of fabricating a total.
1220
+ if (typeof meta.cost === 'number') {
1221
+ state.stats.totalCost += meta.cost;
1222
+ } else if (meta.type === 'agent' && Object.prototype.hasOwnProperty.call(meta, 'cost') && meta.cost === null) {
1223
+ state.stats.unknownCostCount++;
1224
+ }
1225
+ broadcast({ type: 'update' });
1226
+ });
1227
+
1228
+ workflow.on('log', (entry) => {
1229
+ currentPhase.events.push({ type: 'log', time: entry.time || Date.now(), msg: entry.msg });
1230
+ broadcast({ type: 'update' });
1231
+ });
1232
+
1233
+ workflow.on('state', (stateData) => {
1234
+ state.extensions[stateData.namespace] = stateData.data;
1235
+ broadcast({ type: 'state', payload: stateData });
1236
+ });
1237
+
1238
+ workflow.on('end', (res) => {
1239
+ // apra-fleet-eft.53.1: the run's final phase never gets a 'phase'
1240
+ // event to close it out -- stamp its phaseEndedAt here so no phase
1241
+ // entry is left with a dangling null once the run has actually
1242
+ // ended.
1243
+ if (currentPhase && currentPhase.phaseEndedAt == null) {
1244
+ currentPhase.phaseEndedAt = nowIso();
1245
+ }
1246
+ state.status = res.status;
1247
+ state.stats.durationMs = Date.now() - state.stats.startTime;
1248
+ // apra-fleet-eft.2.2/eft.37.3: enrich the terminal state with
1249
+ // whatever the workflow script's own return value surfaced --
1250
+ // stored WHOLESALE and opaquely as `state.result` (core never reads
1251
+ // or names individual keys inside it; a non-se workflow may return
1252
+ // anything JSON-shaped here, or nothing at all).
1253
+ state.result = (res.result !== undefined) ? res.result : state.result;
1254
+ state.endedAt = nowIso();
1255
+ state.terminalReason = res.error
1256
+ ? (res.error.message || res.error.name || res.status)
1257
+ : res.status;
1258
+ broadcast({ type: 'update' });
1259
+ persistState();
1260
+ // apra-fleet-eft.2.1: synchronous flush-on-exit -- a run ending is
1261
+ // one of the process-exit-adjacent paths this writer must never
1262
+ // lose more than one debounce window against.
1263
+ debouncedWriter.flushSync();
1264
+ // apra-fleet-eft.2.3: terminal completion -- move running/<id>.json
1265
+ // to old_runs/<id>.json (directory membership, not a stale field,
1266
+ // is what makes "is this run live" authoritative).
1267
+ moveStateToOldRuns();
1268
+ });
1269
+
1270
+ const server = http.createServer((req, res) => {
1271
+ if (req.url === '/') {
1272
+ res.writeHead(200, { 'Content-Type': 'text/html' });
1273
+ res.end(HTML_TEMPLATE(dashboardExtensions));
1274
+ } else if (req.url === '/events') {
1275
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Connection': 'keep-alive', 'Cache-Control': 'no-cache' });
1276
+ clients.add(res);
1277
+ req.on('close', () => clients.delete(res));
1278
+ } else if (req.url.startsWith('/state')) {
1279
+ // apra-fleet-eft.27.1: GET /state is the RECURRING poll endpoint
1280
+ // (every ~250ms-400ms while a run is live) -- it must never
1281
+ // serve the full in-memory `state` object as-is. That object
1282
+ // accumulates one entry per activity for the run's entire
1283
+ // history, and each entry can embed multi-KB command/agent
1284
+ // output; on a real 449-activity sprint this endpoint measured a
1285
+ // 116 MB payload per poll (apra-fleet-eft.27). buildListStatePayload()
1286
+ // (src/viewer/lean-state.mjs) strips descriptions/transcripts
1287
+ // down to short summaries and dedupes any remaining repeated
1288
+ // strings -- `state` itself (the source of truth persisted to
1289
+ // the configured snapshot dir and running/<runId>.json, and what
1290
+ // the process-free History view embeds) is never mutated by this.
1291
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate' });
1292
+ res.end(JSON.stringify(buildListStatePayload(state)));
1293
+ } else if (req.method === 'GET' && /^\/extensions\/[^/]+\/detail\/[^/]+$/.test(req.url)) {
1294
+ // apra-fleet-eft.37.4 (M3): the GENERIC on-demand-detail route.
1295
+ // Any dashboard extension may register a `detailLookup(state, id)`
1296
+ // hook; this is the only route that calls it, and it is
1297
+ // extension-agnostic -- core never names a specific extension or
1298
+ // reaches into its data shape. Fetched only when a user expands
1299
+ // an on-demand row in SOME extension's UI (e.g. the beads
1300
+ // extension's "more..." control, apra-fleet-eft.27) -- never
1301
+ // during normal polling -- against the LIVE, full-fidelity
1302
+ // `state` object (never the leaned /state projection).
1303
+ const match = req.url.match(/^\/extensions\/([^/]+)\/detail\/([^/]+)$/);
1304
+ const extId = decodeURIComponent(match[1]);
1305
+ const itemId = decodeURIComponent(match[2]);
1306
+ const ext = dashboardExtensions.find((e) => e.id === extId);
1307
+ const detail = (ext && typeof ext.detailLookup === 'function')
1308
+ ? ext.detailLookup(state, itemId)
1309
+ : null;
1310
+ if (!detail) {
1311
+ res.writeHead(404, { 'Content-Type': 'application/json' });
1312
+ res.end(JSON.stringify({ error: 'detail not found', id: itemId }));
1313
+ return;
1314
+ }
1315
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
1316
+ res.end(JSON.stringify({
1317
+ id: itemId,
1318
+ text: detail.text || '',
1319
+ updatedAt: detail.updatedAt ?? null
1320
+ }));
1321
+ } else if (req.method === 'GET' && /^\/beads\/[^/]+\/description$/.test(req.url)) {
1322
+ // BOUNDARY-COMPAT (apra-fleet-eft.37.4, one release only, then
1323
+ // dies per docs/workflow-core-boundary-refactoring.md M3): the
1324
+ // pre-M3 route name. The extension js that used to call it
1325
+ // (packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs) has
1326
+ // already moved to the generic route above; this alias exists
1327
+ // only for anything still pointed at the old URL (e.g. a stale
1328
+ // cached client). A dumb redirect, not a second implementation --
1329
+ // it never touches `state` itself.
1330
+ const id = req.url.slice('/beads/'.length, req.url.length - '/description'.length);
1331
+ res.writeHead(302, { Location: '/extensions/beads/detail/' + id });
1332
+ res.end();
1333
+ } else if (req.method === 'GET' && /^\/activities\/[^/]+\/output$/.test(req.url)) {
1334
+ // apra-fleet-eft.27.4 / apra-fleet-eft.38 (reopened): on-demand
1335
+ // full-output endpoint. First checks command-output-cap.mjs's
1336
+ // dedicated store (a `command` activity whose stdout/error was
1337
+ // capped to a head+tail excerpt before being stored in state.tree
1338
+ // -- see the activity:end handler above). Every OTHER activity
1339
+ // type that GET /state's lean-state.mjs may have marked
1340
+ // <field>Truncated (most notably `agent`: its full LLM response
1341
+ // text is never capped at storage time, so it's never in that
1342
+ // store) falls back to the LIVE, full-fidelity in-memory
1343
+ // state.tree instead, via findActivityById() -- that object still
1344
+ // holds the complete, uncapped text for anything not routed
1345
+ // through command-output-cap.mjs. Fetched only when a user
1346
+ // expands a truncated activity in the dashboard -- never during
1347
+ // normal polling. 404s (not a crash) for an unknown id, or one
1348
+ // with nothing to fetch beyond what's already inline.
1349
+ const id = decodeURIComponent(req.url.slice('/activities/'.length, req.url.length - '/output'.length));
1350
+ let full = getFullOutput(id);
1351
+ if (!full) {
1352
+ const act = findActivityById(state, id);
1353
+ if (act) {
1354
+ const fromState = {};
1355
+ if (typeof act.output === 'string') fromState.output = act.output;
1356
+ if (typeof act.error === 'string') fromState.error = act.error;
1357
+ if (Object.keys(fromState).length > 0) full = fromState;
1358
+ }
1359
+ }
1360
+ if (!full) {
1361
+ res.writeHead(404, { 'Content-Type': 'application/json' });
1362
+ res.end(JSON.stringify({ error: 'activity output not found', id }));
1363
+ return;
1364
+ }
1365
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
1366
+ res.end(JSON.stringify({ id, ...full }));
1367
+ } else if (req.url === '/stop' && req.method === 'POST') {
1368
+ // (apra-fleet-unw.10) Cooperative stop -- no process.exit(). The
1369
+ // old handler killed the whole Node process immediately, with no
1370
+ // state flush and any mid-dispatch agent() /command() call left
1371
+ // orphaned (its promise simply never settles because the process
1372
+ // is gone). Instead, ask the workflow to cancel itself: this
1373
+ // aborts the active run's AbortController (FleetWorkflow
1374
+ // .requestStop(), src/workflow/index.mjs), which rejects every
1375
+ // in-flight and future agent()/command() dispatch for that run
1376
+ // via the apra-fleet-unw.5 client-side signal plumbing with a
1377
+ // typed CancelledError. The run then unwinds normally and
1378
+ // WorkflowEngine.executeFile() emits 'end' with status
1379
+ // 'cancelled' from its own finally block, same as any other
1380
+ // failure path -- the viewer transitions to CANCELLED/FAILED and
1381
+ // closes after the usual grace period, and the Node process
1382
+ // stays alive throughout.
1383
+ //
1384
+ // NOTE: this is local/client-side cancellation only. A remote
1385
+ // fleet member that already accepted a job may keep running to
1386
+ // completion even after this run unwinds as cancelled --
1387
+ // true server-side cancellation would require changes to the
1388
+ // external apra-fleet MCP server (apra-fleet.exe) and is out of
1389
+ // scope here.
1390
+ console.log('[Viewer] Stop signal received -- requesting cooperative cancellation.');
1391
+ if (typeof workflow.requestStop === 'function') {
1392
+ workflow.requestStop('Stop requested via dashboard /stop endpoint');
1393
+ }
1394
+ // apra-fleet-eft.2.1: /stop is one of the required flush-on-exit
1395
+ // paths -- the workflow itself unwinds asynchronously afterward
1396
+ // (and its own 'end' handler above will flush again once it
1397
+ // fires), but flush eagerly here too so the debounced state
1398
+ // file reflects the stop request itself without waiting on that
1399
+ // unwind.
1400
+ debouncedWriter.flushSync();
1401
+ res.writeHead(200);
1402
+ res.end();
1403
+ } else if (req.url === '/save_logs' && req.method === 'POST') {
1404
+ // Manual/scriptable trigger for the same server-side save that
1405
+ // 'end' and SIGINT/SIGTERM already perform (persistState() above)
1406
+ // -- e.g. a future dashboard button, curl, or another tool. Shares
1407
+ // the same idempotency guard (`saved`), so this is a no-op if the
1408
+ // run has already been persisted (by 'end', a signal, or a prior
1409
+ // call to this endpoint).
1410
+ console.log('[Viewer] /save_logs requested -- persisting current dashboard state.');
1411
+ persistState();
1412
+ res.writeHead(200);
1413
+ res.end();
1414
+ } else {
1415
+ res.writeHead(404);
1416
+ res.end();
1417
+ }
1418
+ });
1419
+
1420
+ server.listen(port, () => {
1421
+ console.log(`[Viewer] Workflow Dashboard live at http://localhost:${server.address().port}`);
1422
+ });
1423
+
1424
+ workflow.on('end', () => {
1425
+ setTimeout(() => {
1426
+ try { server.close(); } catch(e) {}
1427
+ }, 5000);
1428
+ });
1429
+
1430
+ // Avoid leaking process-level signal listeners: each createDashboardViewer()
1431
+ // call (one per test, one per real workflow run) adds its own SIGINT/SIGTERM
1432
+ // handler above; remove it once this viewer's server is done.
1433
+ server.on('close', () => {
1434
+ process.removeListener('SIGINT', handleSigint);
1435
+ process.removeListener('SIGTERM', handleSigterm);
1436
+ });
1437
+
1438
+ return server;
1439
+ }