@cortex-agent/server 2026.5.25 → 2026.6.11

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 (355) hide show
  1. package/defaults/config/thread-templates.json +28 -1
  2. package/defaults/hooks/cortex-md-injector.mjs +47 -31
  3. package/defaults/hooks/post-task-hook.mjs +6 -0
  4. package/defaults/hooks/task-status-check.mjs +8 -0
  5. package/defaults/mcp-config-slack.json +11 -0
  6. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +18 -0
  7. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +5 -6
  8. package/defaults/prompts/directives/manager.md +67 -0
  9. package/dist/agent-adapter/claude/adapter-tui.d.ts +35 -3
  10. package/dist/agent-adapter/claude/adapter-tui.js +91 -12
  11. package/dist/agent-adapter/claude/adapter.js +11 -0
  12. package/dist/agent-adapter/claude/defaults.d.ts +30 -0
  13. package/dist/agent-adapter/claude/defaults.js +30 -0
  14. package/dist/agent-adapter/claude/jsonl-tail.d.ts +2 -2
  15. package/dist/agent-adapter/claude/jsonl-tail.js +25 -20
  16. package/dist/agent-adapter/claude/spawn-args.d.ts +11 -0
  17. package/dist/agent-adapter/claude/spawn-args.js +49 -7
  18. package/dist/agent-adapter/claude/tmux-control.d.ts +20 -0
  19. package/dist/agent-adapter/claude/tmux-control.js +54 -8
  20. package/dist/agent-adapter/codex/adapter.js +1 -1
  21. package/dist/agent-adapter/normalize/event-types.d.ts +1 -0
  22. package/dist/agent-adapter/pi/adapter.js +46 -19
  23. package/dist/agent-adapter/pi/agent-dir.d.ts +21 -0
  24. package/dist/agent-adapter/pi/agent-dir.js +53 -2
  25. package/dist/agent-adapter/pi/event-parser.js +13 -1
  26. package/dist/agent-adapter/pi/mcp-bridge.d.ts +12 -0
  27. package/dist/agent-adapter/pi/mcp-bridge.js +47 -9
  28. package/dist/agent-adapter/pi/tool-shims.d.ts +14 -0
  29. package/dist/agent-adapter/pi/tool-shims.js +167 -140
  30. package/dist/agent-adapter/types.d.ts +7 -2
  31. package/dist/core/atomic-write.js +21 -0
  32. package/dist/core/config-generator.d.ts +10 -0
  33. package/dist/core/config-generator.js +28 -0
  34. package/dist/core/gateway-generator.d.ts +77 -7
  35. package/dist/core/gateway-generator.js +301 -29
  36. package/dist/core/icons.d.ts +68 -0
  37. package/dist/core/icons.js +67 -0
  38. package/dist/core/profile-generator.d.ts +6 -0
  39. package/dist/core/profile-generator.js +35 -7
  40. package/dist/core/running-executions.d.ts +51 -41
  41. package/dist/core/running-executions.js +120 -73
  42. package/dist/core/status-format.js +3 -2
  43. package/dist/core/task-parser.d.ts +3 -0
  44. package/dist/core/task-parser.js +3 -1
  45. package/dist/core/types/thread-types.d.ts +54 -8
  46. package/dist/domain/agents/facade.d.ts +18 -0
  47. package/dist/domain/agents/facade.js +26 -3
  48. package/dist/domain/agents/profile-manager.d.ts +11 -0
  49. package/dist/domain/agents/profile-manager.js +21 -2
  50. package/dist/domain/costs/codex-usage-monitor.js +2 -1
  51. package/dist/domain/costs/rate-limit-throttle.js +14 -2
  52. package/dist/domain/executions/registry.d.ts +24 -0
  53. package/dist/domain/executions/registry.js +38 -0
  54. package/dist/domain/mcp/core-server.js +15 -3
  55. package/dist/domain/mcp/feishu/bitable.d.ts +3 -0
  56. package/dist/domain/mcp/feishu/bitable.js +168 -0
  57. package/dist/domain/mcp/feishu/block-types.d.ts +44 -0
  58. package/dist/domain/mcp/feishu/block-types.js +127 -0
  59. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +19 -0
  60. package/dist/domain/mcp/feishu/blocks-to-text.js +43 -0
  61. package/dist/domain/mcp/feishu/client.d.ts +46 -0
  62. package/dist/domain/mcp/feishu/client.js +87 -0
  63. package/dist/domain/mcp/feishu/docx.d.ts +3 -0
  64. package/dist/domain/mcp/feishu/docx.js +163 -0
  65. package/dist/domain/mcp/feishu/drive.d.ts +23 -0
  66. package/dist/domain/mcp/feishu/drive.js +66 -0
  67. package/dist/domain/mcp/feishu/file.d.ts +14 -0
  68. package/dist/domain/mcp/feishu/file.js +107 -0
  69. package/dist/domain/mcp/feishu/index.d.ts +6 -0
  70. package/dist/domain/mcp/feishu/index.js +61 -0
  71. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +40 -0
  72. package/dist/domain/mcp/feishu/markdown-to-blocks.js +191 -0
  73. package/dist/domain/mcp/feishu/sheets.d.ts +3 -0
  74. package/dist/domain/mcp/feishu/sheets.js +119 -0
  75. package/dist/domain/mcp/feishu/types.d.ts +26 -0
  76. package/dist/domain/mcp/feishu/types.js +38 -0
  77. package/dist/domain/mcp/feishu/user-auth.d.ts +140 -0
  78. package/dist/domain/mcp/feishu/user-auth.js +286 -0
  79. package/dist/domain/mcp/feishu/wiki.d.ts +3 -0
  80. package/dist/domain/mcp/feishu/wiki.js +77 -0
  81. package/dist/domain/mcp/feishu-server.d.ts +2 -0
  82. package/dist/domain/mcp/feishu-server.js +33 -0
  83. package/dist/domain/mcp/server.d.ts +0 -1
  84. package/dist/domain/mcp/server.js +6 -25
  85. package/dist/domain/mcp/slack-server.d.ts +3 -0
  86. package/dist/domain/mcp/slack-server.js +46 -0
  87. package/dist/domain/mcp/tools/context.js +1 -1
  88. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  89. package/dist/domain/mcp/tools/schedule.js +6 -20
  90. package/dist/domain/mcp/tools/slack.js +20 -7
  91. package/dist/domain/mcp/tools/thread-ops.d.ts +2 -0
  92. package/dist/domain/mcp/tools/thread-ops.js +121 -0
  93. package/dist/domain/mcp/tools/time.d.ts +2 -0
  94. package/dist/domain/mcp/tools/time.js +66 -0
  95. package/dist/domain/mcp/tools/tui-ask.js +1 -1
  96. package/dist/domain/mcp/tools/tui-plan.js +2 -2
  97. package/dist/domain/mcp/tui-server.js +1 -0
  98. package/dist/domain/monitor/disk-monitor.js +2 -1
  99. package/dist/domain/monitor/gpu-monitor.js +2 -1
  100. package/dist/domain/remote/client-hot-reload.js +3 -2
  101. package/dist/domain/remote/client-manager.js +8 -6
  102. package/dist/domain/scheduling/job-registry.d.ts +4 -0
  103. package/dist/domain/scheduling/job-registry.js +1 -0
  104. package/dist/domain/scheduling/jobs/_shared.js +2 -1
  105. package/dist/domain/scheduling/jobs/memory-index-regen.js +3 -2
  106. package/dist/domain/scheduling/jobs/scheduled-task.js +9 -23
  107. package/dist/domain/scheduling/jobs/sync-public.js +4 -3
  108. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +1 -8
  109. package/dist/domain/scheduling/jobs/target-dispatch.js +0 -7
  110. package/dist/domain/scheduling/jobs/task-archive.js +3 -2
  111. package/dist/domain/scheduling/jobs/task-dispatch.js +120 -10
  112. package/dist/domain/scheduling/schedule-command.js +16 -15
  113. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  114. package/dist/domain/scheduling/scheduler.js +2 -1
  115. package/dist/domain/sessions/session-hooks.d.ts +2 -2
  116. package/dist/domain/sessions/session-hooks.js +19 -18
  117. package/dist/domain/sessions/session-lifecycle.d.ts +38 -0
  118. package/dist/domain/sessions/session-lifecycle.js +44 -0
  119. package/dist/domain/system/install-cli.d.ts +7 -0
  120. package/dist/domain/system/install-cli.js +106 -0
  121. package/dist/domain/system/server-update-check.js +2 -2
  122. package/dist/domain/tasks/dispatch-utils.d.ts +58 -1
  123. package/dist/domain/tasks/dispatch-utils.js +53 -4
  124. package/dist/domain/tasks/dispatcher.js +26 -0
  125. package/dist/domain/tasks/lint.js +28 -0
  126. package/dist/domain/tasks/mutator.d.ts +16 -3
  127. package/dist/domain/tasks/mutator.js +41 -12
  128. package/dist/domain/tasks/pending-tracker.js +6 -5
  129. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  130. package/dist/domain/tasks/system/task-cli.js +37 -6
  131. package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
  132. package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
  133. package/dist/domain/tasks/system/task-mutations.js +166 -8
  134. package/dist/domain/threads/contract.d.ts +17 -0
  135. package/dist/domain/threads/contract.js +59 -0
  136. package/dist/domain/threads/hook-runner.js +7 -6
  137. package/dist/domain/threads/index.d.ts +2 -0
  138. package/dist/domain/threads/index.js +3 -1
  139. package/dist/domain/threads/prompt-builder.d.ts +15 -1
  140. package/dist/domain/threads/prompt-builder.js +41 -2
  141. package/dist/domain/threads/runner.d.ts +6 -5
  142. package/dist/domain/threads/runner.js +128 -79
  143. package/dist/domain/threads/state-machine.d.ts +23 -21
  144. package/dist/domain/threads/state-machine.js +113 -54
  145. package/dist/domain/threads/template-loader.js +3 -2
  146. package/dist/domain/threads/tree.d.ts +45 -0
  147. package/dist/domain/threads/tree.js +171 -0
  148. package/dist/domain/tui-session/index.d.ts +2 -0
  149. package/dist/domain/tui-session/index.js +3 -0
  150. package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
  151. package/dist/domain/tui-session/tui-session-service.js +103 -0
  152. package/dist/domain/tui-session/types.d.ts +67 -0
  153. package/dist/domain/tui-session/types.js +4 -0
  154. package/dist/domain/ui-service/index.d.ts +5 -0
  155. package/dist/domain/ui-service/index.js +3 -0
  156. package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
  157. package/dist/domain/ui-service/mutate/executions.js +15 -0
  158. package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
  159. package/dist/domain/ui-service/mutate/schedules.js +39 -0
  160. package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
  161. package/dist/domain/ui-service/mutate/tasks.js +59 -0
  162. package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
  163. package/dist/domain/ui-service/mutate/threads.js +21 -0
  164. package/dist/domain/ui-service/query/cost.d.ts +3 -0
  165. package/dist/domain/ui-service/query/cost.js +6 -0
  166. package/dist/domain/ui-service/query/executions.d.ts +2 -0
  167. package/dist/domain/ui-service/query/executions.js +35 -0
  168. package/dist/domain/ui-service/query/projects.d.ts +2 -0
  169. package/dist/domain/ui-service/query/projects.js +30 -0
  170. package/dist/domain/ui-service/query/schedules.d.ts +2 -0
  171. package/dist/domain/ui-service/query/schedules.js +23 -0
  172. package/dist/domain/ui-service/query/sessions.d.ts +2 -0
  173. package/dist/domain/ui-service/query/sessions.js +35 -0
  174. package/dist/domain/ui-service/query/tasks.d.ts +2 -0
  175. package/dist/domain/ui-service/query/tasks.js +30 -0
  176. package/dist/domain/ui-service/query/threads.d.ts +2 -0
  177. package/dist/domain/ui-service/query/threads.js +27 -0
  178. package/dist/domain/ui-service/subscribe.d.ts +5 -0
  179. package/dist/domain/ui-service/subscribe.js +118 -0
  180. package/dist/domain/ui-service/types.d.ts +237 -0
  181. package/dist/domain/ui-service/types.js +5 -0
  182. package/dist/domain/ui-service/ui-service.d.ts +2 -0
  183. package/dist/domain/ui-service/ui-service.js +83 -0
  184. package/dist/entry/app.js +94 -5
  185. package/dist/entry/cli.d.ts +12 -0
  186. package/dist/entry/cli.js +122 -12
  187. package/dist/entry/feishu-login.d.ts +28 -0
  188. package/dist/entry/feishu-login.js +218 -0
  189. package/dist/entry/init.d.ts +25 -2
  190. package/dist/entry/init.js +211 -64
  191. package/dist/events/event-types.d.ts +14 -0
  192. package/dist/hooks/cortex-md-injector.mjs +47 -31
  193. package/dist/hooks/post-task-hook.mjs +6 -0
  194. package/dist/hooks/task-status-check.mjs +8 -0
  195. package/dist/orchestration/agent-runner.d.ts +2 -1
  196. package/dist/orchestration/agent-runner.js +55 -55
  197. package/dist/orchestration/conduit-queue.d.ts +18 -0
  198. package/dist/orchestration/conduit-queue.js +32 -0
  199. package/dist/orchestration/conversation-runner.d.ts +48 -0
  200. package/dist/orchestration/conversation-runner.js +109 -0
  201. package/dist/orchestration/dispatch-reconciler.js +8 -1
  202. package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
  203. package/dist/orchestration/interactions/ask-user-question.js +3 -3
  204. package/dist/orchestration/interactions/interaction-handlers.js +48 -17
  205. package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
  206. package/dist/orchestration/interactions/plan-handler.js +4 -3
  207. package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
  208. package/dist/orchestration/interactions/update-prompt.js +100 -0
  209. package/dist/orchestration/lifecycle.d.ts +4 -4
  210. package/dist/orchestration/lifecycle.js +24 -22
  211. package/dist/orchestration/orchestrator.d.ts +1 -1
  212. package/dist/orchestration/routing/commands/cancel.js +39 -47
  213. package/dist/orchestration/routing/commands/channel.js +24 -11
  214. package/dist/orchestration/routing/commands/cost.js +2 -1
  215. package/dist/orchestration/routing/commands/device.js +3 -2
  216. package/dist/orchestration/routing/commands/dispatch.js +6 -5
  217. package/dist/orchestration/routing/commands/index.d.ts +1 -1
  218. package/dist/orchestration/routing/commands/index.js +11 -10
  219. package/dist/orchestration/routing/commands/mode.js +19 -18
  220. package/dist/orchestration/routing/commands/nvtop.js +10 -9
  221. package/dist/orchestration/routing/commands/sendfile.js +7 -6
  222. package/dist/orchestration/routing/commands/session.d.ts +1 -1
  223. package/dist/orchestration/routing/commands/session.js +17 -33
  224. package/dist/orchestration/routing/commands/tail.js +4 -3
  225. package/dist/orchestration/routing/commands/task.js +4 -3
  226. package/dist/orchestration/routing/commands/thread-handlers.js +16 -6
  227. package/dist/orchestration/routing/edit-handler.js +8 -7
  228. package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
  229. package/dist/orchestration/routing/message-router.d.ts +1 -1
  230. package/dist/orchestration/routing/message-router.js +9 -9
  231. package/dist/orchestration/routing/webhook.js +233 -2
  232. package/dist/orchestration/status-helpers.d.ts +5 -1
  233. package/dist/orchestration/status-helpers.js +7 -6
  234. package/dist/orchestration/thread-callback.d.ts +67 -0
  235. package/dist/orchestration/thread-callback.js +465 -0
  236. package/dist/orchestration/thread-executor.d.ts +22 -1
  237. package/dist/orchestration/thread-executor.js +85 -36
  238. package/dist/platform/adapter.d.ts +6 -2
  239. package/dist/platform/adapters/composite-adapter.d.ts +89 -0
  240. package/dist/platform/adapters/composite-adapter.js +318 -0
  241. package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
  242. package/dist/platform/adapters/feishu-output-stream.js +274 -36
  243. package/dist/platform/adapters/feishu.d.ts +50 -5
  244. package/dist/platform/adapters/feishu.js +370 -116
  245. package/dist/platform/adapters/index.d.ts +24 -3
  246. package/dist/platform/adapters/index.js +89 -11
  247. package/dist/platform/adapters/project-conduits.d.ts +9 -0
  248. package/dist/platform/adapters/project-conduits.js +42 -0
  249. package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
  250. package/dist/platform/adapters/slack-project-conduits.js +6 -40
  251. package/dist/platform/adapters/slack.d.ts +9 -2
  252. package/dist/platform/adapters/slack.js +83 -39
  253. package/dist/platform/adapters/tui/index.d.ts +9 -0
  254. package/dist/platform/adapters/tui/index.js +10 -0
  255. package/dist/platform/adapters/tui/ports.d.ts +20 -0
  256. package/dist/platform/adapters/tui/ports.js +4 -0
  257. package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
  258. package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
  259. package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
  260. package/dist/platform/adapters/tui/tui-connection.js +53 -0
  261. package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
  262. package/dist/platform/adapters/tui/tui-gateway.js +919 -0
  263. package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
  264. package/dist/platform/adapters/tui/tui-notifications.js +60 -0
  265. package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
  266. package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
  267. package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
  268. package/dist/platform/adapters/tui/tui-transcript.js +56 -0
  269. package/dist/platform/index.d.ts +1 -0
  270. package/dist/platform/index.js +2 -1
  271. package/dist/platform/interactive-builder.js +3 -2
  272. package/dist/platform/output-stream.d.ts +5 -0
  273. package/dist/platform/testing.d.ts +7 -11
  274. package/dist/platform/testing.js +18 -15
  275. package/dist/platform/tool-trace.js +15 -5
  276. package/dist/platform/tui/protocol.d.ts +355 -0
  277. package/dist/platform/tui/protocol.js +199 -0
  278. package/dist/platform/types.d.ts +12 -3
  279. package/dist/store/execution-repo.d.ts +6 -1
  280. package/dist/store/execution-repo.js +13 -3
  281. package/dist/store/hook-sync.d.ts +18 -0
  282. package/dist/store/hook-sync.js +92 -0
  283. package/dist/store/outbound-queue.js +2 -2
  284. package/dist/store/profile-repo.js +3 -2
  285. package/dist/store/schedule-repo.d.ts +1 -8
  286. package/dist/store/session-registry-repo.d.ts +9 -1
  287. package/dist/store/session-registry-repo.js +19 -3
  288. package/dist/store/session-repo.d.ts +14 -0
  289. package/dist/store/session-repo.js +23 -0
  290. package/dist/store/thread-repo.d.ts +3 -0
  291. package/dist/store/thread-repo.js +49 -2
  292. package/dist/store/version-migrations.js +95 -0
  293. package/dist/tui/App.d.ts +27 -0
  294. package/dist/tui/App.js +219 -0
  295. package/dist/tui/components/AskUserModal.d.ts +11 -0
  296. package/dist/tui/components/AskUserModal.js +364 -0
  297. package/dist/tui/components/ConfirmModal.d.ts +12 -0
  298. package/dist/tui/components/ConfirmModal.js +31 -0
  299. package/dist/tui/components/Dashboard.d.ts +23 -0
  300. package/dist/tui/components/Dashboard.js +80 -0
  301. package/dist/tui/components/DashboardCostTab.d.ts +7 -0
  302. package/dist/tui/components/DashboardCostTab.js +16 -0
  303. package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
  304. package/dist/tui/components/DashboardExecutionsTab.js +94 -0
  305. package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
  306. package/dist/tui/components/DashboardSchedulesTab.js +124 -0
  307. package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
  308. package/dist/tui/components/DashboardTasksTab.js +200 -0
  309. package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
  310. package/dist/tui/components/DashboardThreadsTab.js +81 -0
  311. package/dist/tui/components/Header.d.ts +11 -0
  312. package/dist/tui/components/Header.js +5 -0
  313. package/dist/tui/components/InputBox.d.ts +10 -0
  314. package/dist/tui/components/InputBox.js +19 -0
  315. package/dist/tui/components/MessageRow.d.ts +7 -0
  316. package/dist/tui/components/MessageRow.js +10 -0
  317. package/dist/tui/components/Notifications.d.ts +19 -0
  318. package/dist/tui/components/Notifications.js +72 -0
  319. package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
  320. package/dist/tui/components/PlanFeedbackModal.js +161 -0
  321. package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
  322. package/dist/tui/components/ProjectSwitcher.js +43 -0
  323. package/dist/tui/components/SessionPicker.d.ts +14 -0
  324. package/dist/tui/components/SessionPicker.js +34 -0
  325. package/dist/tui/components/SidePanel.d.ts +19 -0
  326. package/dist/tui/components/SidePanel.js +8 -0
  327. package/dist/tui/components/StatusLine.d.ts +10 -0
  328. package/dist/tui/components/StatusLine.js +29 -0
  329. package/dist/tui/components/Transcript.d.ts +13 -0
  330. package/dist/tui/components/Transcript.js +56 -0
  331. package/dist/tui/hooks/useDashboardData.d.ts +32 -0
  332. package/dist/tui/hooks/useDashboardData.js +104 -0
  333. package/dist/tui/hooks/useKeybindings.d.ts +19 -0
  334. package/dist/tui/hooks/useKeybindings.js +87 -0
  335. package/dist/tui/hooks/useMutate.d.ts +22 -0
  336. package/dist/tui/hooks/useMutate.js +56 -0
  337. package/dist/tui/hooks/useNotifications.d.ts +28 -0
  338. package/dist/tui/hooks/useNotifications.js +70 -0
  339. package/dist/tui/hooks/useTranscript.d.ts +39 -0
  340. package/dist/tui/hooks/useTranscript.js +265 -0
  341. package/dist/tui/hooks/useWsClient.d.ts +29 -0
  342. package/dist/tui/hooks/useWsClient.js +69 -0
  343. package/dist/tui/index.d.ts +2 -0
  344. package/dist/tui/index.js +210 -0
  345. package/dist/tui/logic.d.ts +16 -0
  346. package/dist/tui/logic.js +49 -0
  347. package/dist/tui/render/markdown.d.ts +10 -0
  348. package/dist/tui/render/markdown.js +38 -0
  349. package/dist/tui/render/rich-blocks.d.ts +11 -0
  350. package/dist/tui/render/rich-blocks.js +24 -0
  351. package/dist/tui/ws-client.d.ts +44 -0
  352. package/dist/tui/ws-client.js +157 -0
  353. package/package.json +11 -3
  354. package/dist/orchestration/channel-queue.d.ts +0 -18
  355. package/dist/orchestration/channel-queue.js +0 -32
@@ -3,11 +3,27 @@ import { approveTask as lifecycleApproveTask, blockTask as lifecycleBlockTask, c
3
3
  import { completeTask as lifecycleCompleteTask, uncompleteTask as lifecycleUncompleteTask, } from './system/task-completion.js';
4
4
  import { addTask as lifecycleAddTask, batchEdit as lifecycleBatchEdit, decomposeTask as lifecycleDecomposeTask, } from './system/task-mutations.js';
5
5
  import { editTask as lifecycleEditTask } from './system/task-lifecycle-edit.js';
6
- import { assertLockHeld, getOwnerIdentity } from './system/task-lock.js';
6
+ import { assertLockHeld, getOwnerIdentity, isProjectLocked } from './system/task-lock.js';
7
7
  export class TaskMutator {
8
8
  store;
9
- constructor(store = taskStore) {
9
+ bus;
10
+ constructor(store = taskStore, bus) {
10
11
  this.store = store;
12
+ this.bus = bus;
13
+ }
14
+ setBus(bus) {
15
+ this.bus = bus;
16
+ }
17
+ /** getById with a one-shot refresh on miss: tasks created out-of-process (CLI, manager
18
+ * threads) reach the in-memory cache only on refresh — callers like the cortex-run
19
+ * callback may fire before any dispatch cycle has reloaded TASKS.yaml. */
20
+ getByIdFresh(taskId) {
21
+ let task = this.store.getById(taskId);
22
+ if (!task) {
23
+ this.store.refresh();
24
+ task = this.store.getById(taskId);
25
+ }
26
+ return task;
11
27
  }
12
28
  async claim(taskId, agent) {
13
29
  return this.store.runExclusive(() => {
@@ -18,6 +34,7 @@ export class TaskMutator {
18
34
  if (result.success) {
19
35
  this.store.refresh();
20
36
  this.store.commitAndPush(`task-store: claim ${taskId} by ${agent}`);
37
+ this.bus?.publish({ type: 'task.claimed', taskId, by: agent });
21
38
  }
22
39
  return result;
23
40
  });
@@ -35,15 +52,16 @@ export class TaskMutator {
35
52
  return result;
36
53
  });
37
54
  }
38
- async complete(taskId, note) {
55
+ async complete(taskId, note, options = {}) {
39
56
  return this.store.runExclusive(() => {
40
- const task = this.store.getById(taskId);
57
+ const task = this.getByIdFresh(taskId);
41
58
  if (!task)
42
59
  return { success: false, message: `Task not found: ${taskId}` };
43
- const result = lifecycleCompleteTask(task.text, task.project, note || '', taskId);
60
+ const result = lifecycleCompleteTask(task.text, task.project, note || '', taskId, options.skipVerify ?? false, options.skipVerifyReason ?? null);
44
61
  if (result.success) {
45
62
  this.store.refresh();
46
63
  this.store.commitAndPush(`task-store: complete ${taskId}`);
64
+ this.bus?.publish({ type: 'task.completed', taskId });
47
65
  }
48
66
  return result;
49
67
  });
@@ -63,13 +81,15 @@ export class TaskMutator {
63
81
  }
64
82
  async block(taskId, reason) {
65
83
  return this.store.runExclusive(() => {
66
- const task = this.store.getById(taskId);
84
+ const task = this.getByIdFresh(taskId);
67
85
  if (!task)
68
86
  return { success: false, message: `Task not found: ${taskId}` };
69
87
  const result = lifecycleBlockTask(task.text, task.project, reason, taskId);
70
88
  if (result.success) {
71
89
  this.store.refresh();
72
90
  this.store.commitAndPush(`task-store: block ${taskId}`);
91
+ // DR-0014 §8: a blocked task is a child's escalation — wake its waiting manager.
92
+ this.bus?.publish({ type: 'task.blocked', taskId, reason });
73
93
  }
74
94
  return result;
75
95
  });
@@ -191,15 +211,24 @@ export class TaskMutator {
191
211
  return result;
192
212
  });
193
213
  }
194
- async decompose(project, taskText, subtasks, taskId) {
214
+ async decompose(project, taskText, subtasks, taskId, options = {}) {
195
215
  return this.store.runExclusive(() => {
196
- const lockError = assertLockHeld(project, getOwnerIdentity());
197
- if (lockError)
198
- return { success: false, message: lockError };
199
- const result = lifecycleDecomposeTask(project, taskText, subtasks, taskId || null);
216
+ if (options.system) {
217
+ // System-initiated decompose ([SPLIT] dispatch path, DR-0014): no agent holds the
218
+ // lock here — proceed unless a FOREIGN lock exists (defer to the lock holder).
219
+ const l = isProjectLocked(project);
220
+ if (l.locked)
221
+ return { success: false, message: `Project lock held by ${l.owner} — split deferred` };
222
+ }
223
+ else {
224
+ const lockError = assertLockHeld(project, getOwnerIdentity());
225
+ if (lockError)
226
+ return { success: false, message: lockError };
227
+ }
228
+ const result = lifecycleDecomposeTask(project, taskText, subtasks, taskId || null, { keepParent: options.keepParent });
200
229
  if (result.success) {
201
230
  this.store.refresh();
202
- this.store.commitAndPush(`task-store: decompose task in ${project}`);
231
+ this.store.commitAndPush(`task-store: decompose task in ${project}${options.keepParent ? ' (keep-parent)' : ''}`);
203
232
  }
204
233
  return result;
205
234
  });
@@ -5,6 +5,7 @@
5
5
  import { readFileSync, writeFileSync } from 'fs';
6
6
  import * as path from 'path';
7
7
  import { STORE_DIR, formatDurationCompact } from '../../core/utils.js';
8
+ import { Icons } from '../../core/icons.js';
8
9
  import { createLogger } from '../../core/log.js';
9
10
  import * as executionRegistry from '../executions/registry.js';
10
11
  const log = createLogger('pending-task-tracker');
@@ -32,7 +33,7 @@ if (pendingTasks.size > 0) {
32
33
  // --- Message builders ---
33
34
  function buildTrackingMetaParts({ startedAtMs, elapsed_s }) {
34
35
  const elapsed = elapsed_s ?? ((Date.now() - startedAtMs) / 1000);
35
- return `:stopwatch: ${formatDurationCompact(elapsed || 0)}`;
36
+ return `${Icons.stopwatch} ${formatDurationCompact(elapsed || 0)}`;
36
37
  }
37
38
  function buildTrackingMessage({ taskId, machine, taskText, startedAtMs, elapsed_s, turn_count, status, cost_usd, duration_s, num_turns, finalOutput }) {
38
39
  const label = taskText ? `${taskText}` : `Task ${taskId}`;
@@ -40,15 +41,15 @@ function buildTrackingMessage({ taskId, machine, taskText, startedAtMs, elapsed_
40
41
  const dur = formatDurationCompact(duration_s || elapsed_s || 0);
41
42
  const costStr = cost_usd != null ? ` | $${cost_usd.toFixed(4)}` : '';
42
43
  const outputStr = finalOutput ? `\n\n${finalOutput}` : '';
43
- return `:white_check_mark: *[${taskId}]* ${label}\nCompleted on ${machine} | :stopwatch: ${dur} | ${num_turns || turn_count || '?'} turns${costStr}${outputStr}`;
44
+ return `${Icons.ok} *[${taskId}]* ${label}\nCompleted on ${machine} | ${Icons.stopwatch} ${dur} | ${num_turns || turn_count || '?'} turns${costStr}${outputStr}`;
44
45
  }
45
46
  if (status === 'failed') {
46
47
  const dur = formatDurationCompact(duration_s || elapsed_s || 0);
47
48
  const costStr = cost_usd != null ? ` | $${cost_usd.toFixed(4)}` : '';
48
49
  const outputStr = finalOutput ? `\n\n${finalOutput}` : '';
49
- return `:x: *[${taskId}]* ${label}\nFailed on ${machine} | :stopwatch: ${dur} | ${num_turns || turn_count || '?'} turns${costStr}${outputStr}`;
50
+ return `${Icons.error} *[${taskId}]* ${label}\nFailed on ${machine} | ${Icons.stopwatch} ${dur} | ${num_turns || turn_count || '?'} turns${costStr}${outputStr}`;
50
51
  }
51
- return `:satellite: *[${taskId}]* ${label}\nRunning on ${machine} | ${buildTrackingMetaParts({ startedAtMs, elapsed_s })}`;
52
+ return `${Icons.satellite} *[${taskId}]* ${label}\nRunning on ${machine} | ${buildTrackingMetaParts({ startedAtMs, elapsed_s })}`;
52
53
  }
53
54
  // --- Public API ---
54
55
  function init(adapter) {
@@ -112,7 +113,7 @@ function handleTaskProgress({ task_id, machine, cost_usd, turn_count, elapsed_s
112
113
  const text = buildTrackingMessage({ taskId: task_id, machine: machine || t.machine, taskText: t.taskText, startedAtMs: t.launchedAt, elapsed_s, turn_count, cost_usd, status: 'running' });
113
114
  (async () => {
114
115
  try {
115
- await _adapter.updateMessage({ channel: channel, messageId: t.trackingTs }, { text });
116
+ await _adapter.updateMessage({ conduit: channel, messageId: t.trackingTs }, { text });
116
117
  }
117
118
  catch (e) {
118
119
  log.error(`Failed to update tracking for ${task_id}:`, e.message);
@@ -17,11 +17,13 @@ interface ParsedValues {
17
17
  clearDependsOn: boolean;
18
18
  taskIds: string[];
19
19
  subtasksFile: string | null;
20
+ bulkFile: string | null;
20
21
  status: string | null;
21
22
  hasDeps: boolean;
22
23
  noDeps: boolean;
23
24
  json: boolean;
24
25
  dryRun: boolean;
26
+ keepParent: boolean;
25
27
  skipVerify: boolean;
26
28
  skipVerifyReason: string | null;
27
29
  force: boolean;
@@ -11,7 +11,7 @@ import { editTask } from './task-lifecycle-edit.js';
11
11
  import { assignIds, validateIds } from './task-id-utils.js';
12
12
  import { approveTask, blockTask, claimTask, clearApprovalTask, pauseTask, pendingTask, requestApprovalTask, resumeTask, unblockTask, unclaimTask, } from './task-state.js';
13
13
  import { completeTask, uncompleteTask } from './task-completion.js';
14
- import { addTask, batchEdit, decomposeTask } from './task-mutations.js';
14
+ import { addTask, batchEdit, bulkAddTasks, decomposeTask } from './task-mutations.js';
15
15
  import { stopTask, stopTaskDryRun } from './task-process.js';
16
16
  import { acquireLock, assertLockHeld, getOwnerIdentity, readLock, releaseLock, } from './task-lock.js';
17
17
  const READ_COMMANDS = new Set(['list', 'all', 'query', 'show', 'deps', 'lint', 'stats', 'tree']);
@@ -19,7 +19,7 @@ const WRITE_COMMANDS = new Set([
19
19
  'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
20
20
  'request-approval', 'approve', 'clear-approval',
21
21
  'block', 'unblock',
22
- 'add', 'edit', 'batch-edit', 'decompose',
22
+ 'add', 'edit', 'batch-edit', 'bulk-add', 'decompose',
23
23
  'assign-ids', 'validate', 'stop',
24
24
  'lock-acquire', 'lock-release', 'lock-status', 'lock-force-release',
25
25
  ]);
@@ -35,7 +35,7 @@ const COMMANDS_NEEDING_PROJECT = new Set([
35
35
  'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
36
36
  'request-approval', 'approve', 'clear-approval',
37
37
  'block', 'unblock',
38
- 'add', 'edit', 'batch-edit', 'decompose',
38
+ 'add', 'edit', 'batch-edit', 'bulk-add', 'decompose',
39
39
  'lock-acquire', 'lock-release', 'lock-force-release',
40
40
  ]);
41
41
  const COMMON_FLAGS = new Set(['--base-dir', '--project', '--task-id']);
@@ -69,7 +69,8 @@ const COMMAND_FLAG_ALLOWLIST = {
69
69
  ...COMMON_FLAGS, '--task-ids', '--text', '--why', '--done-when', '--plan', '--priority',
70
70
  '--depends-on', '--add-depends-on', '--remove-depends-on', '--clear-depends-on', '--auto-lock',
71
71
  ]),
72
- decompose: new Set([...COMMON_FLAGS, '--task', '--subtasks-file', '--dry-run', '--auto-lock']),
72
+ decompose: new Set([...COMMON_FLAGS, '--task', '--subtasks-file', '--dry-run', '--auto-lock', '--keep-parent']),
73
+ 'bulk-add': new Set([...COMMON_FLAGS, '--file', '--auto-lock']),
73
74
  'assign-ids': new Set([...COMMON_FLAGS, '--auto-lock']),
74
75
  validate: new Set([...COMMON_FLAGS]),
75
76
  stop: new Set([...COMMON_FLAGS, '--dry-run']),
@@ -126,6 +127,7 @@ const HELP_CONFIG = {
126
127
  heading: 'Mutation',
127
128
  commands: [
128
129
  { name: 'add', description: 'Add new task (--text, --why, --done-when, --plan, --template ...)' },
130
+ { name: 'bulk-add', description: 'Bulk-add tasks from JSON file (--file, use "key" for intra-batch deps)' },
129
131
  { name: 'edit', description: 'Edit task fields (--text, --why, --done-when, ...)' },
130
132
  { name: 'batch-edit', description: 'Apply same edit to multiple tasks (--task-ids)' },
131
133
  { name: 'decompose', description: 'Replace task with subtasks (--subtasks-file)' },
@@ -168,6 +170,7 @@ const HELP_CONFIG = {
168
170
  { flag: '--remove-depends-on <id>', description: 'Remove a dependency (edit only, repeatable)' },
169
171
  { flag: '--clear-depends-on', description: 'Clear all dependencies (edit only)' },
170
172
  { flag: '--subtasks-file <path>', description: 'JSON file with subtasks (decompose; use - for stdin)' },
173
+ { flag: '--file <path>', description: 'JSON file of tasks (bulk-add; use - for stdin)' },
171
174
  { flag: '--status <status>', description: 'Filter by status (read commands)' },
172
175
  { flag: '--has-deps', description: 'Read-only: tasks with dependencies' },
173
176
  { flag: '--no-deps', description: 'Read-only: tasks without dependencies' },
@@ -176,6 +179,7 @@ const HELP_CONFIG = {
176
179
  { flag: '--json', description: 'Output as JSON (read commands)' },
177
180
  { flag: '--base-dir <path>', description: 'Cortex root directory', default: '~/Cortex' },
178
181
  { flag: '--dry-run', description: 'Preview without executing (stop, decompose)' },
182
+ { flag: '--keep-parent', description: 'decompose: keep the original task as a join/acceptance node depending on all subtasks (DR-0014 task tree)' },
179
183
  { flag: '--auto-lock', description: 'Auto-acquire project lock before write (does NOT auto-release)' },
180
184
  { flag: '--skip-verify', description: 'Skip completion evidence check for `complete` (escape hatch)' },
181
185
  { flag: '--skip-verify-reason <text>', description: 'Reason for skipping verification (logged in result)' },
@@ -207,6 +211,7 @@ const STRING_OPT_KEYS = {
207
211
  '--priority': 'priority',
208
212
  '--template': 'template',
209
213
  '--subtasks-file': 'subtasksFile',
214
+ '--file': 'bulkFile',
210
215
  '--status': 'status',
211
216
  '--skip-verify-reason': 'skipVerifyReason',
212
217
  };
@@ -221,6 +226,7 @@ const VALUE_OPTIONS = new Set([
221
226
  ...Object.keys(STRING_OPT_KEYS),
222
227
  ...Object.keys(APPEND_OPT_KEYS),
223
228
  '--task-ids',
229
+ '--file',
224
230
  ]);
225
231
  function getCliHelp() {
226
232
  return formatHelp(HELP_CONFIG);
@@ -245,11 +251,13 @@ function createDefaults() {
245
251
  clearDependsOn: false,
246
252
  taskIds: [],
247
253
  subtasksFile: null,
254
+ bulkFile: null,
248
255
  status: null,
249
256
  hasDeps: false,
250
257
  noDeps: false,
251
258
  json: false,
252
259
  dryRun: false,
260
+ keepParent: false,
253
261
  skipVerify: false,
254
262
  skipVerifyReason: null,
255
263
  force: false,
@@ -328,6 +336,10 @@ function parseOptions(args, values, seen) {
328
336
  seen.add(token);
329
337
  values.dryRun = true;
330
338
  }
339
+ else if (token === '--keep-parent') {
340
+ seen.add(token);
341
+ values.keepParent = true;
342
+ }
331
343
  else if (token === '--skip-verify') {
332
344
  seen.add(token);
333
345
  values.skipVerify = true;
@@ -387,6 +399,12 @@ function validateCommand(command, values) {
387
399
  if (command === 'add' && !values.text) {
388
400
  throw cliError('--text is required for add');
389
401
  }
402
+ if (command === 'add' && values.template && (values.template === 'default' || values.template === 'scheduler')) {
403
+ throw cliError(`Template '${values.template}' is forbidden. The 'default' and 'scheduler' templates are single-agent templates with no review pipeline and are not allowed for task dispatch. Use a multi-agent review template instead (run 'cortex-task --help' to see available templates).`);
404
+ }
405
+ if (command === 'bulk-add' && !values.bulkFile) {
406
+ throw cliError('--file is required for bulk-add (use - for stdin)');
407
+ }
390
408
  if (COMMANDS_NEEDING_PROJECT.has(command) && !values.project) {
391
409
  throw cliError('--project is required');
392
410
  }
@@ -612,7 +630,7 @@ function handleDecompose(v) {
612
630
  if (v.dryRun) {
613
631
  return { success: true, dry_run: true, message: `Would decompose task into ${subtasks.length} subtasks`, subtasks_preview: subtasks };
614
632
  }
615
- return decomposeTask(v.project, v.task, subtasks, v.taskId);
633
+ return decomposeTask(v.project, v.task, subtasks, v.taskId, { keepParent: v.keepParent });
616
634
  }
617
635
  function handleStop(v) {
618
636
  return v.dryRun ? stopTaskDryRun(v.taskId) : stopTask(v.taskId);
@@ -692,6 +710,19 @@ const WRITE_HANDLERS = {
692
710
  edit: handleEdit,
693
711
  'batch-edit': handleBatchEdit,
694
712
  decompose: handleDecompose,
713
+ 'bulk-add': (v) => {
714
+ const content = v.bulkFile === '-'
715
+ ? readStdinSync()
716
+ : fs.readFileSync(v.bulkFile, 'utf8');
717
+ let inputs;
718
+ try {
719
+ inputs = JSON.parse(content);
720
+ }
721
+ catch (e) {
722
+ return { success: false, message: `Failed to parse JSON input: ${e.message || e}` };
723
+ }
724
+ return bulkAddTasks(v.project, inputs);
725
+ },
695
726
  stop: handleStop,
696
727
  'assign-ids': (v) => assignIds(v.project),
697
728
  validate: () => validateIds(),
@@ -700,7 +731,7 @@ const WRITE_HANDLERS = {
700
731
  'lock-status': handleLockStatus,
701
732
  'lock-force-release': handleLockForceRelease,
702
733
  };
703
- const LOCK_GUARD_COMMANDS = new Set(['add', 'edit', 'batch-edit', 'decompose']);
734
+ const LOCK_GUARD_COMMANDS = new Set(['add', 'edit', 'batch-edit', 'bulk-add', 'decompose']);
704
735
  const LOCK_GUARD_ASSIGN_IDS = 'assign-ids';
705
736
  function runWrite(command, values) {
706
737
  if (command === 'lock-status') {
@@ -46,6 +46,7 @@ function ensureSwept(tasksPath) {
46
46
  // ── Template validation ──
47
47
  const VALID_PRIORITIES = new Set(['high', 'medium', 'low']);
48
48
  let cachedTemplateNames = null;
49
+ const FORBIDDEN_TEMPLATES = new Set(['default', 'scheduler']);
49
50
  function getValidTemplateNames() {
50
51
  if (cachedTemplateNames !== null)
51
52
  return cachedTemplateNames;
@@ -53,13 +54,17 @@ function getValidTemplateNames() {
53
54
  loadConfig();
54
55
  }
55
56
  catch { /* suppress loadConfig output */ }
56
- cachedTemplateNames = new Set(listTemplateNames());
57
+ const allNames = listTemplateNames();
58
+ cachedTemplateNames = new Set(allNames.filter((n) => !FORBIDDEN_TEMPLATES.has(n)));
57
59
  return cachedTemplateNames;
58
60
  }
59
61
  function _resetTemplateNameCacheForTests() {
60
62
  cachedTemplateNames = null;
61
63
  }
62
64
  function validateTemplateName(name) {
65
+ if (FORBIDDEN_TEMPLATES.has(name)) {
66
+ return `Template '${name}' is forbidden. The 'default' and 'scheduler' templates are single-agent templates with no review pipeline and are not allowed for task dispatch. Use a multi-agent review template instead (e.g. stage-gate, coder-review, analyst-review).`;
67
+ }
63
68
  const valid = getValidTemplateNames();
64
69
  if (valid.size === 0)
65
70
  return null;
@@ -1,3 +1,15 @@
1
+ interface BulkTaskInput {
2
+ key: string;
3
+ text: string;
4
+ why?: string;
5
+ 'done-when'?: string;
6
+ priority?: string;
7
+ template?: string;
8
+ plan?: string;
9
+ 'depends-on'?: string[];
10
+ gpu?: string;
11
+ 'gpu-count'?: number;
12
+ }
1
13
  declare function addTask(project: string, text: string | null, why: string | null, doneWhen: string | null, priority?: string, template?: string | null, dependsOn?: string[] | null, plan?: string | null): {
2
14
  success: boolean;
3
15
  message: string;
@@ -16,16 +28,42 @@ declare function batchEdit(project: string, taskIds: string[], options?: any): {
16
28
  message: string;
17
29
  }[];
18
30
  };
19
- declare function decomposeTask(project: string, originalText: string | null, subtasks: Array<{
31
+ /** Subtask input for decomposeTask. Accepts both kebab and snake key styles
32
+ * ([SPLIT] proposals are agent-written JSON; be liberal in what we accept). */
33
+ interface DecomposeSubtaskInput {
34
+ key?: string;
20
35
  text: string;
21
36
  template?: string;
22
37
  why?: string;
23
38
  done_when?: string;
39
+ 'done-when'?: string;
24
40
  priority?: string;
25
41
  plan?: string;
26
42
  depends_on?: string[];
27
- }>, taskId?: string | null): {
43
+ 'depends-on'?: string[];
44
+ }
45
+ declare function decomposeTask(project: string, originalText: string | null, subtasks: DecomposeSubtaskInput[], taskId?: string | null, options?: {
46
+ keepParent?: boolean;
47
+ }): {
48
+ success: boolean;
49
+ message: string;
50
+ child_ids?: undefined;
51
+ } | {
28
52
  success: boolean;
29
53
  message: string;
54
+ child_ids: string[];
55
+ };
56
+ declare function bulkAddTasks(project: string, inputs: BulkTaskInput[]): {
57
+ success: boolean;
58
+ message: string;
59
+ created?: undefined;
60
+ } | {
61
+ success: boolean;
62
+ message: string;
63
+ created: {
64
+ key: string;
65
+ id: string;
66
+ text: string;
67
+ }[];
30
68
  };
31
- export { addTask, batchEdit, decomposeTask };
69
+ export { addTask, batchEdit, bulkAddTasks, decomposeTask };
@@ -1,6 +1,6 @@
1
1
  import * as fs from 'node:fs';
2
2
  import { collectAllExistingHashes, generateHash } from './task-id-utils.js';
3
- import { editTask, findTask, getTasksPath, readTasks, validateTemplateName, writeTasks } from './task-lifecycle-edit.js';
3
+ import { editTask, findTask, getTasksPath, readTasks, VALID_PRIORITIES, validateTemplateName, writeTasks } from './task-lifecycle-edit.js';
4
4
  function addTask(project, text, why, doneWhen, priority = 'medium', template = null, dependsOn = null, plan = null) {
5
5
  if (!text || text === 'null') {
6
6
  return { success: false, message: '--text is required and must not be empty' };
@@ -31,6 +31,7 @@ function addTask(project, text, why, doneWhen, priority = 'medium', template = n
31
31
  template,
32
32
  plan: plan?.trim() || '',
33
33
  project,
34
+ parent: null,
34
35
  depends_on: dependsOnList,
35
36
  gpu: null,
36
37
  gpu_count: 1,
@@ -63,7 +64,9 @@ function batchEdit(project, taskIds, options = {}) {
63
64
  }
64
65
  return { success: failed.length === 0, message, results };
65
66
  }
66
- function decomposeTask(project, originalText, subtasks, taskId = null) {
67
+ const HEX_ID_RE = /^[0-9a-fA-F]{4}$/;
68
+ function decomposeTask(project, originalText, subtasks, taskId = null, options = {}) {
69
+ const keepParent = !!options.keepParent;
67
70
  const tasks = readTasks(project);
68
71
  if (tasks.length === 0 && !fs.existsSync(getTasksPath(project))) {
69
72
  return { success: false, message: `TASKS.yaml not found for project ${project}` };
@@ -73,22 +76,46 @@ function decomposeTask(project, originalText, subtasks, taskId = null) {
73
76
  return { success: false, message: found.error };
74
77
  const parentIndex = found.index;
75
78
  const parentTask = found.task;
79
+ // First pass: ids for every subtask, keyed for sibling dependency resolution.
76
80
  const existingHashes = collectAllExistingHashes();
77
- const newTasks = [];
81
+ const keyToId = new Map();
82
+ const ids = [];
78
83
  for (const sub of subtasks) {
79
84
  const hash = generateHash(existingHashes);
80
85
  existingHashes.add(hash);
86
+ ids.push(hash);
87
+ if (sub.key)
88
+ keyToId.set(sub.key.trim(), hash);
89
+ }
90
+ // Second pass: build tasks, resolving depends-on entries (sibling key | existing hex id).
91
+ const newTasks = [];
92
+ for (let i = 0; i < subtasks.length; i++) {
93
+ const sub = subtasks[i];
94
+ const rawDeps = sub.depends_on ?? sub['depends-on'] ?? [];
95
+ const resolvedDeps = [];
96
+ for (const rawDep of rawDeps) {
97
+ const dep = String(rawDep).trim();
98
+ if (keyToId.has(dep))
99
+ resolvedDeps.push(keyToId.get(dep));
100
+ else if (HEX_ID_RE.test(dep))
101
+ resolvedDeps.push(dep);
102
+ else
103
+ return { success: false, message: `subtask[${i}]: unknown dependency "${dep}" — not a sibling key and not a 4-char hex id` };
104
+ }
81
105
  newTasks.push({
82
- id: hash,
106
+ id: ids[i],
83
107
  text: sub.text,
84
108
  why: sub.why || '',
85
- done_when: sub.done_when || '',
109
+ done_when: sub.done_when ?? sub['done-when'] ?? '',
86
110
  priority: (sub.priority || 'medium'),
87
111
  status: 'open',
88
112
  template: sub.template || parentTask.template,
89
113
  plan: (sub.plan?.trim()) || parentTask.plan,
90
114
  project,
91
- depends_on: sub.depends_on || [],
115
+ // keepParent: children hang under the retained parent. Replace mode: children
116
+ // inherit the grandparent so the tree stays connected (DR-0014).
117
+ parent: keepParent ? parentTask.id : (parentTask.parent ?? null),
118
+ depends_on: resolvedDeps,
92
119
  gpu: null,
93
120
  gpu_count: 1,
94
121
  blocked_by: null,
@@ -103,8 +130,139 @@ function decomposeTask(project, originalText, subtasks, taskId = null) {
103
130
  pending_at: null,
104
131
  });
105
132
  }
133
+ if (keepParent) {
134
+ // Parent becomes the join/acceptance node: it stays in place and depends on all
135
+ // children — getActionable keeps it dormant until every child is done, and
136
+ // clearDependsOnAll unlocks it child by child. Zero new dispatch machinery.
137
+ tasks.splice(parentIndex + 1, 0, ...newTasks);
138
+ parentTask.depends_on = [...new Set([...parentTask.depends_on, ...ids])];
139
+ writeTasks(project, tasks);
140
+ return { success: true, message: `Task decomposed into ${subtasks.length} subtasks (parent ${parentTask.id} kept as join node)`, child_ids: ids };
141
+ }
106
142
  tasks.splice(parentIndex, 1, ...newTasks);
107
143
  writeTasks(project, tasks);
108
- return { success: true, message: `Task decomposed into ${subtasks.length} subtasks` };
144
+ return { success: true, message: `Task decomposed into ${subtasks.length} subtasks`, child_ids: ids };
145
+ }
146
+ function bulkAddTasks(project, inputs) {
147
+ // 1. Validate inputs array
148
+ if (!Array.isArray(inputs) || inputs.length === 0) {
149
+ return { success: false, message: 'Input must be a non-empty JSON array of tasks' };
150
+ }
151
+ const tasksPath = getTasksPath(project);
152
+ if (!fs.existsSync(tasksPath)) {
153
+ return { success: false, message: `TASKS.yaml not found for project ${project}` };
154
+ }
155
+ // 2. Validate each input
156
+ const seenKeys = new Set();
157
+ const VALID_PRIORITY_VALUES = VALID_PRIORITIES; // Set from task-lifecycle-edit
158
+ for (let i = 0; i < inputs.length; i++) {
159
+ const inp = inputs[i];
160
+ const idx = `[${i}]`;
161
+ if (!inp.key || typeof inp.key !== 'string' || inp.key.trim() === '') {
162
+ return { success: false, message: `${idx}: "key" is required and must be a non-empty string` };
163
+ }
164
+ const key = inp.key.trim();
165
+ if (seenKeys.has(key)) {
166
+ return { success: false, message: `${idx}: duplicate key "${key}" — keys must be unique within the batch` };
167
+ }
168
+ seenKeys.add(key);
169
+ if (!inp.text || typeof inp.text !== 'string' || inp.text.trim() === '') {
170
+ return { success: false, message: `${idx} (${key}): "text" is required and must be non-empty` };
171
+ }
172
+ if (!inp.template) {
173
+ return { success: false, message: `${idx} (${key}): "template" is required` };
174
+ }
175
+ const templateError = validateTemplateName(inp.template);
176
+ if (templateError) {
177
+ return { success: false, message: `${idx} (${key}): ${templateError}` };
178
+ }
179
+ if (inp.priority && !VALID_PRIORITY_VALUES.has(inp.priority)) {
180
+ return { success: false, message: `${idx} (${key}): invalid priority "${inp.priority}". Valid: ${[...VALID_PRIORITY_VALUES].join(', ')}` };
181
+ }
182
+ // Check self-references
183
+ const deps = inp['depends-on'] || [];
184
+ if (deps.includes(key)) {
185
+ return { success: false, message: `${idx} (${key}): self-referencing depends-on is not allowed` };
186
+ }
187
+ }
188
+ // 3. Collect existing hashes and generate IDs for all tasks
189
+ const existingHashes = collectAllExistingHashes();
190
+ const keyToId = new Map();
191
+ for (const inp of inputs) {
192
+ const hash = generateHash(existingHashes);
193
+ existingHashes.add(hash);
194
+ keyToId.set(inp.key.trim(), hash);
195
+ }
196
+ // 4. Resolve depends-on
197
+ const HEX_ID_RE = /^[0-9a-fA-F]{4}$/;
198
+ const resolvedDeps = new Map();
199
+ for (let i = 0; i < inputs.length; i++) {
200
+ const inp = inputs[i];
201
+ const deps = inp['depends-on'] || [];
202
+ const resolved = [];
203
+ for (const rawDep of deps) {
204
+ if (rawDep == null || typeof rawDep !== 'string') {
205
+ return {
206
+ success: false,
207
+ message: `[${i}] (${inp.key.trim()}): invalid depends-on entry (expected string, got ${typeof rawDep})`,
208
+ };
209
+ }
210
+ const dep = rawDep.trim();
211
+ // Check if it's a batch key
212
+ if (keyToId.has(dep)) {
213
+ resolved.push(keyToId.get(dep));
214
+ }
215
+ else if (HEX_ID_RE.test(dep)) {
216
+ // Existing hex ID — pass through
217
+ resolved.push(dep);
218
+ }
219
+ else {
220
+ return {
221
+ success: false,
222
+ message: `[${i}] (${inp.key.trim()}): unknown dependency "${dep}" — not a batch key and not a valid 4-char hex ID`,
223
+ };
224
+ }
225
+ }
226
+ resolvedDeps.set(inp.key.trim(), resolved);
227
+ }
228
+ // 5. Build Task objects and append
229
+ const tasks = readTasks(project);
230
+ const created = [];
231
+ for (const inp of inputs) {
232
+ const taskId = keyToId.get(inp.key.trim());
233
+ const newTask = {
234
+ id: taskId,
235
+ text: inp.text,
236
+ why: inp.why || '',
237
+ done_when: inp['done-when'] || '',
238
+ priority: (VALID_PRIORITY_VALUES.has(inp.priority || '') ? inp.priority : 'medium'),
239
+ status: 'open',
240
+ template: inp.template,
241
+ plan: (inp.plan || '').trim(),
242
+ project,
243
+ parent: null,
244
+ depends_on: resolvedDeps.get(inp.key.trim()) || [],
245
+ gpu: inp.gpu || null,
246
+ gpu_count: typeof inp['gpu-count'] === 'number' ? inp['gpu-count'] : 1,
247
+ blocked_by: null,
248
+ claimed_by: null,
249
+ claimed_at: null,
250
+ paused: false,
251
+ approval_needed: false,
252
+ approved_at: null,
253
+ not_before: null,
254
+ completed_at: null,
255
+ completed_note: null,
256
+ pending_at: null,
257
+ };
258
+ tasks.push(newTask);
259
+ created.push({ key: inp.key.trim(), id: taskId, text: inp.text });
260
+ }
261
+ writeTasks(project, tasks);
262
+ return {
263
+ success: true,
264
+ message: `Bulk-added ${inputs.length} task(s) to ${project}`,
265
+ created,
266
+ };
109
267
  }
110
- export { addTask, batchEdit, decomposeTask };
268
+ export { addTask, batchEdit, bulkAddTasks, decomposeTask };
@@ -0,0 +1,17 @@
1
+ import type { ThreadRecord, ThreadContract } from '../../core/types/thread-types.js';
2
+ /** Compose the structured child prompt from a delegation contract (analogous to
3
+ * buildDispatchPrompt for tasks). With neither contract nor mission chain, the
4
+ * message passes through unchanged (legacy thread_start behavior). */
5
+ export declare function buildContractPrompt(args: {
6
+ message: string;
7
+ contract?: ThreadContract | null;
8
+ missionChain?: string[];
9
+ }): string;
10
+ /** Ancestor goal chain for a child spawned under `parent`, root-first:
11
+ * the parent's own chain plus the parent's goal (contract goal, else its truncated
12
+ * userMessage). Injected into every contract so leaves can see the whole "why". */
13
+ export declare function buildMissionChain(parent: ThreadRecord | null): string[];
14
+ /** Per-thread contract budget breaker: true when the thread has spent its contract budget.
15
+ * Used by checkTemplateLimits (template threads) and the runner's wait re-entry branch
16
+ * (ad-hoc parents, which bypass transition evaluation). */
17
+ export declare function checkContractBudget(thread: ThreadRecord): boolean;