@cortex-agent/server 2026.5.25-1 → 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 (354) 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/tasks/dispatch-utils.d.ts +58 -1
  122. package/dist/domain/tasks/dispatch-utils.js +53 -4
  123. package/dist/domain/tasks/dispatcher.js +26 -0
  124. package/dist/domain/tasks/lint.js +28 -0
  125. package/dist/domain/tasks/mutator.d.ts +16 -3
  126. package/dist/domain/tasks/mutator.js +41 -12
  127. package/dist/domain/tasks/pending-tracker.js +6 -5
  128. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  129. package/dist/domain/tasks/system/task-cli.js +37 -6
  130. package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
  131. package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
  132. package/dist/domain/tasks/system/task-mutations.js +166 -8
  133. package/dist/domain/threads/contract.d.ts +17 -0
  134. package/dist/domain/threads/contract.js +59 -0
  135. package/dist/domain/threads/hook-runner.js +7 -6
  136. package/dist/domain/threads/index.d.ts +2 -0
  137. package/dist/domain/threads/index.js +3 -1
  138. package/dist/domain/threads/prompt-builder.d.ts +15 -1
  139. package/dist/domain/threads/prompt-builder.js +41 -2
  140. package/dist/domain/threads/runner.d.ts +6 -5
  141. package/dist/domain/threads/runner.js +128 -79
  142. package/dist/domain/threads/state-machine.d.ts +23 -21
  143. package/dist/domain/threads/state-machine.js +113 -54
  144. package/dist/domain/threads/template-loader.js +3 -2
  145. package/dist/domain/threads/tree.d.ts +45 -0
  146. package/dist/domain/threads/tree.js +171 -0
  147. package/dist/domain/tui-session/index.d.ts +2 -0
  148. package/dist/domain/tui-session/index.js +3 -0
  149. package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
  150. package/dist/domain/tui-session/tui-session-service.js +103 -0
  151. package/dist/domain/tui-session/types.d.ts +67 -0
  152. package/dist/domain/tui-session/types.js +4 -0
  153. package/dist/domain/ui-service/index.d.ts +5 -0
  154. package/dist/domain/ui-service/index.js +3 -0
  155. package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
  156. package/dist/domain/ui-service/mutate/executions.js +15 -0
  157. package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
  158. package/dist/domain/ui-service/mutate/schedules.js +39 -0
  159. package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
  160. package/dist/domain/ui-service/mutate/tasks.js +59 -0
  161. package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
  162. package/dist/domain/ui-service/mutate/threads.js +21 -0
  163. package/dist/domain/ui-service/query/cost.d.ts +3 -0
  164. package/dist/domain/ui-service/query/cost.js +6 -0
  165. package/dist/domain/ui-service/query/executions.d.ts +2 -0
  166. package/dist/domain/ui-service/query/executions.js +35 -0
  167. package/dist/domain/ui-service/query/projects.d.ts +2 -0
  168. package/dist/domain/ui-service/query/projects.js +30 -0
  169. package/dist/domain/ui-service/query/schedules.d.ts +2 -0
  170. package/dist/domain/ui-service/query/schedules.js +23 -0
  171. package/dist/domain/ui-service/query/sessions.d.ts +2 -0
  172. package/dist/domain/ui-service/query/sessions.js +35 -0
  173. package/dist/domain/ui-service/query/tasks.d.ts +2 -0
  174. package/dist/domain/ui-service/query/tasks.js +30 -0
  175. package/dist/domain/ui-service/query/threads.d.ts +2 -0
  176. package/dist/domain/ui-service/query/threads.js +27 -0
  177. package/dist/domain/ui-service/subscribe.d.ts +5 -0
  178. package/dist/domain/ui-service/subscribe.js +118 -0
  179. package/dist/domain/ui-service/types.d.ts +237 -0
  180. package/dist/domain/ui-service/types.js +5 -0
  181. package/dist/domain/ui-service/ui-service.d.ts +2 -0
  182. package/dist/domain/ui-service/ui-service.js +83 -0
  183. package/dist/entry/app.js +94 -5
  184. package/dist/entry/cli.d.ts +12 -0
  185. package/dist/entry/cli.js +122 -12
  186. package/dist/entry/feishu-login.d.ts +28 -0
  187. package/dist/entry/feishu-login.js +218 -0
  188. package/dist/entry/init.d.ts +25 -2
  189. package/dist/entry/init.js +211 -64
  190. package/dist/events/event-types.d.ts +14 -0
  191. package/dist/hooks/cortex-md-injector.mjs +47 -31
  192. package/dist/hooks/post-task-hook.mjs +6 -0
  193. package/dist/hooks/task-status-check.mjs +8 -0
  194. package/dist/orchestration/agent-runner.d.ts +2 -1
  195. package/dist/orchestration/agent-runner.js +55 -55
  196. package/dist/orchestration/conduit-queue.d.ts +18 -0
  197. package/dist/orchestration/conduit-queue.js +32 -0
  198. package/dist/orchestration/conversation-runner.d.ts +48 -0
  199. package/dist/orchestration/conversation-runner.js +109 -0
  200. package/dist/orchestration/dispatch-reconciler.js +8 -1
  201. package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
  202. package/dist/orchestration/interactions/ask-user-question.js +3 -3
  203. package/dist/orchestration/interactions/interaction-handlers.js +48 -17
  204. package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
  205. package/dist/orchestration/interactions/plan-handler.js +4 -3
  206. package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
  207. package/dist/orchestration/interactions/update-prompt.js +100 -0
  208. package/dist/orchestration/lifecycle.d.ts +4 -4
  209. package/dist/orchestration/lifecycle.js +24 -22
  210. package/dist/orchestration/orchestrator.d.ts +1 -1
  211. package/dist/orchestration/routing/commands/cancel.js +39 -47
  212. package/dist/orchestration/routing/commands/channel.js +24 -11
  213. package/dist/orchestration/routing/commands/cost.js +2 -1
  214. package/dist/orchestration/routing/commands/device.js +3 -2
  215. package/dist/orchestration/routing/commands/dispatch.js +6 -5
  216. package/dist/orchestration/routing/commands/index.d.ts +1 -1
  217. package/dist/orchestration/routing/commands/index.js +11 -10
  218. package/dist/orchestration/routing/commands/mode.js +19 -18
  219. package/dist/orchestration/routing/commands/nvtop.js +10 -9
  220. package/dist/orchestration/routing/commands/sendfile.js +7 -6
  221. package/dist/orchestration/routing/commands/session.d.ts +1 -1
  222. package/dist/orchestration/routing/commands/session.js +17 -33
  223. package/dist/orchestration/routing/commands/tail.js +4 -3
  224. package/dist/orchestration/routing/commands/task.js +4 -3
  225. package/dist/orchestration/routing/commands/thread-handlers.js +16 -6
  226. package/dist/orchestration/routing/edit-handler.js +8 -7
  227. package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
  228. package/dist/orchestration/routing/message-router.d.ts +1 -1
  229. package/dist/orchestration/routing/message-router.js +9 -9
  230. package/dist/orchestration/routing/webhook.js +233 -2
  231. package/dist/orchestration/status-helpers.d.ts +5 -1
  232. package/dist/orchestration/status-helpers.js +7 -6
  233. package/dist/orchestration/thread-callback.d.ts +67 -0
  234. package/dist/orchestration/thread-callback.js +465 -0
  235. package/dist/orchestration/thread-executor.d.ts +22 -1
  236. package/dist/orchestration/thread-executor.js +85 -36
  237. package/dist/platform/adapter.d.ts +6 -2
  238. package/dist/platform/adapters/composite-adapter.d.ts +89 -0
  239. package/dist/platform/adapters/composite-adapter.js +318 -0
  240. package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
  241. package/dist/platform/adapters/feishu-output-stream.js +274 -36
  242. package/dist/platform/adapters/feishu.d.ts +50 -5
  243. package/dist/platform/adapters/feishu.js +370 -116
  244. package/dist/platform/adapters/index.d.ts +24 -3
  245. package/dist/platform/adapters/index.js +89 -11
  246. package/dist/platform/adapters/project-conduits.d.ts +9 -0
  247. package/dist/platform/adapters/project-conduits.js +42 -0
  248. package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
  249. package/dist/platform/adapters/slack-project-conduits.js +6 -40
  250. package/dist/platform/adapters/slack.d.ts +9 -2
  251. package/dist/platform/adapters/slack.js +83 -39
  252. package/dist/platform/adapters/tui/index.d.ts +9 -0
  253. package/dist/platform/adapters/tui/index.js +10 -0
  254. package/dist/platform/adapters/tui/ports.d.ts +20 -0
  255. package/dist/platform/adapters/tui/ports.js +4 -0
  256. package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
  257. package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
  258. package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
  259. package/dist/platform/adapters/tui/tui-connection.js +53 -0
  260. package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
  261. package/dist/platform/adapters/tui/tui-gateway.js +919 -0
  262. package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
  263. package/dist/platform/adapters/tui/tui-notifications.js +60 -0
  264. package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
  265. package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
  266. package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
  267. package/dist/platform/adapters/tui/tui-transcript.js +56 -0
  268. package/dist/platform/index.d.ts +1 -0
  269. package/dist/platform/index.js +2 -1
  270. package/dist/platform/interactive-builder.js +3 -2
  271. package/dist/platform/output-stream.d.ts +5 -0
  272. package/dist/platform/testing.d.ts +7 -11
  273. package/dist/platform/testing.js +18 -15
  274. package/dist/platform/tool-trace.js +15 -5
  275. package/dist/platform/tui/protocol.d.ts +355 -0
  276. package/dist/platform/tui/protocol.js +199 -0
  277. package/dist/platform/types.d.ts +12 -3
  278. package/dist/store/execution-repo.d.ts +6 -1
  279. package/dist/store/execution-repo.js +13 -3
  280. package/dist/store/hook-sync.d.ts +18 -0
  281. package/dist/store/hook-sync.js +92 -0
  282. package/dist/store/outbound-queue.js +2 -2
  283. package/dist/store/profile-repo.js +3 -2
  284. package/dist/store/schedule-repo.d.ts +1 -8
  285. package/dist/store/session-registry-repo.d.ts +9 -1
  286. package/dist/store/session-registry-repo.js +19 -3
  287. package/dist/store/session-repo.d.ts +14 -0
  288. package/dist/store/session-repo.js +23 -0
  289. package/dist/store/thread-repo.d.ts +3 -0
  290. package/dist/store/thread-repo.js +49 -2
  291. package/dist/store/version-migrations.js +95 -0
  292. package/dist/tui/App.d.ts +27 -0
  293. package/dist/tui/App.js +219 -0
  294. package/dist/tui/components/AskUserModal.d.ts +11 -0
  295. package/dist/tui/components/AskUserModal.js +364 -0
  296. package/dist/tui/components/ConfirmModal.d.ts +12 -0
  297. package/dist/tui/components/ConfirmModal.js +31 -0
  298. package/dist/tui/components/Dashboard.d.ts +23 -0
  299. package/dist/tui/components/Dashboard.js +80 -0
  300. package/dist/tui/components/DashboardCostTab.d.ts +7 -0
  301. package/dist/tui/components/DashboardCostTab.js +16 -0
  302. package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
  303. package/dist/tui/components/DashboardExecutionsTab.js +94 -0
  304. package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
  305. package/dist/tui/components/DashboardSchedulesTab.js +124 -0
  306. package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
  307. package/dist/tui/components/DashboardTasksTab.js +200 -0
  308. package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
  309. package/dist/tui/components/DashboardThreadsTab.js +81 -0
  310. package/dist/tui/components/Header.d.ts +11 -0
  311. package/dist/tui/components/Header.js +5 -0
  312. package/dist/tui/components/InputBox.d.ts +10 -0
  313. package/dist/tui/components/InputBox.js +19 -0
  314. package/dist/tui/components/MessageRow.d.ts +7 -0
  315. package/dist/tui/components/MessageRow.js +10 -0
  316. package/dist/tui/components/Notifications.d.ts +19 -0
  317. package/dist/tui/components/Notifications.js +72 -0
  318. package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
  319. package/dist/tui/components/PlanFeedbackModal.js +161 -0
  320. package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
  321. package/dist/tui/components/ProjectSwitcher.js +43 -0
  322. package/dist/tui/components/SessionPicker.d.ts +14 -0
  323. package/dist/tui/components/SessionPicker.js +34 -0
  324. package/dist/tui/components/SidePanel.d.ts +19 -0
  325. package/dist/tui/components/SidePanel.js +8 -0
  326. package/dist/tui/components/StatusLine.d.ts +10 -0
  327. package/dist/tui/components/StatusLine.js +29 -0
  328. package/dist/tui/components/Transcript.d.ts +13 -0
  329. package/dist/tui/components/Transcript.js +56 -0
  330. package/dist/tui/hooks/useDashboardData.d.ts +32 -0
  331. package/dist/tui/hooks/useDashboardData.js +104 -0
  332. package/dist/tui/hooks/useKeybindings.d.ts +19 -0
  333. package/dist/tui/hooks/useKeybindings.js +87 -0
  334. package/dist/tui/hooks/useMutate.d.ts +22 -0
  335. package/dist/tui/hooks/useMutate.js +56 -0
  336. package/dist/tui/hooks/useNotifications.d.ts +28 -0
  337. package/dist/tui/hooks/useNotifications.js +70 -0
  338. package/dist/tui/hooks/useTranscript.d.ts +39 -0
  339. package/dist/tui/hooks/useTranscript.js +265 -0
  340. package/dist/tui/hooks/useWsClient.d.ts +29 -0
  341. package/dist/tui/hooks/useWsClient.js +69 -0
  342. package/dist/tui/index.d.ts +2 -0
  343. package/dist/tui/index.js +210 -0
  344. package/dist/tui/logic.d.ts +16 -0
  345. package/dist/tui/logic.js +49 -0
  346. package/dist/tui/render/markdown.d.ts +10 -0
  347. package/dist/tui/render/markdown.js +38 -0
  348. package/dist/tui/render/rich-blocks.d.ts +11 -0
  349. package/dist/tui/render/rich-blocks.js +24 -0
  350. package/dist/tui/ws-client.d.ts +44 -0
  351. package/dist/tui/ws-client.js +157 -0
  352. package/package.json +11 -3
  353. package/dist/orchestration/channel-queue.d.ts +0 -18
  354. package/dist/orchestration/channel-queue.js +0 -32
@@ -256,7 +256,7 @@
256
256
  "implReview": {
257
257
  "description": "Read `## Implementation Summary` + diff and append `## Impl Review (iteration M)` \u2014 must end with `[IMPL-APPROVED]` or list Blockers.",
258
258
  "continuesSession": true,
259
- "promptTemplate": "Audit Coder's project-file changes (changes by other agents in the same files may appear \u2014 ignore those):\n{{modifiedFiles}}\n\nRead the latest `## Implementation Summary (iteration M)` in {{artifactPath}} (and the following `## Response to Impl Review` if present). Append `## Impl Review (iteration M)` to {{artifactPath}}. **Remember: you MUST write your review to {{artifactPath}}.** If approved, end with `[IMPL-APPROVED]`; otherwise list the Blockers. Coder gets only 1 retry after the first block; beyond that the pipeline ends. Do not fabricate approval markers.\n\nBefore writing your review, run the project's full test suite (`npm test` or equivalent). Check that every stage passes: architecture linter, unit tests, integration tests. Any failure is a Blocker \u2014 do not write [IMPL-APPROVED] until the full suite is green."
259
+ "promptTemplate": "Original task:\n{{input}}\n\nAudit Coder's project-file changes (changes by other agents in the same files may appear \u2014 ignore those):\n{{modifiedFiles}}\n\nRead the latest `## Implementation Summary (iteration M)` in {{artifactPath}} (and the following `## Response to Impl Review` if present). Append `## Impl Review (iteration M)` to {{artifactPath}}. **Remember: you MUST write your review to {{artifactPath}}.** If approved, end with `[IMPL-APPROVED]`; otherwise list the Blockers. Coder gets only 1 retry after the first block; beyond that the pipeline ends. Do not fabricate approval markers.\n\nBefore writing your review, run the project's full test suite (`npm test` or equivalent). Check that every stage passes: architecture linter, unit tests, integration tests. Any failure is a Blocker \u2014 do not write [IMPL-APPROVED] until the full suite is green."
260
260
  }
261
261
  },
262
262
  "tools": "Agent,Bash,Edit,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write",
@@ -303,6 +303,22 @@
303
303
  "plugins/cortex-common",
304
304
  "plugins/cortex-system"
305
305
  ]
306
+ },
307
+ "manager": {
308
+ "name": "manager",
309
+ "description": "Resident manager of a composite task node (DR-0014 \u00a78): decomposes into child tasks (decompose --keep-parent), suspends via [WAIT_CHILDREN], re-enters its own session to verify deliverables, rework, or escalate. persistSession is load-bearing \u2014 re-entry resumes the SAME session with full memory.",
310
+ "profile": "__active__",
311
+ "persistSession": true,
312
+ "directive": "file:manager.md",
313
+ "systemPrompt": "file:worker.md",
314
+ "promptTemplate": "{{input}}\n\nYour shared artifact (decomposition rationale + acceptance log) is {{artifactPath}}.",
315
+ "tools": "Bash,Edit,Glob,Grep,Read,Skill,TodoWrite,WebFetch,WebSearch,Write",
316
+ "pluginDirs": [
317
+ "plugins/cortex-common",
318
+ "plugins/cortex-stage-gate",
319
+ "plugins/cortex-coder",
320
+ "plugins/cortex-system"
321
+ ]
306
322
  }
307
323
  },
308
324
  "templates": {
@@ -562,6 +578,17 @@
562
578
  "timeout": 10000
563
579
  }
564
580
  }
581
+ },
582
+ "manager": {
583
+ "name": "manager",
584
+ "description": "Composite-task node manager (DR-0014 \u00a78). Single resident agent: Phase A decomposes the task into children (keep-parent) and suspends on [WAIT_CHILDREN]; woken per task.completed/task.blocked events, Phase B verifies deliverables against done_when, reworks or escalates, finally completes its own task. Assign this template at task creation to any task expected to span 2+ independently verifiable units.",
585
+ "agents": [
586
+ "manager"
587
+ ],
588
+ "transitions": [],
589
+ "entryAgent": "manager",
590
+ "maxTotalSteps": 16,
591
+ "maxTotalCostUsd": 20
565
592
  }
566
593
  }
567
594
  }
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.6.4 ← set to the current release version (agent-server/package.json) whenever you change this hook; syncManagedHooks then refreshes deployed installs
2
3
  // input: stdin JSON — Claude Code hook event or PI hook-bridge payload
3
4
  // output: { hookSpecificOutput: { hookEventName, additionalContext, matched } }
4
5
  // pos: Inject CORTEX.md / CORTEX.local.md ancestor chain into agent context
@@ -6,8 +7,11 @@
6
7
  // PostToolUse (Read) — from tool_input.file_path/path
7
8
  // SessionStart (startup|resume|clear|compact) — from payload.cwd
8
9
  // Per-session disk-backed dedup cache (~/.cortex/tmp/cortexmd-cache/<sessionId>.json)
10
+ // — only files actually injected are marked seen; truncated files stay eligible so
11
+ // a later Read re-attempts them (they are never silently suppressed)
9
12
  // markOnlyPaths: tool operating on a CORTEX.md itself → cache update only, no inject
10
- // Total length guard at 9,500 chars with truncated annotation
13
+ // Total length guard at 9,500 chars; files that overflow the budget are turned into an
14
+ // explicit "Read EACH of these files now" instruction instead of a silent drop
11
15
  // >>> If I am updated, be sure to update my header comment and the CORTEX.md in the same folder <<<
12
16
 
13
17
  import { readFileSync, statSync, existsSync, mkdirSync, renameSync, writeFileSync } from 'fs';
@@ -123,35 +127,44 @@ function saveCache(sessionId, cache) {
123
127
  // ── context builder ──
124
128
 
125
129
  function buildContext(entries) {
126
- if (entries.length === 0) return '';
127
-
128
- // Build blocks in original order (leaf→root)
129
- const blocks = entries.map(e =>
130
- `<system-reminder>\nAuto-loaded CORTEX.md from ${HOSTNAME}:${e.path} (ancestor of accessed path). These instructions apply to files under this directory.\n\n${e.content}\n</system-reminder>`
131
- );
132
-
133
- const included = [];
130
+ if (entries.length === 0) return { text: '', includedPaths: [] };
131
+
132
+ // Walk entries in original order (leaf→root), inlining each as a block until the char
133
+ // budget is exhausted. Once exhausted, the remaining entries are NOT inlined — instead
134
+ // they are turned into an explicit read-instruction below, so their rules are never
135
+ // silently dropped (e.g. a root-level CORTEX.local.md carrying dev/safety rules).
136
+ const includedBlocks = [];
137
+ const includedPaths = [];
138
+ const truncated = [];
134
139
  let totalLen = 0;
135
-
136
- for (const block of blocks) {
137
- if (totalLen + block.length > MAX_CONTEXT_CHARS) break;
138
- included.push(block);
140
+ let budgetExhausted = false;
141
+
142
+ for (const e of entries) {
143
+ const block = `<system-reminder>\nAuto-loaded CORTEX.md from ${HOSTNAME}:${e.path} (ancestor of accessed path). These instructions apply to files under this directory.\n\n${e.content}\n</system-reminder>`;
144
+ if (budgetExhausted || totalLen + block.length > MAX_CONTEXT_CHARS) {
145
+ budgetExhausted = true; // match prior behavior: stop inlining at the first overflow
146
+ truncated.push(e);
147
+ continue;
148
+ }
149
+ includedBlocks.push(block);
150
+ includedPaths.push(e.path);
139
151
  totalLen += block.length;
140
152
  }
141
153
 
142
- const remaining = entries.length - included.length;
154
+ const parts = [...includedBlocks];
143
155
 
144
- // No block fit within the limit — return empty rather than
145
- // emitting a bare "[truncated, N more files at root]" message.
146
- if (included.length === 0) return '';
147
-
148
- let context = included.join('\n\n');
149
-
150
- if (remaining > 0) {
151
- context += `\n\n[truncated, ${remaining} more files at root]`;
156
+ // Overflow → actionable instruction. Reading these files delivers their content via the
157
+ // Read tool result; the markOnlyPaths branch then suppresses a duplicate inject.
158
+ if (truncated.length > 0) {
159
+ const list = truncated.map(e => `- ${e.path}`).join('\n');
160
+ parts.push(
161
+ `<system-reminder>\n⚠️ ${truncated.length} CORTEX rule file(s) were too large to inline here. ` +
162
+ `Read EACH of the following files now to load their rules before proceeding:\n${list}\n</system-reminder>`
163
+ );
152
164
  }
153
165
 
154
- return context;
166
+ if (parts.length === 0) return { text: '', includedPaths: [] };
167
+ return { text: parts.join('\n\n'), includedPaths };
155
168
  }
156
169
 
157
170
  // ── main ──
@@ -213,23 +226,26 @@ function main() {
213
226
  const cache = loadCache(sessionId);
214
227
  const newEntries = entries.filter(e => cache.get(e.path) !== e.mtimeMs);
215
228
 
216
- // Update cache with all scanned entries
217
- for (const entry of entries) {
218
- cache.set(entry.path, entry.mtimeMs);
219
- }
220
- saveCache(sessionId, cache);
221
-
222
229
  if (newEntries.length === 0) return;
223
230
 
224
231
  // Build context with truncation guard
225
- const additionalContext = buildContext(newEntries);
232
+ const { text: additionalContext, includedPaths } = buildContext(newEntries);
226
233
  if (!additionalContext) return;
227
234
 
235
+ // Mark as seen ONLY the entries actually injected. Truncated entries stay "unseen" so a
236
+ // later Read re-attempts their injection (or re-emits the read-instruction) — they must
237
+ // never be silently suppressed by being cached before the truncation filter runs.
238
+ const injected = new Set(includedPaths);
239
+ for (const entry of entries) {
240
+ if (injected.has(entry.path)) cache.set(entry.path, entry.mtimeMs);
241
+ }
242
+ saveCache(sessionId, cache);
243
+
228
244
  process.stdout.write(JSON.stringify({
229
245
  hookSpecificOutput: {
230
246
  hookEventName,
231
247
  additionalContext,
232
- matched: newEntries.map(e => e.path),
248
+ matched: includedPaths,
233
249
  },
234
250
  }));
235
251
  }
@@ -50,6 +50,12 @@ async function main() {
50
50
  parts.push('After completing the task, run `git status` to check for your uncommitted changes. If there are changes, commit them with an appropriate commit message. Do not commit changes that are not made by you.');
51
51
  }
52
52
 
53
+ // Worktree integration reminder (concurrent-safe code isolation). Piggybacks on the
54
+ // turn we are already injecting, so it costs no extra agent step. Self-gates: a no-op
55
+ // for tasks that never created a worktree.
56
+ const threadId = context.threadId || '$CORTEX_THREAD_ID';
57
+ parts.push(`If you created a git worktree for this task (branch cortex/${threadId}), integrate it back now before finishing: pull the latest main branch, merge your branch into it, resolve conflicts, push, then \`git worktree remove\` and delete the branch. On remote machines run these commands via remote_bash on the device you worked on. If conflicts cannot be resolved automatically, stop and report it — never force-overwrite another thread's work. If you did NOT create a worktree, ignore this.`);
58
+
53
59
  console.log(JSON.stringify({
54
60
  insertAgent: false,
55
61
  targetAgent,
@@ -119,6 +119,14 @@ async function main() {
119
119
 
120
120
  if (!project || !taskId) { noop(); return; }
121
121
 
122
+ // [SPLIT] decomposition proposal (DR-0014): the task is INTENTIONALLY not done — the
123
+ // dispatcher decomposes it keep-parent and unclaims. Don't burn an agent turn nagging.
124
+ if ((ctx.artifactContent || '').includes('[SPLIT]')) { noop(); return; }
125
+
126
+ // [ABORT] worker escalation (DR-0014 §8): the dispatcher blocks the task with the abort
127
+ // reason right after this hook returns — the task is intentionally not done.
128
+ if (/\[ABORT(?::|\])/.test(ctx.artifactContent || '')) { noop(); return; }
129
+
122
130
  const tasksPath = path.join(PROJECTS_DIR, project, 'TASKS.yaml');
123
131
  if (!existsSync(tasksPath)) { noop(); return; }
124
132
 
@@ -0,0 +1,11 @@
1
+ {
2
+ "mcpServers": {
3
+ "cortex-slack": {
4
+ "command": "node",
5
+ "args": [
6
+ "/path/to/slack-server.js"
7
+ ],
8
+ "cwd": "/path/to/server"
9
+ }
10
+ }
11
+ }
@@ -371,6 +371,24 @@ If decomposed tasks have execution order requirements, they **must use `depends-
371
371
  - Mixes blocked and unblocked work
372
372
  - Mixes mechanical work and judgment-based work
373
373
 
374
+ #### Composite Tasks: Assign the `manager` Template (DR-0014 §8)
375
+
376
+ Decomposition does NOT have to happen at creation time. When a task is clearly composite —
377
+ it would trigger the conditions above, but the right split is only knowable after some
378
+ investigation — do not force a premature decomposition. Instead create ONE task with
379
+ `template: manager`:
380
+
381
+ - A manager thread (strong model, persistent session) is dispatched for it: it orients,
382
+ decomposes into child tasks (`decompose --keep-parent`, children carry `parent`), suspends
383
+ on `[WAIT_CHILDREN]`, and is woken to verify each child's deliverable against its done_when
384
+ before completing the parent. Acceptance is part of the node, not an afterthought.
385
+ - Rule of thumb: expected to span 2+ independently verifiable units, or the decomposition
386
+ itself needs judgment → `manager`. A single well-scoped unit → a worker template
387
+ (coder-review / execute-review / ...).
388
+ - Worker escalation: a worker that discovers its task is mis-scoped writes
389
+ `[ABORT: too-big — <diagnosis>]`; the task gets blocked with the diagnosis and the owning
390
+ manager (or a human) re-plans. Workers never decompose tasks themselves.
391
+
374
392
  ### Stage Boundary Constraints
375
393
 
376
394
  **For projects using the stage-gate mechanism**: Each task creation operation only creates tasks **up to the next gate**; do not pre-create tasks across gates for future stages.
@@ -36,7 +36,6 @@ Scheduled tasks allow Cortex to automatically execute messages at set times —
36
36
  **Targets (where the fired task lands):**
37
37
  - `fresh` *(default)* — new isolated thread + new session (current behavior; safest for unrelated tasks)
38
38
  - `current-project` — spawn a fresh session in the project (default for project-addressed schedules)
39
- - `current-session` — reuse the current cortex-XXXX session (same conversation)
40
39
  - `current-thread` — continue the current thread (only valid while it's running/waiting)
41
40
 
42
41
  `current-*` shorthand resolves to concrete IDs at create time, so `cortex_schedule_list` always shows real IDs.
@@ -58,8 +57,8 @@ mcp__cortex__cortex_schedule_add({
58
57
  time?: '09:00', // for daily/weekly
59
58
  dayOfWeek?: 'mon' | 0-6, // for weekly
60
59
  delay?: '2h' | '90m', // for once
61
- target?: 'fresh' | 'current-project' | 'current-session' | 'current-thread' | { kind, ... },
62
- fallback?: 'fresh' | 'skip' | 'wait', // when target session/thread is gone at fire time
60
+ target?: 'fresh' | 'current-project' | 'current-thread' | { kind, ... },
61
+ fallback?: 'fresh' | 'skip' | 'wait', // when target thread is gone at fire time
63
62
  profile?: 'fast-worker',
64
63
  channel?: 'C123', // override; defaults to current context
65
64
  })
@@ -76,15 +75,15 @@ mcp__cortex__cortex_schedule_resume({ id })
76
75
  >
77
76
  > Call `mcp__cortex__cortex_schedule_add({ type: 'daily', time: '09:00', message: '/orient', target: 'current-project' })` — done. No need to call `cortex_context` first; the shorthand resolves automatically.
78
77
 
79
- > User: "Report training status in this conversation after 30 minutes"
78
+ > User: "Report training status in this thread after 30 minutes"
80
79
  >
81
- > Call `mcp__cortex__cortex_schedule_add({ type: 'once', delay: '30m', message: 'Check training results on <machine> and report', target: 'current-session' })` — the schedule will resume the same Claude/Codex session, so prior context is intact.
80
+ > Call `mcp__cortex__cortex_schedule_add({ type: 'once', delay: '30m', message: 'Check training results on <machine> and report', target: 'current-thread' })` — the schedule continues the current thread (valid while it is running/waiting), so prior context is intact.
82
81
 
83
82
  > User: "Run deep retrospective every Monday at 9 PM"
84
83
  >
85
84
  > Call `mcp__cortex__cortex_schedule_add({ type: 'weekly', dayOfWeek: 'mon', time: '21:00', message: '/deep-retrospective' })` — `target` defaults to `fresh`, which is the right choice for a standalone weekly job.
86
85
 
87
- If `current-session` / `current-thread` is requested but the context lacks the field, the tool throws — it does NOT silently fall back to fresh. Re-issue with `target: 'fresh'` if that's actually what you want.
86
+ If `current-thread` is requested but the context lacks the field, the tool throws — it does NOT silently fall back to fresh. Re-issue with `target: 'fresh'` if that's actually what you want.
88
87
 
89
88
  ---
90
89
 
@@ -0,0 +1,67 @@
1
+ # Identity
2
+
3
+ - **Role**: Manager — the resident owner of a composite task node (DR-0014 §8). You decompose, supervise, verify, and correct. You do NOT do the execution work yourself.
4
+ - **Position**: dispatched for a task whose template is `manager`. Your thread suspends while child tasks run and is re-entered (same session, full memory) when they complete or get blocked.
5
+ - **One node per invocation**: you own exactly the task in `{{input}}` (its Task ID is stated there). Everything you create hangs under it.
6
+
7
+ # Mission
8
+
9
+ Turn one composite task into verified, integrated results. Cortex optimizes **Quality > Cost > Speed**: your value is in decomposition quality and acceptance rigor, not in doing the work. A wrong decomposition multiplies cost downstream; a rubber-stamp acceptance poisons everything that depends on this node.
10
+
11
+ # Operating Phases
12
+
13
+ You will live through multiple wake-ups in one session. On EVERY entry, first determine your phase:
14
+
15
+ run `cortex-task tree --task-id <your Task ID>` (and `cortex-task show`) to see your children and their states.
16
+
17
+ ## Phase A — Decompose (no children exist yet)
18
+
19
+ 1. **Orient**: read the task's plan file, the project's `STATUS.md` / `mission.md` / `roadmap.md`, and any context the dispatch prompt names. Understand what "done" means for YOUR task (its done_when is the contract you'll be graded on).
20
+ 2. **Judge size first**: if the task is actually leaf-sized (a single independently verifiable unit), just do it yourself and complete it — do not decompose for ceremony.
21
+ 3. **Decompose by the Iron Rules** (One-Criterion-One-Task; explicit dependencies — see /task skill):
22
+ - Each child = one independently completable AND verifiable unit, verb-first text, concrete done_when.
23
+ - Order siblings with `key` + `depends-on`. Pick each child's `template` deliberately (worker templates for execution; another `manager` for a composite child — that nests the tree).
24
+ - Create them in ONE call (exact recipe — write the JSON to a temp file first):
25
+
26
+ ```bash
27
+ cat > /tmp/subtasks-<your Task ID>.json <<'JSON'
28
+ {"subtasks": [
29
+ {"key": "a", "text": "Create X", "done-when": "X exists and ...", "template": "execute-review"},
30
+ {"key": "b", "text": "Create Y", "done-when": "...", "template": "execute-review", "depends-on": ["a"]}
31
+ ]}
32
+ JSON
33
+ cortex-task decompose --project <project> --task-id <your Task ID> --keep-parent --auto-lock --subtasks-file /tmp/subtasks-<your Task ID>.json
34
+ ```
35
+
36
+ `--keep-parent` makes children hang under you (`parent`) and adds them to your task's `depends_on` — that is your disaster-recovery join: if this thread is ever lost, your task re-unlocks after all children finish and a fresh manager takes over.
37
+ Verify with `cortex-task tree --task-id <your Task ID>` before suspending. If decompose errors, fix the JSON and retry — do NOT fall back to ad-hoc task creation that leaves children unlinked to you.
38
+ 4. **Write your reasoning down** (MANDATORY — fallback memory for a fresh manager if this session is ever lost): why this decomposition, what each child must deliver, your per-child acceptance checklist. Write it BOTH to your artifact AND to `context/projects/<project>/manager-notes-<your Task ID>.md` — the project file survives thread-workspace cleanup; the artifact does not.
39
+ 5. End your step with the marker `[WAIT_CHILDREN]` on its own line.
40
+
41
+ **Queue semantics — read carefully (this is where managers go wrong):**
42
+ - Your children are dispatched by the task queue ONLY AFTER your step ends and you suspend. You will NEVER see them start, run, or finish during your own step. Children sitting `open`/unclaimed while you are still running is the EXPECTED state, not a failure.
43
+ - NEVER block, complete, or unclaim your own task in Phase A, and never conclude "the dispatcher isn't working" from inside your own step. Emit `[WAIT_CHILDREN]` and end — the system does the rest.
44
+ - Do not poll or wait in-step. Suspension is free; polling burns budget.
45
+
46
+ ## Phase B — Verify & Correct (woken with child results)
47
+
48
+ Child results arrive as injected messages; ALWAYS cross-check against `cortex-task tree` for the full picture (pre-existing blocked children may not generate messages).
49
+
50
+ For each finished child, **acceptance before trust**:
51
+ 1. Read the actual deliverable (code, files, experiment records) and check it against the child's done_when. Run tests where code is involved. Never accept a completion note as evidence.
52
+ 2. **Pass** → distill the key conclusions into your artifact; move on.
53
+ 3. **Fail** → write the expected/actual gap and your hypothesis into the artifact, then either `cortex-task uncomplete` + edit the child with a sharper contract, or add a revision child via the same `decompose --keep-parent` call. End with `[WAIT_CHILDREN]` again.
54
+ 4. **Blocked child** (escalation from a worker — e.g. `worker-abort: too-big`): this means YOUR decomposition needs revising. Diagnose, then `cortex-task unblock` + edit, or rebuild the unit as new children. Do not just retry the same contract.
55
+ 5. **Direction is wrong** (the decomposition premise no longer holds, or the problem exceeds your node's authority): append `[ABORT: <one-line diagnosis>]` to the artifact — your own parent manager (or a human) re-plans with your diagnosis.
56
+
57
+ When ALL children are verified:
58
+ 6. Integrate: check the combined result against YOUR task's original done_when (the children passing individually is not enough).
59
+ 7. Update the project's `STATUS.md`; record durable findings in the project knowledge files.
60
+ 8. `cortex-task complete --project <project> --task-id <your Task ID> --note "<what was delivered + verification evidence>"`.
61
+ 9. End normally — WITHOUT `[WAIT_CHILDREN]`.
62
+
63
+ # Tools & Limits
64
+
65
+ - `thread_start` remains available for quick sub-calls that don't deserve a task (an independent verifier pass on a child's deliverable, a short research probe before deciding a split). Minutes-scale only; tree guards (width/depth/budget) apply.
66
+ - Stay within your node: don't touch sibling tasks or re-plan above your level — that's what `[ABORT: <diagnosis>]` is for.
67
+ - Rework discipline: at most 2 revision rounds per child; if a unit fails a third time, escalate with your accumulated diagnosis instead of iterating.
@@ -12,8 +12,21 @@ export interface TuiSessionDeps {
12
12
  tmux: TmuxControl;
13
13
  /** Factory creating a tail for the given jsonl path. Defaults to real JsonlTail in production. */
14
14
  tailFactory: (jsonlPath: string) => JsonlTailLike;
15
- /** Max wait for jsonl file to appear after spawning. Tests pass 0 (skip wait). Default 5000ms. */
15
+ /** @deprecated No longer used — the jsonl file appears only after the first submit, so there is
16
+ * nothing to wait for at spawn. Kept so existing callers/tests construct without changes. */
16
17
  waitForJsonlMs?: number;
18
+ /** Fast-fail window (ms) for a fresh turn producing no jsonl output. Tests override with a small
19
+ * value. Defaults to JSONL_FIRST_EVENT_TIMEOUT. */
20
+ firstEventTimeoutMs?: number;
21
+ /** Delay (ms) between pasting the prompt and sending Enter. Tests set 0 to submit synchronously.
22
+ * Defaults to PASTE_SUBMIT_DELAY_MS (needed so Claude's Ink TUI registers the paste). */
23
+ pasteSubmitDelayMs?: number;
24
+ /** Max time (ms) to poll capture-pane for the Claude TUI readiness marker after a fresh spawn,
25
+ * before the first paste. Tests set 0 to skip the wait (mocked tmux never renders a pane).
26
+ * Defaults to PANE_READY_TIMEOUT. */
27
+ paneReadyTimeoutMs?: number;
28
+ /** Poll interval (ms) for the pane-readiness wait. Defaults to PANE_READY_POLL_MS. */
29
+ paneReadyPollMs?: number;
17
30
  }
18
31
  export interface ClaudeTuiSessionConfig {
19
32
  channel: string;
@@ -85,7 +98,10 @@ export declare class ClaudeTuiSession {
85
98
  readonly jsonlPath: string;
86
99
  private readonly tmux;
87
100
  private readonly tailFactory;
88
- private readonly waitForJsonlMs;
101
+ private readonly firstEventTimeoutMs;
102
+ private readonly pasteSubmitDelayMs;
103
+ private readonly paneReadyTimeoutMs;
104
+ private readonly paneReadyPollMs;
89
105
  private readonly config;
90
106
  private tail;
91
107
  private normalizer;
@@ -95,10 +111,17 @@ export declare class ClaudeTuiSession {
95
111
  private idleTimer;
96
112
  private maxTimer;
97
113
  private turnIdleTimer;
114
+ private firstEventTimer;
98
115
  constructor(config: ClaudeTuiSessionConfig);
99
116
  isAlive(): boolean;
100
117
  private ensureSpawned;
101
- private waitForJsonl;
118
+ /**
119
+ * Poll capture-pane until the Claude TUI prompt is interactive (or the timeout elapses). Returns
120
+ * as soon as {@link PANE_READY_MARKER} appears. On timeout it logs and returns anyway — better to
121
+ * attempt the paste than to hard-fail, and the first-event watchdog still bounds a dead session.
122
+ * Tests pass paneReadyTimeoutMs=0 to skip entirely (mocked tmux renders no pane).
123
+ */
124
+ private waitForPaneReady;
102
125
  sendMessage(userMessage: string, options: SendMessageOptions): Promise<TuiAgentResult>;
103
126
  /**
104
127
  * Cancel the currently in-flight turn. Sends Escape (interrupts model generation), then C-u
@@ -114,6 +137,15 @@ export declare class ClaudeTuiSession {
114
137
  private resetIdleTimer;
115
138
  private startTurnIdleTimer;
116
139
  private bumpTurnIdleTimer;
140
+ /**
141
+ * One-shot fast-fail watchdog for the window between submitting a prompt and the first jsonl
142
+ * event. Replaces the old 5s file-appear wait that used to fail fast at spawn — now that the
143
+ * tail is non-blocking, a Claude that never starts would otherwise hang until TURN_IDLE_TIMEOUT
144
+ * (60 min). On fire: reject the pending turn with a descriptive error and kill the session.
145
+ * Disarmed by {@link clearFirstEventWatchdog} on the first jsonl event of the turn.
146
+ */
147
+ private armFirstEventWatchdog;
148
+ private clearFirstEventWatchdog;
117
149
  close(): void;
118
150
  kill(): boolean;
119
151
  }
@@ -2,11 +2,10 @@
2
2
  // output: ClaudeTuiSession — interactive Claude under tmux with jsonl tail; implements turn lifecycle
3
3
  // pos: DR-0012 Phase 2 — parallel adapter to claude/adapter.ts; selects via spawn-args mode='tui'
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
- import * as fs from 'fs';
6
5
  import * as path from 'path';
7
6
  import { createLogger } from '../../core/log.js';
8
7
  import { JsonlTail, JsonlEventNormalizer } from './jsonl-tail.js';
9
- import { CancelledError, TUI_TMUX_NAME_PREFIX, TUI_JSONL_BASE, IDLE_SESSION_TIMEOUT, MAX_TIMEOUT, TURN_IDLE_TIMEOUT, } from './defaults.js';
8
+ import { CancelledError, TUI_TMUX_NAME_PREFIX, TUI_JSONL_BASE, IDLE_SESSION_TIMEOUT, MAX_TIMEOUT, TURN_IDLE_TIMEOUT, JSONL_FIRST_EVENT_TIMEOUT, PASTE_SUBMIT_DELAY_MS, PANE_READY_TIMEOUT, PANE_READY_POLL_MS, PANE_READY_MARKER, } from './defaults.js';
10
9
  import { buildSpawnArgs, buildClaudeEnv } from './spawn-args.js';
11
10
  import { buildPrompt, mergeSubstantialOutput } from './event-parser.js';
12
11
  const log = createLogger('claude-tui');
@@ -29,7 +28,10 @@ export class ClaudeTuiSession {
29
28
  jsonlPath;
30
29
  tmux;
31
30
  tailFactory;
32
- waitForJsonlMs;
31
+ firstEventTimeoutMs;
32
+ pasteSubmitDelayMs;
33
+ paneReadyTimeoutMs;
34
+ paneReadyPollMs;
33
35
  config;
34
36
  tail = null;
35
37
  normalizer = new JsonlEventNormalizer();
@@ -39,6 +41,7 @@ export class ClaudeTuiSession {
39
41
  idleTimer = null;
40
42
  maxTimer = null;
41
43
  turnIdleTimer = null;
44
+ firstEventTimer = null;
42
45
  constructor(config) {
43
46
  this.config = config;
44
47
  this.channel = config.channel;
@@ -48,7 +51,10 @@ export class ClaudeTuiSession {
48
51
  this.needsResume = config.needsResume;
49
52
  this.tmux = config.deps.tmux;
50
53
  this.tailFactory = config.deps.tailFactory;
51
- this.waitForJsonlMs = config.deps.waitForJsonlMs ?? 5000;
54
+ this.firstEventTimeoutMs = config.deps.firstEventTimeoutMs ?? JSONL_FIRST_EVENT_TIMEOUT;
55
+ this.pasteSubmitDelayMs = config.deps.pasteSubmitDelayMs ?? PASTE_SUBMIT_DELAY_MS;
56
+ this.paneReadyTimeoutMs = config.deps.paneReadyTimeoutMs ?? PANE_READY_TIMEOUT;
57
+ this.paneReadyPollMs = config.deps.paneReadyPollMs ?? PANE_READY_POLL_MS;
52
58
  this.tmuxName = `${TUI_TMUX_NAME_PREFIX}${this.sessionId}`;
53
59
  this.jsonlPath = computeJsonlPath(this.cwd, this.sessionId);
54
60
  }
@@ -84,6 +90,15 @@ export class ClaudeTuiSession {
84
90
  if (typeof v === 'string')
85
91
  stringEnv[k] = v;
86
92
  }
93
+ // A tmux session under our name may already exist while we are NOT `alive` — e.g. a prior
94
+ // spawn created it but then failed (the first tail.start threw), or it was orphaned. Killing
95
+ // it first (idempotent) keeps the next newSession from crashing with "duplicate session" and
96
+ // permanently wedging the pool entry. The top-of-method guard already returned early for the
97
+ // healthy alive+hasSession case, so reaching here with a live session means it is stale.
98
+ if (this.tmux.hasSession(this.tmuxName)) {
99
+ log.warn(`ensureSpawned: stale tmux session ${this.tmuxName} present while not alive — killing before respawn`);
100
+ this.tmux.killSession(this.tmuxName);
101
+ }
87
102
  log.info(`Spawning TUI session ${this.tmuxName} (${this.needsResume ? 'resume' : 'new'})`);
88
103
  this.tmux.newSession({
89
104
  name: this.tmuxName,
@@ -95,7 +110,10 @@ export class ClaudeTuiSession {
95
110
  // the Claude jsonl transcript now exists at jsonlPath, and --session-id would conflict.
96
111
  // This covers the "tmux died externally between turns" case (DR-0012 §3.6 recovery path).
97
112
  this.needsResume = true;
98
- await this.waitForJsonl();
113
+ // NOTE: we do NOT wait for the jsonl file here. Current Claude Code creates the transcript only
114
+ // after the first message is submitted (DR-0012 soak finding), so the file cannot appear before
115
+ // the paste in sendMessage. The tail attaches now (non-blocking) and backfills the first turn
116
+ // once Claude writes it; a missing-output failure is bounded by the first-event watchdog.
99
117
  // Tear down any pre-existing tail before reassigning. This path is reached during
100
118
  // recovery from external tmux death (alive flag was true but hasSession returned false),
101
119
  // where the previous tail's poll timer would otherwise keep firing forever and
@@ -114,6 +132,10 @@ export class ClaudeTuiSession {
114
132
  this.tail = this.tailFactory(this.jsonlPath);
115
133
  this.tail.on('event', (raw) => this.handleRawEvent(raw));
116
134
  await this.tail.start();
135
+ // Claude's Ink TUI boots asynchronously and only accepts input once its prompt UI is drawn.
136
+ // Block here until capture-pane shows a readiness marker, otherwise the first paste lands in a
137
+ // not-yet-ready terminal and the submit Enter is a no-op (no jsonl → first-event watchdog kill).
138
+ await this.waitForPaneReady();
117
139
  this.alive = true;
118
140
  this.resetIdleTimer();
119
141
  this.maxTimer = setTimeout(() => {
@@ -125,16 +147,27 @@ export class ClaudeTuiSession {
125
147
  if (typeof this.maxTimer.unref === 'function')
126
148
  this.maxTimer.unref();
127
149
  }
128
- async waitForJsonl() {
129
- if (this.waitForJsonlMs <= 0)
150
+ /**
151
+ * Poll capture-pane until the Claude TUI prompt is interactive (or the timeout elapses). Returns
152
+ * as soon as {@link PANE_READY_MARKER} appears. On timeout it logs and returns anyway — better to
153
+ * attempt the paste than to hard-fail, and the first-event watchdog still bounds a dead session.
154
+ * Tests pass paneReadyTimeoutMs=0 to skip entirely (mocked tmux renders no pane).
155
+ */
156
+ async waitForPaneReady() {
157
+ if (this.paneReadyTimeoutMs <= 0)
130
158
  return;
131
- const deadline = Date.now() + this.waitForJsonlMs;
159
+ const deadline = Date.now() + this.paneReadyTimeoutMs;
132
160
  while (Date.now() < deadline) {
133
- if (fs.existsSync(this.jsonlPath))
161
+ let pane = '';
162
+ try {
163
+ pane = this.tmux.capturePane(this.tmuxName);
164
+ }
165
+ catch { /* pane not ready yet */ }
166
+ if (PANE_READY_MARKER.test(pane))
134
167
  return;
135
- await new Promise(r => setTimeout(r, 50));
168
+ await new Promise(r => setTimeout(r, this.paneReadyPollMs));
136
169
  }
137
- // Best-effort: jsonl may appear after first user message; do not throw here.
170
+ log.warn(`TUI session ${this.sessionId.substring(0, 8)} pane not ready within ${this.paneReadyTimeoutMs}ms — pasting anyway`);
138
171
  }
139
172
  // -----------------------------------------------------------------------------
140
173
  // Turn execution
@@ -161,10 +194,16 @@ export class ClaudeTuiSession {
161
194
  options,
162
195
  };
163
196
  });
164
- // Paste prompt + Enter
197
+ // Paste prompt, let the Ink TUI register the bracketed paste, THEN submit with Enter.
198
+ // Enter sent immediately after paste-buffer is swallowed and the prompt never submits
199
+ // (DR-0012 soak finding on Claude 2.1.160) — hence the settle delay.
165
200
  this.tmux.pasteText(this.tmuxName, prompt);
201
+ if (this.pasteSubmitDelayMs > 0) {
202
+ await new Promise(r => setTimeout(r, this.pasteSubmitDelayMs));
203
+ }
166
204
  this.tmux.sendKeys(this.tmuxName, 'Enter');
167
205
  this.startTurnIdleTimer();
206
+ this.armFirstEventWatchdog();
168
207
  return turnPromise;
169
208
  }
170
209
  /**
@@ -193,12 +232,16 @@ export class ClaudeTuiSession {
193
232
  clearTimeout(this.turnIdleTimer);
194
233
  this.turnIdleTimer = null;
195
234
  }
235
+ this.clearFirstEventWatchdog();
196
236
  turn.reject(new CancelledError());
197
237
  }
198
238
  // -----------------------------------------------------------------------------
199
239
  // Event handling — jsonl tail → normalizer → turn state
200
240
  // -----------------------------------------------------------------------------
201
241
  handleRawEvent(raw) {
242
+ // First jsonl line of the turn proves Claude started producing output — disarm the fast-fail
243
+ // watchdog; from here the per-event turnIdleTimer governs stalls.
244
+ this.clearFirstEventWatchdog();
202
245
  this.resetIdleTimer();
203
246
  this.bumpTurnIdleTimer();
204
247
  const events = this.normalizer.consume(raw);
@@ -295,6 +338,7 @@ export class ClaudeTuiSession {
295
338
  clearTimeout(this.turnIdleTimer);
296
339
  this.turnIdleTimer = null;
297
340
  }
341
+ this.clearFirstEventWatchdog();
298
342
  this.currentTurn = null;
299
343
  // Note: needsResume is set to true in ensureSpawned() after first spawn — that flag stays
300
344
  // true for the rest of this ClaudeTuiSession's lifetime so recovery from tmux death uses
@@ -342,6 +386,39 @@ export class ClaudeTuiSession {
342
386
  return;
343
387
  this.startTurnIdleTimer();
344
388
  }
389
+ /**
390
+ * One-shot fast-fail watchdog for the window between submitting a prompt and the first jsonl
391
+ * event. Replaces the old 5s file-appear wait that used to fail fast at spawn — now that the
392
+ * tail is non-blocking, a Claude that never starts would otherwise hang until TURN_IDLE_TIMEOUT
393
+ * (60 min). On fire: reject the pending turn with a descriptive error and kill the session.
394
+ * Disarmed by {@link clearFirstEventWatchdog} on the first jsonl event of the turn.
395
+ */
396
+ armFirstEventWatchdog() {
397
+ this.clearFirstEventWatchdog();
398
+ this.firstEventTimer = setTimeout(() => {
399
+ const turn = this.currentTurn;
400
+ if (!turn)
401
+ return;
402
+ log.warn(`TUI session ${this.sessionId.substring(0, 8)} produced no jsonl output within ${this.firstEventTimeoutMs}ms of submit — killing`);
403
+ // Detach the turn before kill() so it surfaces this descriptive error rather than kill()'s
404
+ // generic CancelledError (which the adapter treats as a silent user cancel).
405
+ this.currentTurn = null;
406
+ if (this.turnIdleTimer) {
407
+ clearTimeout(this.turnIdleTimer);
408
+ this.turnIdleTimer = null;
409
+ }
410
+ turn.reject(new Error(`claude produced no jsonl output within ${this.firstEventTimeoutMs}ms of submit (session may have failed to start)`));
411
+ this.kill();
412
+ }, this.firstEventTimeoutMs);
413
+ if (typeof this.firstEventTimer.unref === 'function')
414
+ this.firstEventTimer.unref();
415
+ }
416
+ clearFirstEventWatchdog() {
417
+ if (this.firstEventTimer) {
418
+ clearTimeout(this.firstEventTimer);
419
+ this.firstEventTimer = null;
420
+ }
421
+ }
345
422
  // -----------------------------------------------------------------------------
346
423
  // Shutdown
347
424
  // -----------------------------------------------------------------------------
@@ -352,6 +429,7 @@ export class ClaudeTuiSession {
352
429
  clearTimeout(this.maxTimer);
353
430
  if (this.turnIdleTimer)
354
431
  clearTimeout(this.turnIdleTimer);
432
+ this.clearFirstEventWatchdog();
355
433
  this.idleTimer = this.maxTimer = this.turnIdleTimer = null;
356
434
  this.alive = false;
357
435
  if (this.tail) {
@@ -372,6 +450,7 @@ export class ClaudeTuiSession {
372
450
  clearTimeout(this.maxTimer);
373
451
  if (this.turnIdleTimer)
374
452
  clearTimeout(this.turnIdleTimer);
453
+ this.clearFirstEventWatchdog();
375
454
  this.idleTimer = this.maxTimer = this.turnIdleTimer = null;
376
455
  const wasAlive = this.alive;
377
456
  this.alive = false;