@cortex-agent/server 2026.7.30 → 2026.8.3-2

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 (353) hide show
  1. package/README.md +1 -1
  2. package/defaults/CORTEX.md +1 -0
  3. package/defaults/config/CORTEX.md +2 -1
  4. package/defaults/config/hooks/13-status-md-guard.json +11 -0
  5. package/defaults/config/hooks/CORTEX.md +1 -0
  6. package/defaults/config/mcp-config-empty.json +3 -0
  7. package/defaults/config/thread-templates/agents/benchmark-coder.json +22 -0
  8. package/defaults/config/thread-templates/agents/benchmark-reviewer.json +22 -0
  9. package/defaults/config/thread-templates/agents/coder-reviewer.json +4 -9
  10. package/defaults/config/thread-templates/agents/coder.json +4 -14
  11. package/defaults/config/thread-templates/templates/benchmark-coder-review.json +37 -0
  12. package/defaults/config/thread-templates/templates/coder-review.json +3 -27
  13. package/defaults/context/projects/CORTEX.md +1 -1
  14. package/defaults/data/schedules.json +12 -0
  15. package/defaults/hooks/CORTEX.md +1 -0
  16. package/defaults/hooks/new-session-hook.mjs +2 -2
  17. package/defaults/hooks/status-md-guard.mjs +193 -0
  18. package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +1 -1
  19. package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +28 -2
  20. package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +1 -1
  21. package/defaults/plugins/cortex-common/skills/compound/SKILL.md +1 -1
  22. package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +4 -2
  23. package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +1 -1
  24. package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +1 -1
  25. package/defaults/plugins/cortex-stage-gate/skills/director-method/SKILL.md +1 -1
  26. package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +1 -0
  27. package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +2 -2
  28. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +11 -8
  29. package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +1 -1
  30. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +13 -16
  31. package/defaults/prompts/directives/coder-reviewer.md +24 -20
  32. package/defaults/prompts/directives/coder.md +4 -5
  33. package/defaults/prompts/directives/director.md +4 -10
  34. package/defaults/prompts/directives/manager.md +9 -10
  35. package/defaults/prompts/systemPrompts/worker.md +2 -2
  36. package/defaults/rules/cortex-md.md +31 -0
  37. package/defaults/rules/experiment-format.md +8 -1
  38. package/defaults/rules/issues-md.md +10 -9
  39. package/defaults/rules/meta-conventions.md +5 -4
  40. package/defaults/rules/mission-md.md +2 -1
  41. package/defaults/rules/status-md.md +39 -21
  42. package/dist/agent-adapter/bg-wait.d.ts +10 -12
  43. package/dist/agent-adapter/bg-wait.js +209 -129
  44. package/dist/agent-adapter/claude/adapter-tui.d.ts +3 -1
  45. package/dist/agent-adapter/claude/adapter-tui.js +8 -5
  46. package/dist/agent-adapter/claude/adapter.d.ts +43 -14
  47. package/dist/agent-adapter/claude/adapter.js +276 -161
  48. package/dist/agent-adapter/claude/defaults.d.ts +2 -0
  49. package/dist/agent-adapter/claude/defaults.js +5 -5
  50. package/dist/agent-adapter/claude/event-parser.d.ts +3 -8
  51. package/dist/agent-adapter/claude/event-parser.js +28 -31
  52. package/dist/agent-adapter/claude/hooks-builder.js +4 -3
  53. package/dist/agent-adapter/claude/jsonl-tail.js +54 -35
  54. package/dist/agent-adapter/claude/spawn-args.d.ts +15 -12
  55. package/dist/agent-adapter/claude/spawn-args.js +44 -38
  56. package/dist/agent-adapter/claude/tmux-control.d.ts +4 -17
  57. package/dist/agent-adapter/claude/tmux-control.js +39 -32
  58. package/dist/agent-adapter/event-tee.d.ts +19 -0
  59. package/dist/agent-adapter/event-tee.js +145 -0
  60. package/dist/agent-adapter/index.d.ts +1 -0
  61. package/dist/agent-adapter/index.js +7 -3
  62. package/dist/agent-adapter/normalize/event-types.d.ts +17 -9
  63. package/dist/agent-adapter/normalize/event-types.js +4 -4
  64. package/dist/agent-adapter/pi/adapter.d.ts +16 -4
  65. package/dist/agent-adapter/pi/adapter.js +69 -36
  66. package/dist/agent-adapter/pi/discovery.d.ts +19 -3
  67. package/dist/agent-adapter/pi/discovery.js +81 -43
  68. package/dist/agent-adapter/pi/event-parser.js +4 -2
  69. package/dist/agent-adapter/pi/spawn-args.d.ts +2 -4
  70. package/dist/agent-adapter/pi/spawn-args.js +6 -5
  71. package/dist/agent-adapter/types.d.ts +43 -2
  72. package/dist/agent-adapter/types.js +8 -4
  73. package/dist/core/atomic-write.d.ts +6 -1
  74. package/dist/core/atomic-write.js +183 -7
  75. package/dist/core/cli-utils.d.ts +15 -2
  76. package/dist/core/cli-utils.js +46 -41
  77. package/dist/core/config-generator.d.ts +4 -0
  78. package/dist/core/config-generator.js +34 -21
  79. package/dist/core/json-repository.d.ts +4 -0
  80. package/dist/core/json-repository.js +6 -3
  81. package/dist/core/locales/en.d.ts +94 -0
  82. package/dist/core/locales/slices/commands.d.ts +76 -0
  83. package/dist/core/locales/slices/commands.js +155 -1
  84. package/dist/core/locales/slices/status.d.ts +18 -0
  85. package/dist/core/locales/slices/status.js +43 -2
  86. package/dist/core/log.d.ts +5 -0
  87. package/dist/core/log.js +25 -23
  88. package/dist/core/pi-session-filename.d.ts +2 -0
  89. package/dist/core/pi-session-filename.js +18 -0
  90. package/dist/core/resume-reminder.d.ts +5 -0
  91. package/dist/core/resume-reminder.js +18 -0
  92. package/dist/core/runtime-env.d.ts +1 -0
  93. package/dist/core/runtime-env.js +15 -0
  94. package/dist/core/settings-migration.d.ts +5 -0
  95. package/dist/core/settings-migration.js +128 -0
  96. package/dist/core/settings-spec.d.ts +174 -0
  97. package/dist/core/settings-spec.js +150 -0
  98. package/dist/core/settings.d.ts +10 -0
  99. package/dist/core/settings.js +235 -0
  100. package/dist/core/task-parser.d.ts +11 -1
  101. package/dist/core/task-parser.js +34 -3
  102. package/dist/core/types/agent-types.d.ts +19 -0
  103. package/dist/core/types/agent-types.js +1 -1
  104. package/dist/core/types/thread-types.d.ts +48 -3
  105. package/dist/core/types/thread-types.js +2 -2
  106. package/dist/core/utils.d.ts +21 -1
  107. package/dist/core/utils.js +37 -1
  108. package/dist/domain/agent-run/access-probe-cli.d.ts +7 -0
  109. package/dist/domain/agent-run/access-probe-cli.js +139 -0
  110. package/dist/domain/agent-run/access-probe-policy.d.ts +61 -0
  111. package/dist/domain/agent-run/access-probe-policy.js +614 -0
  112. package/dist/domain/agent-run/access-probe.d.ts +21 -0
  113. package/dist/domain/agent-run/access-probe.js +194 -0
  114. package/dist/domain/agent-run/agent-run-cli.d.ts +19 -0
  115. package/dist/domain/agent-run/agent-run-cli.js +171 -0
  116. package/dist/domain/agent-run/atif.d.ts +54 -0
  117. package/dist/domain/agent-run/atif.js +211 -0
  118. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +32 -0
  119. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +616 -0
  120. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +34 -0
  121. package/dist/domain/agent-run/benchmark-thread-identity.js +106 -0
  122. package/dist/domain/agent-run/identity.d.ts +62 -0
  123. package/dist/domain/agent-run/identity.js +118 -0
  124. package/dist/domain/agent-run/journal.d.ts +51 -0
  125. package/dist/domain/agent-run/journal.js +259 -0
  126. package/dist/domain/agent-run/manifest-contract.d.ts +44 -0
  127. package/dist/domain/agent-run/manifest-contract.js +134 -0
  128. package/dist/domain/agent-run/manifest.d.ts +51 -0
  129. package/dist/domain/agent-run/manifest.js +801 -0
  130. package/dist/domain/agent-run/pinned-node-process.d.ts +35 -0
  131. package/dist/domain/agent-run/pinned-node-process.js +206 -0
  132. package/dist/domain/agent-run/role-surface.d.ts +4 -0
  133. package/dist/domain/agent-run/role-surface.js +99 -0
  134. package/dist/domain/agent-run/run-config.d.ts +22 -0
  135. package/dist/domain/agent-run/run-config.js +135 -0
  136. package/dist/domain/agent-run/runner.d.ts +7 -0
  137. package/dist/domain/agent-run/runner.js +518 -0
  138. package/dist/domain/agent-run/supervisor.d.ts +78 -0
  139. package/dist/domain/agent-run/supervisor.js +425 -0
  140. package/dist/domain/agent-run/trajectory-merge-cli.d.ts +11 -0
  141. package/dist/domain/agent-run/trajectory-merge-cli.js +111 -0
  142. package/dist/domain/agent-run/trajectory-merge.d.ts +39 -0
  143. package/dist/domain/agent-run/trajectory-merge.js +505 -0
  144. package/dist/domain/agents/config.d.ts +10 -0
  145. package/dist/domain/agents/config.js +149 -44
  146. package/dist/domain/agents/facade.d.ts +42 -7
  147. package/dist/domain/agents/facade.js +174 -170
  148. package/dist/domain/agents/provider-run-lifecycle.d.ts +18 -0
  149. package/dist/domain/agents/provider-run-lifecycle.js +60 -0
  150. package/dist/domain/auth/auth-events.d.ts +18 -0
  151. package/dist/domain/auth/auth-events.js +38 -0
  152. package/dist/domain/auth/auth-format.d.ts +2 -0
  153. package/dist/domain/auth/auth-format.js +58 -0
  154. package/dist/domain/auth/auth-status.d.ts +61 -0
  155. package/dist/domain/auth/auth-status.js +304 -0
  156. package/dist/domain/auth/auth-watch.d.ts +16 -0
  157. package/dist/domain/auth/auth-watch.js +125 -0
  158. package/dist/domain/auth/cc-login.d.ts +7 -0
  159. package/dist/domain/auth/cc-login.js +16 -0
  160. package/dist/domain/auth/cc-subscription.d.ts +38 -0
  161. package/dist/domain/auth/cc-subscription.js +204 -0
  162. package/dist/domain/auth/index.d.ts +12 -0
  163. package/dist/domain/auth/index.js +16 -0
  164. package/dist/domain/auth/login-flow.d.ts +120 -0
  165. package/dist/domain/auth/login-flow.js +253 -0
  166. package/dist/domain/auth/login-service.d.ts +32 -0
  167. package/dist/domain/auth/login-service.js +97 -0
  168. package/dist/domain/auth/logout.d.ts +32 -0
  169. package/dist/domain/auth/logout.js +123 -0
  170. package/dist/domain/auth/pi-login.d.ts +36 -0
  171. package/dist/domain/auth/pi-login.js +72 -0
  172. package/dist/domain/auth/pi-oauth.d.ts +36 -0
  173. package/dist/domain/auth/pi-oauth.js +84 -0
  174. package/dist/domain/auth/pi-runtime.d.ts +72 -0
  175. package/dist/domain/auth/pi-runtime.js +86 -0
  176. package/dist/domain/mcp/benchmark-thread-server.d.ts +1 -0
  177. package/dist/domain/mcp/benchmark-thread-server.js +26 -0
  178. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +23 -0
  179. package/dist/domain/mcp/tools/benchmark-thread-run.js +146 -0
  180. package/dist/domain/memory/user-context.js +6 -8
  181. package/dist/domain/monitor/disk-monitor.js +47 -16
  182. package/dist/domain/projects/project-store.js +23 -6
  183. package/dist/domain/remote/client-hot-reload.d.ts +9 -1
  184. package/dist/domain/remote/client-hot-reload.js +60 -12
  185. package/dist/domain/remote/client-manager.js +12 -6
  186. package/dist/domain/scheduling/jobs/auth-expiry-scan.d.ts +14 -0
  187. package/dist/domain/scheduling/jobs/auth-expiry-scan.js +86 -0
  188. package/dist/domain/scheduling/jobs/task-dispatch.js +36 -40
  189. package/dist/domain/scheduling/runner.d.ts +2 -0
  190. package/dist/domain/scheduling/runner.js +7 -4
  191. package/dist/domain/sessions/session-backup.d.ts +14 -20
  192. package/dist/domain/sessions/session-backup.js +57 -68
  193. package/dist/domain/system/doctor.d.ts +4 -0
  194. package/dist/domain/system/doctor.js +113 -28
  195. package/dist/domain/system/install-cli.js +8 -3
  196. package/dist/domain/system/server-update-check.js +7 -5
  197. package/dist/domain/system/system-notice.d.ts +3 -1
  198. package/dist/domain/system/system-notice.js +6 -11
  199. package/dist/domain/tasks/archiver.d.ts +1 -0
  200. package/dist/domain/tasks/archiver.js +13 -7
  201. package/dist/domain/tasks/claim-recovery.d.ts +3 -3
  202. package/dist/domain/tasks/claim-recovery.js +12 -8
  203. package/dist/domain/tasks/dispatch-utils.d.ts +15 -14
  204. package/dist/domain/tasks/dispatch-utils.js +22 -18
  205. package/dist/domain/tasks/dispatcher.d.ts +1 -0
  206. package/dist/domain/tasks/dispatcher.js +9 -5
  207. package/dist/domain/tasks/mutator.d.ts +21 -11
  208. package/dist/domain/tasks/mutator.js +30 -24
  209. package/dist/domain/tasks/pending-tracker.d.ts +5 -2
  210. package/dist/domain/tasks/pending-tracker.js +11 -5
  211. package/dist/domain/tasks/system/cortex-run.d.ts +2 -1
  212. package/dist/domain/tasks/system/cortex-run.js +24 -4
  213. package/dist/domain/tasks/system/task-cli.d.ts +1 -0
  214. package/dist/domain/tasks/system/task-cli.js +72 -22
  215. package/dist/domain/tasks/system/task-completion.d.ts +19 -2
  216. package/dist/domain/tasks/system/task-completion.js +31 -17
  217. package/dist/domain/tasks/system/task-file-input.d.ts +10 -0
  218. package/dist/domain/tasks/system/task-file-input.js +57 -0
  219. package/dist/domain/tasks/system/task-id-utils.d.ts +9 -9
  220. package/dist/domain/tasks/system/task-id-utils.js +13 -4
  221. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -2
  222. package/dist/domain/tasks/system/task-lifecycle-edit.js +200 -6
  223. package/dist/domain/tasks/system/task-lock.js +19 -5
  224. package/dist/domain/tasks/system/task-mutations.d.ts +22 -12
  225. package/dist/domain/tasks/system/task-mutations.js +28 -4
  226. package/dist/domain/tasks/system/task-process.js +10 -8
  227. package/dist/domain/tasks/system/task-state.d.ts +65 -11
  228. package/dist/domain/tasks/system/task-state.js +86 -13
  229. package/dist/domain/threads/local-runtime-deps.d.ts +32 -0
  230. package/dist/domain/threads/local-runtime-deps.js +91 -0
  231. package/dist/domain/threads/local-runtime-scope.d.ts +6 -0
  232. package/dist/domain/threads/local-runtime-scope.js +12 -0
  233. package/dist/domain/threads/pending-user-inputs.d.ts +3 -0
  234. package/dist/domain/threads/pending-user-inputs.js +37 -0
  235. package/dist/domain/threads/prompt-builder.d.ts +12 -1
  236. package/dist/domain/threads/prompt-builder.js +73 -26
  237. package/dist/domain/threads/runner.d.ts +15 -3
  238. package/dist/domain/threads/runner.js +261 -105
  239. package/dist/domain/threads/state-machine.d.ts +1 -1
  240. package/dist/domain/threads/state-machine.js +17 -8
  241. package/dist/domain/ui-service/app-router.d.ts +86 -6
  242. package/dist/domain/ui-service/app-router.js +171 -133
  243. package/dist/domain/ui-service/input-schemas.d.ts +132 -10
  244. package/dist/domain/ui-service/input-schemas.js +59 -5
  245. package/dist/domain/ui-service/mutate/approvals.d.ts +2 -1
  246. package/dist/domain/ui-service/mutate/approvals.js +2 -1
  247. package/dist/domain/ui-service/mutate/auth.d.ts +6 -0
  248. package/dist/domain/ui-service/mutate/auth.js +83 -0
  249. package/dist/domain/ui-service/mutate/config.js +11 -10
  250. package/dist/domain/ui-service/query/approvals.js +3 -0
  251. package/dist/domain/ui-service/query/auth.d.ts +6 -0
  252. package/dist/domain/ui-service/query/auth.js +12 -0
  253. package/dist/domain/ui-service/query/config.d.ts +5 -5
  254. package/dist/domain/ui-service/query/config.js +27 -17
  255. package/dist/domain/ui-service/query/tasks.d.ts +1 -1
  256. package/dist/domain/ui-service/query/tasks.js +69 -30
  257. package/dist/domain/ui-service/query/threads.js +3 -3
  258. package/dist/domain/ui-service/types.d.ts +67 -8
  259. package/dist/domain/ui-service/types.js +2 -2
  260. package/dist/domain/ui-service/ui-service.js +16 -2
  261. package/dist/entry/admin-channel-hot-reload.d.ts +4 -0
  262. package/dist/entry/admin-channel-hot-reload.js +22 -0
  263. package/dist/entry/app.js +38 -38
  264. package/dist/entry/auth-cli.d.ts +10 -0
  265. package/dist/entry/auth-cli.js +52 -0
  266. package/dist/entry/cli-help.d.ts +5 -0
  267. package/dist/entry/cli-help.js +130 -0
  268. package/dist/entry/cli.d.ts +5 -5
  269. package/dist/entry/cli.js +174 -248
  270. package/dist/entry/daemon.d.ts +11 -0
  271. package/dist/entry/daemon.js +204 -103
  272. package/dist/entry/draft-attachments.d.ts +8 -0
  273. package/dist/entry/draft-attachments.js +83 -0
  274. package/dist/entry/feishu-login.d.ts +2 -6
  275. package/dist/entry/feishu-login.js +16 -21
  276. package/dist/entry/init.js +6 -4
  277. package/dist/entry/start-ui-http.d.ts +2 -8
  278. package/dist/entry/start-ui-http.js +7 -34
  279. package/dist/events/event-logger.js +11 -13
  280. package/dist/events/event-types.d.ts +19 -1
  281. package/dist/events/event-types.js +3 -3
  282. package/dist/events/index.d.ts +1 -1
  283. package/dist/events/index.js +3 -3
  284. package/dist/hooks/new-session-hook.mjs +2 -2
  285. package/dist/hooks/status-md-guard.mjs +193 -0
  286. package/dist/orchestration/agent-file-send.js +44 -14
  287. package/dist/orchestration/agent-runner.d.ts +7 -3
  288. package/dist/orchestration/agent-runner.js +65 -41
  289. package/dist/orchestration/conversation-runner.d.ts +5 -1
  290. package/dist/orchestration/conversation-runner.js +16 -7
  291. package/dist/orchestration/lifecycle.d.ts +23 -1
  292. package/dist/orchestration/lifecycle.js +103 -40
  293. package/dist/orchestration/mid-turn-inject.d.ts +2 -0
  294. package/dist/orchestration/mid-turn-inject.js +29 -13
  295. package/dist/orchestration/resume-dispatcher.d.ts +3 -5
  296. package/dist/orchestration/resume-dispatcher.js +9 -17
  297. package/dist/orchestration/routing/commands/index.d.ts +4 -1
  298. package/dist/orchestration/routing/commands/index.js +83 -61
  299. package/dist/orchestration/routing/commands/login-notice.d.ts +21 -0
  300. package/dist/orchestration/routing/commands/login-notice.js +97 -0
  301. package/dist/orchestration/routing/commands/login.d.ts +12 -0
  302. package/dist/orchestration/routing/commands/login.js +555 -0
  303. package/dist/orchestration/routing/commands/status.js +45 -59
  304. package/dist/orchestration/routing/edit-handler.d.ts +5 -0
  305. package/dist/orchestration/routing/edit-handler.js +127 -73
  306. package/dist/orchestration/routing/webhook.js +5 -4
  307. package/dist/orchestration/session-rewind.d.ts +5 -1
  308. package/dist/orchestration/session-rewind.js +106 -62
  309. package/dist/orchestration/session-send.d.ts +2 -0
  310. package/dist/orchestration/session-send.js +5 -6
  311. package/dist/orchestration/status-helpers.d.ts +1 -2
  312. package/dist/orchestration/status-helpers.js +7 -10
  313. package/dist/orchestration/thread-callback.d.ts +19 -11
  314. package/dist/orchestration/thread-callback.js +132 -61
  315. package/dist/orchestration/thread-executor.js +37 -27
  316. package/dist/orchestration/turn-mutation-lock.d.ts +3 -0
  317. package/dist/orchestration/turn-mutation-lock.js +36 -0
  318. package/dist/orchestration/turn-notify.d.ts +2 -5
  319. package/dist/orchestration/turn-notify.js +9 -21
  320. package/dist/platform/adapter.d.ts +1 -0
  321. package/dist/platform/adapter.js +2 -2
  322. package/dist/platform/adapters/composite-adapter.d.ts +2 -0
  323. package/dist/platform/adapters/composite-adapter.js +13 -3
  324. package/dist/platform/adapters/feishu.d.ts +2 -4
  325. package/dist/platform/adapters/feishu.js +38 -59
  326. package/dist/platform/adapters/index.d.ts +1 -1
  327. package/dist/platform/adapters/index.js +13 -12
  328. package/dist/platform/adapters/slack.d.ts +1 -1
  329. package/dist/platform/adapters/slack.js +12 -35
  330. package/dist/platform/index.d.ts +2 -1
  331. package/dist/platform/index.js +3 -3
  332. package/dist/platform/testing.d.ts +1 -0
  333. package/dist/platform/testing.js +13 -4
  334. package/dist/platform/tool-trace.js +6 -11
  335. package/dist/platform/ui-http/ui-http-server.d.ts +1 -1
  336. package/dist/platform/ui-http/ui-http-server.js +6 -18
  337. package/dist/store/execution-repo.d.ts +17 -1
  338. package/dist/store/execution-repo.js +55 -4
  339. package/dist/store/prompt-migration-replacements.d.ts +4 -0
  340. package/dist/store/prompt-migration-replacements.js +149 -0
  341. package/dist/store/thread-repo.d.ts +15 -4
  342. package/dist/store/thread-repo.js +61 -24
  343. package/dist/store/version-migrations.js +36 -1
  344. package/native/cortex-supervisor/dist/build-manifest.json +22 -0
  345. package/native/cortex-supervisor/dist/cortex-supervisor +0 -0
  346. package/package.json +5 -2
  347. package/web/dist/assets/index-XqBCYtkw.js +139 -0
  348. package/web/dist/assets/index-zpf3OSKC.css +1 -0
  349. package/web/dist/index.html +2 -2
  350. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.d.ts +0 -1
  351. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.js +0 -78
  352. package/web/dist/assets/index-B19jLgji.js +0 -138
  353. package/web/dist/assets/index-BuFyPyRW.css +0 -1
@@ -1,4 +1,4 @@
1
- import { type Task } from '../core/task-parser.js';
1
+ import { type Task, type TaskGenerationExpectation } from '../core/task-parser.js';
2
2
  import type { ThreadRecord, RunThreadOptions } from '../core/types/thread-types.js';
3
3
  import type { PlatformAdapter } from '../platform/index.js';
4
4
  import type { IncomingMessage } from '../platform/index.js';
@@ -62,14 +62,10 @@ export declare function notifyThreadParent(childId: string, deps?: {
62
62
  * completed → acceptance instructions (verify the deliverable, never the report);
63
63
  * blocked → escalation instructions (the child cannot finish on its own). */
64
64
  export declare function buildTaskResultNotice(task: Task, kind: 'completed' | 'blocked'): string;
65
- /** Event-bridge entry: a task completed or got blocked — wake every manager thread waiting
66
- * on it. For 'completed', the task's real status is verified on disk first: the dispatch
67
- * cycle publishes task.completed loosely (thread ended ≠ task done), so the disk state is
68
- * the source of truth. A rejected bogus event keeps the manager waiting; the genuine
69
- * completion publishes again later. */
65
+ /** Verify task provenance while holding its mutation lock, then wake waiting managers. */
70
66
  export declare function notifyTaskParentThreads(taskId: string, kind: 'completed' | 'blocked', deps?: {
71
67
  resume?: ResumeFn;
72
- }): Promise<void>;
68
+ }, ownership?: TaskGenerationExpectation): Promise<void>;
73
69
  type WakeFn = (channel: string, notice: string) => void | Promise<void>;
74
70
  /** Wake (or create) the session on a channel by routing a synthetic user message — the same
75
71
  * mechanism the interactive thread-parent path uses. Shared by thread completion (fireThreadCallback),
@@ -80,14 +76,25 @@ type WakeFn = (channel: string, notice: string) => void | Promise<void>;
80
76
  * skip) and tests can stay in sync with the exact synthetic shape by construction. */
81
77
  export declare function buildSyntheticWakeMessage(channel: string, notice: string, tag: string): IncomingMessage;
82
78
  export declare function wakeSession(channel: string, notice: string, tag: string): Promise<void>;
79
+ /** Human-facing project-channel notice for a fire-and-forget task queued from inside a thread:
80
+ * the thread has (most likely) ended and never consumes the result, so nobody is woken —
81
+ * the outcome just surfaces in the project's report stream. */
82
+ export declare function buildThreadOriginTaskNotice(task: Task, kind: 'completed' | 'blocked'): string;
83
+ type PostNoticeFn = (projectId: string, text: string) => void | Promise<void>;
83
84
  /** Session→task wake (Problem 1): when a task created by an interactive session/agent turns
84
85
  * terminal, route a notice back to its origin channel. Default-on, no fallback — if origin_channel
85
86
  * is set we always wake it. Mutually exclusive with the thread-parent path: if any thread is
86
87
  * currently waiting on this task (waitingOnTasks), that path owns the result and we defer.
87
- * `wake` is injectable for testing (mirrors the `resume` injection on notifyTaskParentThreads). */
88
+ * Thread-origin tasks (origin_thread_id set — fire-and-forget adds from inside a thread) never
89
+ * wake a session: the creating thread has likely ended, and its recorded channel is an
90
+ * unattended dispatch conduit; the result degrades to a durable project-report notice instead.
91
+ * origin_thread_id takes precedence over origin_channel so legacy tasks that captured both
92
+ * are fixed retroactively. `wake`/`postNotice` are injectable for testing (mirrors the
93
+ * `resume` injection on notifyTaskParentThreads). */
88
94
  export declare function notifyTaskOriginSession(taskId: string, kind: 'completed' | 'blocked', deps?: {
89
95
  wake?: WakeFn;
90
- }): Promise<void>;
96
+ postNotice?: PostNoticeFn;
97
+ }, ownership?: TaskGenerationExpectation): Promise<void>;
91
98
  /** Sweep one waiting thread's waitingOnTasks against disk state: deliver already-done and
92
99
  * already-blocked children, drop missing ones, keep open ones. Closes the race window
93
100
  * where a child task turns terminal between the suspension snapshot and the waiting
@@ -112,10 +119,12 @@ export declare function closeResumedTaskLoop(threadId: string, deps?: {
112
119
  publish?: (e: {
113
120
  type: 'task.completed';
114
121
  taskId: string;
122
+ dispatchGeneration?: string | null;
115
123
  } | {
116
124
  type: 'task.blocked';
117
125
  taskId: string;
118
126
  reason: string;
127
+ dispatchGeneration?: string | null;
119
128
  }) => void;
120
129
  }): Promise<void>;
121
130
  /** Periodic disk-driven backstop: reconcile EVERY suspended manager's task children against disk
@@ -130,8 +139,7 @@ export declare function closeResumedTaskLoop(threadId: string, deps?: {
130
139
  export declare function sweepWaitingManagers(deps?: {
131
140
  resume?: ResumeFn;
132
141
  }): Promise<number>;
133
- /** Start the periodic waiting-manager sweep (thin setInterval wrapper, mirrors
134
- * startDispatchReconciler). No-op when the interval is 0. */
142
+ /** Start the periodic waiting-manager sweep. No-op when the startup interval is disabled. */
135
143
  export declare function startWaitingManagerSweep(): void;
136
144
  /** Register the EventBus subscribers that wake suspended manager threads on child-task
137
145
  * terminal events (DR-0014 §8). Call once at startup, before recoverWaitingThreads. */
@@ -1,5 +1,5 @@
1
- // input: thread store, agent runner, outbound queue, adapter
2
- // output: task callbacks, framed notices, persisted thread resumes
1
+ // input: thread store, task generations, runner, outbound queue
2
+ // output: fenced callbacks, resumes, rotation, waiting sweeps
3
3
  // pos: Delivers child results and resumes suspended parents
4
4
  // >>> If I am updated, update my header comment and parent CORTEX.md <<<
5
5
  import { threadStore } from '../store/thread-repo.js';
@@ -11,8 +11,10 @@ import { sealThreadStatus } from './status-helpers.js';
11
11
  import { isTerminalStatus } from '../domain/threads/tree.js';
12
12
  import { runThreadDetached } from './thread-executor.js';
13
13
  import { createLogger } from '../core/log.js';
14
- import { scanAllTasks } from '../core/task-parser.js';
14
+ import { getSettings } from '../core/settings.js';
15
+ import { scanAllTasks, } from '../core/task-parser.js';
15
16
  import { recordDelivered, pendingDeliveries } from '../domain/tasks/acceptance-ledger.js';
17
+ import { withTaskFileMutationLockAsync } from '../domain/tasks/system/task-lifecycle-edit.js';
16
18
  import { isTaskArtifactTemplate } from '../domain/threads/index.js';
17
19
  import { SYNTHETIC_CALLBACK_SENDER } from '../platform/types.js';
18
20
  const log = createLogger('thread-callback');
@@ -64,18 +66,18 @@ export function buildChildResultNotice(child) {
64
66
  lines.push('Acceptance (mandatory — do NOT trust the child\'s self-reported summary):');
65
67
  lines.push('1. Read the actual deliverable; check it against done_when item by item; for code, run the tests.');
66
68
  lines.push('2. Passes → distill the key conclusions into your artifact and continue your plan.');
67
- lines.push('3. Fails → write out the expected/actual gap and your failure hypothesis; if CORTEX_TASK_ID is set, create a replacement child with cortex-task spawn and call thread_wait; otherwise call thread_abort.');
69
+ lines.push('3. Fails → write out the expected/actual gap and your failure hypothesis; if CORTEX_TASK_ID is set, use the Write tool to stage child JSON at a per-task unique path, run cortex-task spawn --task-file <path>, and call thread_wait; otherwise call thread_abort.');
68
70
  lines.push('4. Cannot judge, or a directional question → call the thread_abort tool (with a one-line diagnosis) to escalate to your manager.');
69
71
  return lines.join('\n');
70
72
  }
71
- /** Durable degraded-path notice to the project-report channel. */
72
- async function postProjectNotice(t, text) {
73
+ /** Durable notice to a project's report channel (falls back to a direct post without a queue). */
74
+ async function postProjectNoticeTo(projectId, trigger, text) {
73
75
  const adapter = jobCtx.adapter;
74
76
  if (!adapter) {
75
- log.error(`no adapter; cannot post notice for ${t.id}`);
77
+ log.error(`no adapter; cannot post project notice for ${projectId}`);
76
78
  return;
77
79
  }
78
- const dest = { type: 'project-report', projectId: t.projectId, trigger: 'mcp-thread', sessionId: '' };
80
+ const dest = { type: 'project-report', projectId, trigger, sessionId: '' };
79
81
  const queue = getOutboundQueue();
80
82
  if (queue) {
81
83
  await durablePost(queue, adapter, dest, { text });
@@ -84,6 +86,10 @@ async function postProjectNotice(t, text) {
84
86
  await adapter.postMessage(dest, { text });
85
87
  }
86
88
  }
89
+ /** Durable degraded-path notice to the project-report channel. */
90
+ async function postProjectNotice(t, text) {
91
+ await postProjectNoticeTo(t.projectId, 'mcp-thread', text);
92
+ }
87
93
  /** Rebuild run options for a suspended or provider-paused thread.
88
94
  * Restore the persisted status message so resumed updates target the original message.
89
95
  * Lifecycle hooks are resolved by the HookBus from the thread's persisted metadata. */
@@ -170,10 +176,9 @@ export function resumeManagerForQuestion(managerThreadId, resume) {
170
176
  (resume ?? defaultResume)(managerThreadId);
171
177
  }
172
178
  // --- Manager session rotation (DR-0017 W3) ---
173
- /** CORTEX_MANAGER_ROTATE_STEPS (default 10) — steps per manager session before rotation. */
179
+ /** Configured steps per manager session before rotation. */
174
180
  function rotateStepsThreshold() {
175
- const v = parseInt(process.env.CORTEX_MANAGER_ROTATE_STEPS || '', 10);
176
- return Number.isFinite(v) && v > 0 ? v : 10;
181
+ return getSettings().managerRotateSteps;
177
182
  }
178
183
  /** Rehydration notice for a freshly rotated manager incarnation: durable artifact first,
179
184
  * tree reconcile second, ledger-pending acceptances third. Mirrors the disaster-join
@@ -213,7 +218,8 @@ export async function maybeRotateManager(threadId) {
213
218
  return false;
214
219
  const base = parent.metadata?.rotationBaseStepIndex ?? 0;
215
220
  const since = parent.steps.length - base;
216
- if (since < rotateStepsThreshold())
221
+ const threshold = rotateStepsThreshold();
222
+ if (since < threshold)
217
223
  return false;
218
224
  const notice = buildRehydrationNotice(parent, since);
219
225
  await threadStore.mutate(threadId, (t) => {
@@ -231,7 +237,7 @@ export async function maybeRotateManager(threadId) {
231
237
  m.pendingMessages.shift();
232
238
  m.pendingMessages.push(notice);
233
239
  });
234
- log.info(`rotated manager ${threadId}: fresh session after ${since} steps (threshold ${rotateStepsThreshold()})`);
240
+ log.info(`rotated manager ${threadId}: fresh session after ${since} steps (threshold ${threshold})`);
235
241
  return true;
236
242
  }
237
243
  // --- Wait-set deadlock guard (2026-07-21) ---
@@ -394,6 +400,7 @@ export async function notifyThreadParent(childId, deps = {}) {
394
400
  await maybeResumeParent(parentId, deps.resume);
395
401
  }
396
402
  // --- Task-children bridge (DR-0014 §8: resident manager waits on child TASKS) ---
403
+ const SAFE_TASK_CHILD_CREATION = 'For verifier or replacement children, use the Write tool to stage JSON at a per-task unique path, then run cortex-task spawn --task-file <path>; never place task prose in shell arguments.';
397
404
  /** Child-task result notice delivered into a suspended manager's pendingMessages.
398
405
  * completed → acceptance instructions (verify the deliverable, never the report);
399
406
  * blocked → escalation instructions (the child cannot finish on its own). */
@@ -421,6 +428,7 @@ export function buildTaskResultNotice(task, kind) {
421
428
  lines.push('2. Fixable → cortex-task unblock and revise the task description/done_when, or rebuild a revised subtask (decompose --keep-parent), then call thread_wait.');
422
429
  lines.push('3. Beyond your authority or a directional question → call the thread_abort tool (with a one-line diagnosis) to escalate upward.');
423
430
  }
431
+ lines.push('', SAFE_TASK_CHILD_CREATION);
424
432
  return lines.join('\n');
425
433
  }
426
434
  /** Disk-fresh read of one task (zero-dependency core parser — consistent with the
@@ -433,6 +441,10 @@ function readTaskFromDisk(project, taskId) {
433
441
  return null;
434
442
  }
435
443
  }
444
+ function matchesTaskGeneration(task, ownership) {
445
+ return !ownership || task.dispatch_generation === ownership.generation
446
+ || (task.status === 'done' && task.dispatch_generation === null);
447
+ }
436
448
  /** Deliver one child-task result to one waiting manager thread. Returns true if delivered.
437
449
  * Same-incarnation idempotency rides the persistent deliveredChildResults array (4-hex
438
450
  * task ids cannot collide with thr_ thread ids). Cross-incarnation idempotency (DR-0017
@@ -481,32 +493,37 @@ async function deliverTaskResult(parentThreadId, task, kind, deps) {
481
493
  await maybeResumeParent(parentThreadId, deps.resume);
482
494
  return delivered;
483
495
  }
484
- /** Event-bridge entry: a task completed or got blocked — wake every manager thread waiting
485
- * on it. For 'completed', the task's real status is verified on disk first: the dispatch
486
- * cycle publishes task.completed loosely (thread ended ≠ task done), so the disk state is
487
- * the source of truth. A rejected bogus event keeps the manager waiting; the genuine
488
- * completion publishes again later. */
489
- export async function notifyTaskParentThreads(taskId, kind, deps = {}) {
490
- for (const parent of threadStore.getAll()) {
491
- if (parent.status !== 'waiting')
492
- continue;
493
- if (!parent.metadata?.waitingOnTasks?.includes(taskId))
494
- continue;
495
- const project = parent.metadata?.taskProject || parent.projectId;
496
+ async function deliverCurrentTaskResult(parent, taskId, kind, deps, ownership) {
497
+ const project = parent.metadata?.taskProject || parent.projectId;
498
+ await withTaskFileMutationLockAsync(project, async () => {
496
499
  const task = readTaskFromDisk(project, taskId);
497
500
  if (!task) {
498
- log.warn(`task ${taskId} not found on disk for waiting manager ${parent.id} — leaving to reconcile/recovery`);
499
- continue;
501
+ log.warn(`task ${taskId} missing for waiting manager ${parent.id}`);
502
+ return;
500
503
  }
501
504
  if (kind === 'completed' && task.status !== 'done') {
502
505
  log.info(`ignoring loose task.completed for ${taskId} (disk status=${task.status})`);
503
- continue;
506
+ return;
504
507
  }
505
- if (kind === 'blocked' && !task.blocked_by) {
506
- log.info(`ignoring stale task.blocked for ${taskId} (no blocked_by on disk)`);
507
- continue;
508
+ if (kind === 'completed' && !matchesTaskGeneration(task, ownership)) {
509
+ log.info(`ignoring stale task.completed for ${taskId} (dispatch generation mismatch)`);
510
+ return;
508
511
  }
512
+ if (kind === 'blocked' && !task.blocked_by)
513
+ return;
514
+ if (kind === 'blocked' && !matchesTaskGeneration(task, ownership))
515
+ return;
509
516
  await deliverTaskResult(parent.id, task, kind, deps);
517
+ });
518
+ }
519
+ /** Verify task provenance while holding its mutation lock, then wake waiting managers. */
520
+ export async function notifyTaskParentThreads(taskId, kind, deps = {}, ownership) {
521
+ for (const parent of threadStore.getAll()) {
522
+ if (parent.status !== 'waiting')
523
+ continue;
524
+ if (!parent.metadata?.waitingOnTasks?.includes(taskId))
525
+ continue;
526
+ await deliverCurrentTaskResult(parent, taskId, kind, deps, ownership);
510
527
  }
511
528
  }
512
529
  /** Wake (or create) the session on a channel by routing a synthetic user message — the same
@@ -547,12 +564,28 @@ function buildTaskOriginNotice(task, kind) {
547
564
  }
548
565
  return `[Task blocked] The task you dispatched #${task.id} (${task.project}) "${task.text}" is blocked.\nBlocked by: ${task.blocked_by || '(unrecorded)'}\nRun cortex-task show --task-id ${task.id} for details; once handled, cortex-task unblock.`;
549
566
  }
567
+ /** Human-facing project-channel notice for a fire-and-forget task queued from inside a thread:
568
+ * the thread has (most likely) ended and never consumes the result, so nobody is woken —
569
+ * the outcome just surfaces in the project's report stream. */
570
+ export function buildThreadOriginTaskNotice(task, kind) {
571
+ const origin = `queued by thread ${task.origin_thread_id}`;
572
+ if (kind === 'completed') {
573
+ const note = task.completed_note ? `\nNote: ${task.completed_note}` : '';
574
+ return `[Task done] #${task.id} (${task.project}) "${task.text}" — ${origin}.${note}\nRun cortex-task show --task-id ${task.id} for details.`;
575
+ }
576
+ return `[Task blocked] #${task.id} (${task.project}) "${task.text}" — ${origin}.\nBlocked by: ${task.blocked_by || '(unrecorded)'}\nRun cortex-task show --task-id ${task.id} for details; once handled, cortex-task unblock.`;
577
+ }
550
578
  /** Session→task wake (Problem 1): when a task created by an interactive session/agent turns
551
579
  * terminal, route a notice back to its origin channel. Default-on, no fallback — if origin_channel
552
580
  * is set we always wake it. Mutually exclusive with the thread-parent path: if any thread is
553
581
  * currently waiting on this task (waitingOnTasks), that path owns the result and we defer.
554
- * `wake` is injectable for testing (mirrors the `resume` injection on notifyTaskParentThreads). */
555
- export async function notifyTaskOriginSession(taskId, kind, deps = {}) {
582
+ * Thread-origin tasks (origin_thread_id set — fire-and-forget adds from inside a thread) never
583
+ * wake a session: the creating thread has likely ended, and its recorded channel is an
584
+ * unattended dispatch conduit; the result degrades to a durable project-report notice instead.
585
+ * origin_thread_id takes precedence over origin_channel so legacy tasks that captured both
586
+ * are fixed retroactively. `wake`/`postNotice` are injectable for testing (mirrors the
587
+ * `resume` injection on notifyTaskParentThreads). */
588
+ export async function notifyTaskOriginSession(taskId, kind, deps = {}, ownership) {
556
589
  for (const t of threadStore.getAll()) {
557
590
  if (t.status === 'waiting' && t.metadata?.waitingOnTasks?.includes(taskId))
558
591
  return;
@@ -560,17 +593,37 @@ export async function notifyTaskOriginSession(taskId, kind, deps = {}) {
560
593
  const key = `task_${taskId}_${kind}`;
561
594
  if (fired.has(key))
562
595
  return;
563
- // The event carries only the id; origin fields live on the task — scan disk to find it.
564
- const task = scanAllTasks().find((t) => t.id === taskId);
565
- if (!task || !task.origin_channel)
596
+ const located = scanAllTasks().find((task) => task.id === taskId);
597
+ if (!located?.origin_channel && !located?.origin_thread_id)
566
598
  return;
567
- if (kind === 'completed' && task.status !== 'done')
568
- return; // dispatch publishes loosely
569
- if (kind === 'blocked' && !task.blocked_by)
599
+ const delivery = await withTaskFileMutationLockAsync(located.project, async () => {
600
+ const task = readTaskFromDisk(located.project, taskId);
601
+ if (!task || (!task.origin_channel && !task.origin_thread_id))
602
+ return null;
603
+ if (kind === 'completed' && task.status !== 'done')
604
+ return null;
605
+ if (kind === 'completed' && !matchesTaskGeneration(task, ownership))
606
+ return null;
607
+ if (kind === 'blocked' && !task.blocked_by)
608
+ return null;
609
+ if (kind === 'blocked' && !matchesTaskGeneration(task, ownership))
610
+ return null;
611
+ fired.add(key);
612
+ if (task.origin_thread_id) {
613
+ return { channel: null, project: task.project, notice: buildThreadOriginTaskNotice(task, kind) };
614
+ }
615
+ return { channel: task.origin_channel, project: task.project, notice: buildTaskOriginNotice(task, kind) };
616
+ });
617
+ if (!delivery)
570
618
  return;
571
- fired.add(key);
572
- const wake = deps.wake ?? ((ch, n) => wakeSession(ch, n, `task_${taskId}`));
573
- await wake(task.origin_channel, buildTaskOriginNotice(task, kind));
619
+ if (delivery.channel) {
620
+ const wake = deps.wake ?? ((ch, n) => wakeSession(ch, n, `task_${taskId}`));
621
+ await wake(delivery.channel, delivery.notice);
622
+ }
623
+ else {
624
+ const post = deps.postNotice ?? ((p, n) => postProjectNoticeTo(p, 'task-origin', n));
625
+ await post(delivery.project, delivery.notice);
626
+ }
574
627
  }
575
628
  /** Sweep one waiting thread's waitingOnTasks against disk state: deliver already-done and
576
629
  * already-blocked children, drop missing ones, keep open ones. Closes the race window
@@ -633,10 +686,16 @@ export async function closeResumedTaskLoop(threadId, deps = {}) {
633
686
  return;
634
687
  const publish = deps.publish ?? ((e) => jobCtx.bus?.publish(e));
635
688
  if (task.status === 'done') {
636
- publish({ type: 'task.completed', taskId: m.taskId });
689
+ publish({
690
+ type: 'task.completed', taskId: m.taskId,
691
+ dispatchGeneration: m.dispatchGeneration ?? null,
692
+ });
637
693
  }
638
694
  else if (task.blocked_by) {
639
- publish({ type: 'task.blocked', taskId: m.taskId, reason: task.blocked_by });
695
+ publish({
696
+ type: 'task.blocked', taskId: m.taskId, reason: task.blocked_by,
697
+ dispatchGeneration: m.dispatchGeneration ?? null,
698
+ });
640
699
  }
641
700
  }
642
701
  /** Periodic disk-driven backstop: reconcile EVERY suspended manager's task children against disk
@@ -658,32 +717,44 @@ export async function sweepWaitingManagers(deps = {}) {
658
717
  }
659
718
  return swept;
660
719
  }
661
- /** Default sweep cadence — frequent enough to recover a stranded manager within a minute, cheap
662
- * enough (a disk scan per waiting manager) to run unconditionally. Override with
663
- * CORTEX_WAITING_SWEEP_MS (0 disables). */
664
- const WAITING_SWEEP_INTERVAL_MS = (() => {
665
- const v = parseInt(process.env.CORTEX_WAITING_SWEEP_MS || '', 10);
666
- return Number.isFinite(v) ? v : 60_000;
667
- })();
668
- /** Start the periodic waiting-manager sweep (thin setInterval wrapper, mirrors
669
- * startDispatchReconciler). No-op when the interval is 0. */
720
+ /** Schedule one sweep and re-arm only after it settles, using the latest cadence. */
721
+ function scheduleWaitingManagerSweep(intervalMs) {
722
+ const timer = setTimeout(async () => {
723
+ await sweepWaitingManagers().catch((e) => log.error(`waiting-manager sweep: ${e.message}`));
724
+ const nextIntervalMs = getSettings().waitingSweepMs;
725
+ // Runtime zero stops re-arming until restart; startup zero never starts the loop.
726
+ if (nextIntervalMs > 0)
727
+ scheduleWaitingManagerSweep(nextIntervalMs);
728
+ }, intervalMs);
729
+ timer.unref?.();
730
+ }
731
+ /** Start the periodic waiting-manager sweep. No-op when the startup interval is disabled. */
670
732
  export function startWaitingManagerSweep() {
671
- if (WAITING_SWEEP_INTERVAL_MS <= 0)
733
+ const intervalMs = getSettings().waitingSweepMs;
734
+ if (intervalMs <= 0)
672
735
  return;
673
- setInterval(() => {
674
- void sweepWaitingManagers().catch((e) => log.error(`waiting-manager sweep: ${e.message}`));
675
- }, WAITING_SWEEP_INTERVAL_MS).unref?.();
736
+ scheduleWaitingManagerSweep(intervalMs);
676
737
  }
677
738
  /** Register the EventBus subscribers that wake suspended manager threads on child-task
678
739
  * terminal events (DR-0014 §8). Call once at startup, before recoverWaitingThreads. */
679
740
  export function registerTaskTreeSubscribers(bus) {
680
741
  bus.subscribe('task.completed', (e) => {
681
- void notifyTaskParentThreads(e.taskId, 'completed').catch((err) => log.error(`task.completed bridge: ${err.message}`));
682
- void notifyTaskOriginSession(e.taskId, 'completed').catch((err) => log.error(`task.completed origin-wake: ${err.message}`));
742
+ const ownership = Object.hasOwn(e, 'dispatchGeneration')
743
+ ? { generation: e.dispatchGeneration ?? null }
744
+ : undefined;
745
+ void notifyTaskParentThreads(e.taskId, 'completed', {}, ownership)
746
+ .catch((err) => log.error(`task.completed bridge: ${err.message}`));
747
+ void notifyTaskOriginSession(e.taskId, 'completed', {}, ownership)
748
+ .catch((err) => log.error(`task.completed origin-wake: ${err.message}`));
683
749
  });
684
750
  bus.subscribe('task.blocked', (e) => {
685
- void notifyTaskParentThreads(e.taskId, 'blocked').catch((err) => log.error(`task.blocked bridge: ${err.message}`));
686
- void notifyTaskOriginSession(e.taskId, 'blocked').catch((err) => log.error(`task.blocked origin-wake: ${err.message}`));
751
+ const ownership = Object.hasOwn(e, 'dispatchGeneration')
752
+ ? { generation: e.dispatchGeneration ?? null }
753
+ : undefined;
754
+ void notifyTaskParentThreads(e.taskId, 'blocked', {}, ownership)
755
+ .catch((err) => log.error(`task.blocked bridge: ${err.message}`));
756
+ void notifyTaskOriginSession(e.taskId, 'blocked', {}, ownership)
757
+ .catch((err) => log.error(`task.blocked origin-wake: ${err.message}`));
687
758
  });
688
759
  }
689
760
  /** Startup recovery: re-deliver results that completed while the server was down.
@@ -1,18 +1,21 @@
1
- // input: domain/threads, thread-runner, orch/channel-queue, orch/busy-tracker
2
- // output: ThreadExecutor with queue markers plus detached thread runner
1
+ // input: threads, platform files, channel queue, busy tracker
2
+ // output: ThreadExecutor with file-aware buffering and detached runs
3
3
  // pos: Sole thread-routing execution path
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { randomUUID } from 'node:crypto';
5
6
  import { createLogger } from '../core/log.js';
6
7
  import { Icons } from '../core/icons.js';
7
8
  import { conduitQueues, enqueue } from './conduit-queue.js';
8
9
  import { trackPendingTask } from './busy-tracker.js';
9
10
  import { addAgentToThread, createThread, getTemplate, getAgent } from '../domain/threads/index.js';
11
+ import { evictPendingUserInput, registerPendingUserInput } from '../domain/threads/pending-user-inputs.js';
10
12
  import { runThread, continueThread, getActiveHandle } from '../domain/threads/runner.js';
11
13
  import { downloadFiles as downloadPlatformFiles } from './routing/file-handler.js';
12
14
  import { computeElapsed, buildStatusActionBlocks, buildSealedStatusActionBlocks, initStatusBlocks, sealThreadStatus } from './status-helpers.js';
13
15
  import { threadStore } from '../store/thread-repo.js';
14
16
  import { WORKSPACE_DIR } from '../core/utils.js';
15
17
  import { buildInteractiveCallbacks } from './agent-runner.js';
18
+ import { buildPrompt as buildAgentPrompt } from '../agent-adapter/normalize/prompt-builder.js';
16
19
  const TEMP_DIR = WORKSPACE_DIR;
17
20
  const log = createLogger('thread-executor');
18
21
  /** Run a thread fire-and-forget while holding the daemon busy gate for the ENTIRE pipeline.
@@ -245,34 +248,41 @@ async function handleThreadStart({ threadStartMatch, messageId, channel, adapter
245
248
  return statusMsg;
246
249
  }
247
250
  // --- Message buffering (Phase 6) ---
248
- /** Append a user message to thread.metadata.pendingMessages for inclusion
249
- * in the next step's prompt. Used when a step is currently executing
250
- * and we can't safely call continueThread + runThread concurrently. */
251
- async function bufferUserMessage(ctx) {
252
- const { adapter, channel, threadAnchorId } = ctx;
253
- const interactiveDest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
254
- const thread = ctx.existingThread;
255
- const text = ctx.agentMessage || ctx.message.text || '';
256
- // Synchronously append to in-memory metadata so the next buildStepPrompt
257
- // call (within the same event-loop tick) sees it immediately.
258
- // NOTE: Uses threadStore.set() (not mutate()) intentionally — mutate() awaits
259
- // _pendingPersist which introduces a microtask delay, breaking the synchronous
260
- // visibility guarantee required by the runThread main loop. The in-memory ref is
261
- // updated first, then the fire-and-forget set() persists the whole record.
251
+ /** Reserve user input synchronously so the runner sees it before the current step exits. */
252
+ function reserveUserInput(thread, text) {
253
+ const inputId = `buf_${randomUUID()}`;
262
254
  if (!thread.metadata)
263
255
  thread.metadata = {};
264
- if (!Array.isArray(thread.metadata.pendingMessages))
265
- thread.metadata.pendingMessages = [];
266
- // Cap at 10 to prevent unbounded prompt growth
267
- if (thread.metadata.pendingMessages.length >= 10) {
268
- thread.metadata.pendingMessages.shift();
269
- }
270
- thread.metadata.pendingMessages.push(text);
271
- // Fire-and-forget persist — .set() is deliberate (see NOTE above). Errors are
272
- // dropped because the in-memory state is authoritative and will be persisted by
273
- // the next conventional mutate() call on this thread.
256
+ const inputs = thread.metadata.pendingUserInputs ??= [];
257
+ const evictedInputId = inputs.length >= 10 ? inputs.shift()?.id ?? null : null;
258
+ inputs.push({ id: inputId, text });
274
259
  threadStore.set(thread).catch(() => { });
275
- await adapter.postMessage(interactiveDest, {
260
+ return { inputId, evictedInputId };
261
+ }
262
+ async function prepareUserInput(ctx, inputId, text) {
263
+ const files = await downloadFiles(ctx.message.files, ctx.hasFiles, ctx.adapter);
264
+ const thread = threadStore.get(ctx.existingThread.id);
265
+ const input = thread?.metadata?.pendingUserInputs?.find((entry) => entry.id === inputId);
266
+ if (!thread || !input)
267
+ return;
268
+ input.text = buildAgentPrompt(text, files.map((file) => ({
269
+ mimeType: file.mimetype,
270
+ path: file.localPath,
271
+ })));
272
+ await threadStore.set(thread);
273
+ }
274
+ /** Buffer user text plus downloaded files for the next thread step. */
275
+ async function bufferUserMessage(ctx) {
276
+ const { adapter, channel, threadAnchorId } = ctx;
277
+ const text = ctx.agentMessage || ctx.message.text || '';
278
+ const { inputId, evictedInputId } = reserveUserInput(ctx.existingThread, text);
279
+ if (evictedInputId)
280
+ evictPendingUserInput(ctx.existingThread.id, evictedInputId);
281
+ const preparation = prepareUserInput(ctx, inputId, text);
282
+ registerPendingUserInput(ctx.existingThread.id, inputId, preparation);
283
+ await preparation.catch((error) => log.warn(`Failed to prepare buffered input: ${error.message}`));
284
+ const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
285
+ await adapter.postMessage(dest, {
276
286
  text: `${Icons.inbox} Message buffered — will be included in the next step’s prompt`,
277
287
  }, threadAnchorId ? { threadId: threadAnchorId } : undefined);
278
288
  }
@@ -0,0 +1,3 @@
1
+ export type TurnMutationRelease = () => void;
2
+ export declare function tryAcquireTurnMutationLock(channel: string): TurnMutationRelease | null;
3
+ export declare function acquireTurnMutationLock(channel: string): Promise<TurnMutationRelease>;
@@ -0,0 +1,36 @@
1
+ // input: channel ids and turn mutation requests
2
+ // output: keyed mutation lease type and acquisition functions
3
+ // pos: Serializes snapshot and rewind mutations
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
+ const entries = new Map();
6
+ function releaseFor(channel, entry) {
7
+ let released = false;
8
+ return () => {
9
+ if (released)
10
+ return;
11
+ released = true;
12
+ const next = entry.waiters.shift();
13
+ if (next) {
14
+ next(releaseFor(channel, entry));
15
+ return;
16
+ }
17
+ entry.locked = false;
18
+ if (entries.get(channel) === entry)
19
+ entries.delete(channel);
20
+ };
21
+ }
22
+ export function tryAcquireTurnMutationLock(channel) {
23
+ const entry = entries.get(channel) ?? { locked: false, waiters: [] };
24
+ entries.set(channel, entry);
25
+ if (entry.locked)
26
+ return null;
27
+ entry.locked = true;
28
+ return releaseFor(channel, entry);
29
+ }
30
+ export function acquireTurnMutationLock(channel) {
31
+ const release = tryAcquireTurnMutationLock(channel);
32
+ if (release)
33
+ return Promise.resolve(release);
34
+ const entry = entries.get(channel);
35
+ return new Promise((resolve) => entry.waiters.push(resolve));
36
+ }
@@ -1,10 +1,7 @@
1
1
  import type { PlatformAdapter } from '../platform/index.js';
2
- /** Feature gate: turn-completion notification is ON by default. Opt out by setting
3
- * CORTEX_TURN_NOTIFY to a falsy value (0 / false / off / no). */
2
+ /** Feature gate: turn-completion notification is ON by default. */
4
3
  export declare function isTurnNotifyEnabled(): boolean;
5
- /** Minimum turn duration (seconds) before a completion notification is pushed.
6
- * Configurable via CORTEX_TURN_NOTIFY_THRESHOLD_S; defaults to 60s. A non-positive
7
- * or unparseable value falls back to the default. */
4
+ /** Minimum turn duration (seconds) before a completion notification is pushed. */
8
5
  export declare function getTurnNotifyThresholdS(): number;
9
6
  /** Push a NEW message to the conversation's channel when a long-running, user-initiated
10
7
  * turn finishes — so the user gets an actual push notification (editing the status
@@ -1,34 +1,22 @@
1
- // input: orch/bg-continuation(isInteractiveChannel), store/outbound-queue(durablePost,getOutboundQueue), core/status-format(buildSessionTag), core/icons, core/i18n
2
- // output: isTurnNotifyEnabled / getTurnNotifyThresholdS / maybeNotifyTurnComplete
3
- // pos: orch layer — push a NEW message (Slack + Feishu) when a long-running user turn finishes
4
- // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
1
+ // input: runtime settings, platform adapter, outbound queue
2
+ // output: turn notification gates and completion notifier
3
+ // pos: Pushes completion notices for long interactive turns
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import { createLogger } from '../core/log.js';
6
+ import { getSettings } from '../core/settings.js';
6
7
  import { Icons } from '../core/icons.js';
7
8
  import { t } from '../core/i18n.js';
8
9
  import { buildSessionTag } from '../core/status-format.js';
9
10
  import { getOutboundQueue, durablePost } from '../store/outbound-queue.js';
10
11
  import { isInteractiveChannel } from './bg-continuation.js';
11
12
  const log = createLogger('turn-notify');
12
- const DEFAULT_THRESHOLD_S = 60;
13
- /** Feature gate: turn-completion notification is ON by default. Opt out by setting
14
- * CORTEX_TURN_NOTIFY to a falsy value (0 / false / off / no). */
13
+ /** Feature gate: turn-completion notification is ON by default. */
15
14
  export function isTurnNotifyEnabled() {
16
- const v = process.env.CORTEX_TURN_NOTIFY;
17
- if (v === undefined)
18
- return true;
19
- return !['0', 'false', 'off', 'no'].includes(v.trim().toLowerCase());
15
+ return getSettings().turnNotify;
20
16
  }
21
- /** Minimum turn duration (seconds) before a completion notification is pushed.
22
- * Configurable via CORTEX_TURN_NOTIFY_THRESHOLD_S; defaults to 60s. A non-positive
23
- * or unparseable value falls back to the default. */
17
+ /** Minimum turn duration (seconds) before a completion notification is pushed. */
24
18
  export function getTurnNotifyThresholdS() {
25
- const raw = process.env.CORTEX_TURN_NOTIFY_THRESHOLD_S;
26
- if (raw === undefined)
27
- return DEFAULT_THRESHOLD_S;
28
- const n = Number(raw.trim());
29
- if (!Number.isFinite(n) || n <= 0)
30
- return DEFAULT_THRESHOLD_S;
31
- return n;
19
+ return getSettings().turnNotifyThresholdS;
32
20
  }
33
21
  /** Push a NEW message to the conversation's channel when a long-running, user-initiated
34
22
  * turn finishes — so the user gets an actual push notification (editing the status
@@ -23,6 +23,7 @@ export interface PlatformAdapter {
23
23
  uploadFile(destination: Destination, filePath: string, opts?: FileUploadOpts): Promise<void>;
24
24
  downloadFile(fileRef: PlatformFileRef, destDir: string): Promise<DownloadedFile>;
25
25
  getPermalink(ref: MessageRef): Promise<string | null>;
26
+ setAdminChannel?(channel: string | null): void;
26
27
  /** Open a new OutputStream for streaming agent output to the given destination. */
27
28
  openOutputStream(destination: Destination, opts?: OpenOutputStreamOpts): OutputStream;
28
29
  /** Register a conduit (channel/chat) for project-report destinations. */
@@ -1,5 +1,5 @@
1
- // input: ./types.js platform-agnostic message types
2
- // output: PlatformAdapter interface with symmetric queue-marker lifecycle
1
+ // input: platform message and output-stream types
2
+ // output: PlatformAdapter lifecycle and live-update contract
3
3
  // pos: Boundary between orchestration and messaging platforms
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  export {};
@@ -85,6 +85,8 @@ export declare class CompositeAdapter implements PlatformAdapter {
85
85
  resolveInboundProject(conduit: string): Promise<string | null>;
86
86
  ownsConduit(conduit: string): boolean;
87
87
  }
88
+ export type AdminChannelPlatform = 'slack' | 'feishu';
89
+ export declare function setPlatformAdminChannel(adapter: PlatformAdapter, platform: AdminChannelPlatform, channel: string | null): void;
88
90
  /**
89
91
  * Extract the TuiGatewayAdapter from an adapter.
90
92
  * - CompositeAdapter: return the inner gateway (if any)