@cortex-agent/server 2026.7.30 → 2026.8.3

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 (348) 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/domain/agent-run/access-probe-cli.d.ts +7 -0
  107. package/dist/domain/agent-run/access-probe-cli.js +139 -0
  108. package/dist/domain/agent-run/access-probe-policy.d.ts +61 -0
  109. package/dist/domain/agent-run/access-probe-policy.js +614 -0
  110. package/dist/domain/agent-run/access-probe.d.ts +21 -0
  111. package/dist/domain/agent-run/access-probe.js +194 -0
  112. package/dist/domain/agent-run/agent-run-cli.d.ts +19 -0
  113. package/dist/domain/agent-run/agent-run-cli.js +171 -0
  114. package/dist/domain/agent-run/atif.d.ts +54 -0
  115. package/dist/domain/agent-run/atif.js +211 -0
  116. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +32 -0
  117. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +616 -0
  118. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +34 -0
  119. package/dist/domain/agent-run/benchmark-thread-identity.js +106 -0
  120. package/dist/domain/agent-run/identity.d.ts +62 -0
  121. package/dist/domain/agent-run/identity.js +118 -0
  122. package/dist/domain/agent-run/journal.d.ts +51 -0
  123. package/dist/domain/agent-run/journal.js +259 -0
  124. package/dist/domain/agent-run/manifest-contract.d.ts +44 -0
  125. package/dist/domain/agent-run/manifest-contract.js +134 -0
  126. package/dist/domain/agent-run/manifest.d.ts +51 -0
  127. package/dist/domain/agent-run/manifest.js +801 -0
  128. package/dist/domain/agent-run/pinned-node-process.d.ts +35 -0
  129. package/dist/domain/agent-run/pinned-node-process.js +206 -0
  130. package/dist/domain/agent-run/role-surface.d.ts +4 -0
  131. package/dist/domain/agent-run/role-surface.js +99 -0
  132. package/dist/domain/agent-run/run-config.d.ts +22 -0
  133. package/dist/domain/agent-run/run-config.js +135 -0
  134. package/dist/domain/agent-run/runner.d.ts +7 -0
  135. package/dist/domain/agent-run/runner.js +518 -0
  136. package/dist/domain/agent-run/supervisor.d.ts +78 -0
  137. package/dist/domain/agent-run/supervisor.js +425 -0
  138. package/dist/domain/agent-run/trajectory-merge-cli.d.ts +11 -0
  139. package/dist/domain/agent-run/trajectory-merge-cli.js +111 -0
  140. package/dist/domain/agent-run/trajectory-merge.d.ts +39 -0
  141. package/dist/domain/agent-run/trajectory-merge.js +505 -0
  142. package/dist/domain/agents/config.d.ts +10 -0
  143. package/dist/domain/agents/config.js +149 -44
  144. package/dist/domain/agents/facade.d.ts +42 -7
  145. package/dist/domain/agents/facade.js +174 -170
  146. package/dist/domain/agents/provider-run-lifecycle.d.ts +18 -0
  147. package/dist/domain/agents/provider-run-lifecycle.js +60 -0
  148. package/dist/domain/auth/auth-events.d.ts +18 -0
  149. package/dist/domain/auth/auth-events.js +38 -0
  150. package/dist/domain/auth/auth-format.d.ts +2 -0
  151. package/dist/domain/auth/auth-format.js +58 -0
  152. package/dist/domain/auth/auth-status.d.ts +61 -0
  153. package/dist/domain/auth/auth-status.js +304 -0
  154. package/dist/domain/auth/auth-watch.d.ts +16 -0
  155. package/dist/domain/auth/auth-watch.js +125 -0
  156. package/dist/domain/auth/cc-login.d.ts +7 -0
  157. package/dist/domain/auth/cc-login.js +16 -0
  158. package/dist/domain/auth/cc-subscription.d.ts +38 -0
  159. package/dist/domain/auth/cc-subscription.js +204 -0
  160. package/dist/domain/auth/index.d.ts +12 -0
  161. package/dist/domain/auth/index.js +16 -0
  162. package/dist/domain/auth/login-flow.d.ts +120 -0
  163. package/dist/domain/auth/login-flow.js +253 -0
  164. package/dist/domain/auth/login-service.d.ts +32 -0
  165. package/dist/domain/auth/login-service.js +97 -0
  166. package/dist/domain/auth/logout.d.ts +32 -0
  167. package/dist/domain/auth/logout.js +123 -0
  168. package/dist/domain/auth/pi-login.d.ts +36 -0
  169. package/dist/domain/auth/pi-login.js +72 -0
  170. package/dist/domain/auth/pi-oauth.d.ts +36 -0
  171. package/dist/domain/auth/pi-oauth.js +84 -0
  172. package/dist/domain/auth/pi-runtime.d.ts +72 -0
  173. package/dist/domain/auth/pi-runtime.js +86 -0
  174. package/dist/domain/mcp/benchmark-thread-server.d.ts +1 -0
  175. package/dist/domain/mcp/benchmark-thread-server.js +26 -0
  176. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +23 -0
  177. package/dist/domain/mcp/tools/benchmark-thread-run.js +146 -0
  178. package/dist/domain/memory/user-context.js +6 -8
  179. package/dist/domain/monitor/disk-monitor.js +47 -16
  180. package/dist/domain/projects/project-store.js +23 -6
  181. package/dist/domain/remote/client-manager.js +12 -6
  182. package/dist/domain/scheduling/jobs/auth-expiry-scan.d.ts +14 -0
  183. package/dist/domain/scheduling/jobs/auth-expiry-scan.js +86 -0
  184. package/dist/domain/scheduling/jobs/task-dispatch.js +36 -40
  185. package/dist/domain/scheduling/runner.d.ts +2 -0
  186. package/dist/domain/scheduling/runner.js +7 -4
  187. package/dist/domain/sessions/session-backup.d.ts +14 -20
  188. package/dist/domain/sessions/session-backup.js +57 -68
  189. package/dist/domain/system/doctor.d.ts +4 -0
  190. package/dist/domain/system/doctor.js +113 -28
  191. package/dist/domain/system/server-update-check.js +7 -5
  192. package/dist/domain/system/system-notice.d.ts +3 -1
  193. package/dist/domain/system/system-notice.js +6 -11
  194. package/dist/domain/tasks/archiver.d.ts +1 -0
  195. package/dist/domain/tasks/archiver.js +13 -7
  196. package/dist/domain/tasks/claim-recovery.d.ts +3 -3
  197. package/dist/domain/tasks/claim-recovery.js +12 -8
  198. package/dist/domain/tasks/dispatch-utils.d.ts +15 -14
  199. package/dist/domain/tasks/dispatch-utils.js +22 -18
  200. package/dist/domain/tasks/dispatcher.d.ts +1 -0
  201. package/dist/domain/tasks/dispatcher.js +9 -5
  202. package/dist/domain/tasks/mutator.d.ts +21 -11
  203. package/dist/domain/tasks/mutator.js +30 -24
  204. package/dist/domain/tasks/pending-tracker.d.ts +5 -2
  205. package/dist/domain/tasks/pending-tracker.js +11 -5
  206. package/dist/domain/tasks/system/cortex-run.d.ts +2 -1
  207. package/dist/domain/tasks/system/cortex-run.js +24 -4
  208. package/dist/domain/tasks/system/task-cli.d.ts +1 -0
  209. package/dist/domain/tasks/system/task-cli.js +72 -22
  210. package/dist/domain/tasks/system/task-completion.d.ts +19 -2
  211. package/dist/domain/tasks/system/task-completion.js +31 -17
  212. package/dist/domain/tasks/system/task-file-input.d.ts +10 -0
  213. package/dist/domain/tasks/system/task-file-input.js +57 -0
  214. package/dist/domain/tasks/system/task-id-utils.d.ts +9 -9
  215. package/dist/domain/tasks/system/task-id-utils.js +13 -4
  216. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -2
  217. package/dist/domain/tasks/system/task-lifecycle-edit.js +200 -6
  218. package/dist/domain/tasks/system/task-lock.js +19 -5
  219. package/dist/domain/tasks/system/task-mutations.d.ts +22 -12
  220. package/dist/domain/tasks/system/task-mutations.js +28 -4
  221. package/dist/domain/tasks/system/task-process.js +10 -8
  222. package/dist/domain/tasks/system/task-state.d.ts +65 -11
  223. package/dist/domain/tasks/system/task-state.js +86 -13
  224. package/dist/domain/threads/local-runtime-deps.d.ts +32 -0
  225. package/dist/domain/threads/local-runtime-deps.js +91 -0
  226. package/dist/domain/threads/local-runtime-scope.d.ts +6 -0
  227. package/dist/domain/threads/local-runtime-scope.js +12 -0
  228. package/dist/domain/threads/pending-user-inputs.d.ts +3 -0
  229. package/dist/domain/threads/pending-user-inputs.js +37 -0
  230. package/dist/domain/threads/prompt-builder.d.ts +12 -1
  231. package/dist/domain/threads/prompt-builder.js +73 -26
  232. package/dist/domain/threads/runner.d.ts +15 -3
  233. package/dist/domain/threads/runner.js +261 -105
  234. package/dist/domain/threads/state-machine.d.ts +1 -1
  235. package/dist/domain/threads/state-machine.js +17 -8
  236. package/dist/domain/ui-service/app-router.d.ts +86 -6
  237. package/dist/domain/ui-service/app-router.js +171 -133
  238. package/dist/domain/ui-service/input-schemas.d.ts +132 -10
  239. package/dist/domain/ui-service/input-schemas.js +59 -5
  240. package/dist/domain/ui-service/mutate/approvals.d.ts +2 -1
  241. package/dist/domain/ui-service/mutate/approvals.js +2 -1
  242. package/dist/domain/ui-service/mutate/auth.d.ts +6 -0
  243. package/dist/domain/ui-service/mutate/auth.js +83 -0
  244. package/dist/domain/ui-service/mutate/config.js +11 -10
  245. package/dist/domain/ui-service/query/approvals.js +3 -0
  246. package/dist/domain/ui-service/query/auth.d.ts +6 -0
  247. package/dist/domain/ui-service/query/auth.js +12 -0
  248. package/dist/domain/ui-service/query/config.d.ts +5 -5
  249. package/dist/domain/ui-service/query/config.js +27 -17
  250. package/dist/domain/ui-service/query/tasks.d.ts +1 -1
  251. package/dist/domain/ui-service/query/tasks.js +69 -30
  252. package/dist/domain/ui-service/query/threads.js +3 -3
  253. package/dist/domain/ui-service/types.d.ts +67 -8
  254. package/dist/domain/ui-service/types.js +2 -2
  255. package/dist/domain/ui-service/ui-service.js +16 -2
  256. package/dist/entry/admin-channel-hot-reload.d.ts +4 -0
  257. package/dist/entry/admin-channel-hot-reload.js +22 -0
  258. package/dist/entry/app.js +38 -38
  259. package/dist/entry/auth-cli.d.ts +10 -0
  260. package/dist/entry/auth-cli.js +52 -0
  261. package/dist/entry/cli-help.d.ts +5 -0
  262. package/dist/entry/cli-help.js +130 -0
  263. package/dist/entry/cli.d.ts +5 -5
  264. package/dist/entry/cli.js +174 -248
  265. package/dist/entry/daemon.d.ts +11 -0
  266. package/dist/entry/daemon.js +204 -103
  267. package/dist/entry/draft-attachments.d.ts +8 -0
  268. package/dist/entry/draft-attachments.js +83 -0
  269. package/dist/entry/feishu-login.d.ts +2 -6
  270. package/dist/entry/feishu-login.js +16 -21
  271. package/dist/entry/init.js +6 -4
  272. package/dist/entry/start-ui-http.d.ts +2 -8
  273. package/dist/entry/start-ui-http.js +7 -34
  274. package/dist/events/event-logger.js +11 -13
  275. package/dist/events/event-types.d.ts +19 -1
  276. package/dist/events/event-types.js +3 -3
  277. package/dist/events/index.d.ts +1 -1
  278. package/dist/events/index.js +3 -3
  279. package/dist/hooks/new-session-hook.mjs +2 -2
  280. package/dist/hooks/status-md-guard.mjs +193 -0
  281. package/dist/orchestration/agent-file-send.js +44 -14
  282. package/dist/orchestration/agent-runner.d.ts +7 -3
  283. package/dist/orchestration/agent-runner.js +65 -41
  284. package/dist/orchestration/conversation-runner.d.ts +5 -1
  285. package/dist/orchestration/conversation-runner.js +16 -7
  286. package/dist/orchestration/lifecycle.d.ts +23 -1
  287. package/dist/orchestration/lifecycle.js +103 -40
  288. package/dist/orchestration/mid-turn-inject.d.ts +2 -0
  289. package/dist/orchestration/mid-turn-inject.js +29 -13
  290. package/dist/orchestration/resume-dispatcher.d.ts +3 -5
  291. package/dist/orchestration/resume-dispatcher.js +9 -17
  292. package/dist/orchestration/routing/commands/index.d.ts +4 -1
  293. package/dist/orchestration/routing/commands/index.js +83 -61
  294. package/dist/orchestration/routing/commands/login-notice.d.ts +21 -0
  295. package/dist/orchestration/routing/commands/login-notice.js +97 -0
  296. package/dist/orchestration/routing/commands/login.d.ts +12 -0
  297. package/dist/orchestration/routing/commands/login.js +555 -0
  298. package/dist/orchestration/routing/commands/status.js +45 -59
  299. package/dist/orchestration/routing/edit-handler.d.ts +5 -0
  300. package/dist/orchestration/routing/edit-handler.js +127 -73
  301. package/dist/orchestration/routing/webhook.js +5 -4
  302. package/dist/orchestration/session-rewind.d.ts +5 -1
  303. package/dist/orchestration/session-rewind.js +106 -62
  304. package/dist/orchestration/session-send.d.ts +2 -0
  305. package/dist/orchestration/session-send.js +5 -6
  306. package/dist/orchestration/status-helpers.d.ts +1 -2
  307. package/dist/orchestration/status-helpers.js +7 -10
  308. package/dist/orchestration/thread-callback.d.ts +19 -11
  309. package/dist/orchestration/thread-callback.js +132 -61
  310. package/dist/orchestration/thread-executor.js +37 -27
  311. package/dist/orchestration/turn-mutation-lock.d.ts +3 -0
  312. package/dist/orchestration/turn-mutation-lock.js +36 -0
  313. package/dist/orchestration/turn-notify.d.ts +2 -5
  314. package/dist/orchestration/turn-notify.js +9 -21
  315. package/dist/platform/adapter.d.ts +1 -0
  316. package/dist/platform/adapter.js +2 -2
  317. package/dist/platform/adapters/composite-adapter.d.ts +2 -0
  318. package/dist/platform/adapters/composite-adapter.js +13 -3
  319. package/dist/platform/adapters/feishu.d.ts +2 -4
  320. package/dist/platform/adapters/feishu.js +38 -59
  321. package/dist/platform/adapters/index.d.ts +1 -1
  322. package/dist/platform/adapters/index.js +13 -12
  323. package/dist/platform/adapters/slack.d.ts +1 -1
  324. package/dist/platform/adapters/slack.js +12 -35
  325. package/dist/platform/index.d.ts +2 -1
  326. package/dist/platform/index.js +3 -3
  327. package/dist/platform/testing.d.ts +1 -0
  328. package/dist/platform/testing.js +13 -4
  329. package/dist/platform/tool-trace.js +6 -11
  330. package/dist/platform/ui-http/ui-http-server.d.ts +1 -1
  331. package/dist/platform/ui-http/ui-http-server.js +6 -18
  332. package/dist/store/execution-repo.d.ts +17 -1
  333. package/dist/store/execution-repo.js +55 -4
  334. package/dist/store/prompt-migration-replacements.d.ts +4 -0
  335. package/dist/store/prompt-migration-replacements.js +149 -0
  336. package/dist/store/thread-repo.d.ts +15 -4
  337. package/dist/store/thread-repo.js +61 -24
  338. package/dist/store/version-migrations.js +36 -1
  339. package/native/cortex-supervisor/dist/build-manifest.json +22 -0
  340. package/native/cortex-supervisor/dist/cortex-supervisor +0 -0
  341. package/package.json +5 -2
  342. package/web/dist/assets/index-DrNx9R6c.js +139 -0
  343. package/web/dist/assets/index-zpf3OSKC.css +1 -0
  344. package/web/dist/index.html +2 -2
  345. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.d.ts +0 -1
  346. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.js +0 -78
  347. package/web/dist/assets/index-B19jLgji.js +0 -138
  348. package/web/dist/assets/index-BuFyPyRW.css +0 -1
@@ -1,5 +1,5 @@
1
- // input: task repo, lifecycle and project-lock operations
2
- // output: task mutations and terminal events
1
+ // input: task repo, lifecycle ownership, project locks, EventBus
2
+ // output: serialized owned mutations and generation-aware events
3
3
  // pos: Serializes task mutations across processes
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { taskStore } from '../../store/task-repo.js';
@@ -26,6 +26,12 @@ function releaseSystemProjectLock(project, owner) {
26
26
  if (!result.released)
27
27
  throw new Error(result.message || `Failed to release project lock for ${project}`);
28
28
  }
29
+ function decomposeLockError(project, options) {
30
+ if (!options.system)
31
+ return assertLockHeld(project, getOwnerIdentity());
32
+ const lock = isProjectLocked(project);
33
+ return lock.locked ? `Project lock held by ${lock.owner} — split deferred` : null;
34
+ }
29
35
  export class TaskMutator {
30
36
  store;
31
37
  bus;
@@ -47,12 +53,12 @@ export class TaskMutator {
47
53
  }
48
54
  return task;
49
55
  }
50
- async claim(taskId, agent) {
56
+ async claim(taskId, agent, options = {}) {
51
57
  return this.store.runExclusive(() => {
52
58
  const task = this.store.getById(taskId);
53
59
  if (!task)
54
60
  return { success: false, message: `Task not found: ${taskId}` };
55
- const result = lifecycleClaimTask(task.text, task.project, agent, taskId);
61
+ const result = lifecycleClaimTask(task.text, task.project, agent, taskId, options.generation ?? null);
56
62
  if (result.success) {
57
63
  this.store.refresh();
58
64
  this.store.commitAndPush(`task-store: claim ${taskId} by ${agent}`);
@@ -61,12 +67,12 @@ export class TaskMutator {
61
67
  return result;
62
68
  });
63
69
  }
64
- async unclaim(taskId) {
70
+ async unclaim(taskId, options = {}) {
65
71
  return this.store.runExclusive(() => {
66
72
  const task = this.store.getById(taskId);
67
73
  if (!task)
68
74
  return { success: false, message: `Task not found: ${taskId}` };
69
- const result = lifecycleUnclaimTask(task.text, task.project, taskId);
75
+ const result = lifecycleUnclaimTask(task.text, task.project, taskId, options.ownership);
70
76
  if (result.success) {
71
77
  this.store.refresh();
72
78
  this.store.commitAndPush(`task-store: unclaim ${taskId}`);
@@ -80,11 +86,14 @@ export class TaskMutator {
80
86
  const task = this.getByIdFresh(taskId);
81
87
  if (!task)
82
88
  return { success: false, message: `Task not found: ${taskId}` };
83
- const result = lifecycleCompleteTask(task.text, task.project, note || '', taskId, options.skipVerify ?? false, options.skipVerifyReason ?? null);
89
+ const result = lifecycleCompleteTask(task.text, task.project, note || '', taskId, options.skipVerify ?? false, options.skipVerifyReason ?? null, options.ownership);
84
90
  if (result.success) {
85
91
  this.store.refresh();
86
92
  this.store.commitAndPush(`task-store: complete ${taskId}`);
87
- this.bus?.publish({ type: 'task.completed', taskId });
93
+ this.bus?.publish({
94
+ type: 'task.completed', taskId,
95
+ ...(options.ownership ? { dispatchGeneration: options.ownership.generation } : {}),
96
+ });
88
97
  void emitCortexEvent('cortex:task.completed', { taskId, project: task.project }).catch(() => { });
89
98
  }
90
99
  return result;
@@ -103,17 +112,20 @@ export class TaskMutator {
103
112
  return result;
104
113
  });
105
114
  }
106
- async block(taskId, reason) {
115
+ async block(taskId, reason, options = {}) {
107
116
  return this.store.runExclusive(() => {
108
117
  const task = this.getByIdFresh(taskId);
109
118
  if (!task)
110
119
  return { success: false, message: `Task not found: ${taskId}` };
111
- const result = lifecycleBlockTask(task.text, task.project, reason, taskId);
120
+ const result = lifecycleBlockTask(task.text, task.project, reason, taskId, options.ownership);
112
121
  if (result.success) {
113
122
  this.store.refresh();
114
123
  this.store.commitAndPush(`task-store: block ${taskId}`);
115
124
  // DR-0014 §8: a blocked task is a child's escalation — wake its waiting manager.
116
- this.bus?.publish({ type: 'task.blocked', taskId, reason });
125
+ this.bus?.publish({
126
+ type: 'task.blocked', taskId, reason,
127
+ ...(options.ownership ? { dispatchGeneration: options.ownership.generation } : {}),
128
+ });
117
129
  void emitCortexEvent('cortex:task.blocked', { taskId, project: task.project, reason }).catch(() => { });
118
130
  }
119
131
  return result;
@@ -265,19 +277,13 @@ export class TaskMutator {
265
277
  }
266
278
  async decompose(project, taskText, subtasks, taskId, options = {}) {
267
279
  return this.store.runExclusive(() => {
268
- if (options.system) {
269
- // System-initiated decompose ([SPLIT] dispatch path, DR-0014): no agent holds the
270
- // lock here — proceed unless a FOREIGN lock exists (defer to the lock holder).
271
- const l = isProjectLocked(project);
272
- if (l.locked)
273
- return { success: false, message: `Project lock held by ${l.owner} — split deferred` };
274
- }
275
- else {
276
- const lockError = assertLockHeld(project, getOwnerIdentity());
277
- if (lockError)
278
- return { success: false, message: lockError };
279
- }
280
- const result = lifecycleDecomposeTask(project, taskText, subtasks, taskId || null, { keepParent: options.keepParent });
280
+ const lockError = decomposeLockError(project, options);
281
+ if (lockError)
282
+ return { success: false, message: lockError };
283
+ const result = lifecycleDecomposeTask(project, taskText, subtasks, taskId || null, {
284
+ keepParent: options.keepParent,
285
+ ownership: options.ownership,
286
+ });
281
287
  if (result.success) {
282
288
  this.store.refresh();
283
289
  this.store.commitAndPush(`task-store: decompose task in ${project}${options.keepParent ? ' (keep-parent)' : ''}`);
@@ -11,6 +11,7 @@ interface PendingTaskEntry {
11
11
  sessionName: string | null;
12
12
  tmuxName: string | null;
13
13
  pid: string | null;
14
+ dispatchGeneration: string | null;
14
15
  }
15
16
  declare function buildTrackingMetaParts({ startedAtMs, elapsed_s }: {
16
17
  startedAtMs?: number;
@@ -30,7 +31,7 @@ declare function buildTrackingMessage({ taskId, machine, taskText, startedAtMs,
30
31
  finalOutput?: string | null;
31
32
  }): string;
32
33
  declare function init(adapter: PlatformAdapter): void;
33
- declare function onTaskLaunched({ taskId, machine, channel, scheduleTaskId, taskText, taskHash, project, sessionName, tmuxName, pid }: {
34
+ declare function onTaskLaunched({ taskId, machine, channel, scheduleTaskId, taskText, taskHash, project, sessionName, tmuxName, pid, dispatchGeneration }: {
34
35
  taskId: string;
35
36
  machine: string;
36
37
  channel: string;
@@ -41,6 +42,7 @@ declare function onTaskLaunched({ taskId, machine, channel, scheduleTaskId, task
41
42
  sessionName?: string | null;
42
43
  tmuxName?: string | null;
43
44
  pid?: string | null;
45
+ dispatchGeneration?: string | null;
44
46
  }): Promise<void>;
45
47
  declare function handleTaskProgress({ task_id, machine, cost_usd, turn_count, elapsed_s }: {
46
48
  task_id?: string;
@@ -62,6 +64,7 @@ declare function findPendingTaskMatch({ scheduleTaskId, taskHash, project, taskT
62
64
  taskId: string;
63
65
  }) | null;
64
66
  declare function getTask(taskId: string): PendingTaskEntry | null;
67
+ declare function isTaskTracked(taskHash: string, project: string, generation: string | null): boolean;
65
68
  declare function hasPendingTasks(): boolean;
66
69
  declare function pendingTaskCount(): number;
67
- export { init, onTaskLaunched, handleTaskProgress, clearTask, getPendingTasksForSchedule, findPendingTaskMatch, getTask, hasPendingTasks, pendingTaskCount, buildTrackingMessage, buildTrackingMetaParts, };
70
+ export { init, onTaskLaunched, handleTaskProgress, clearTask, getPendingTasksForSchedule, findPendingTaskMatch, getTask, isTaskTracked, hasPendingTasks, pendingTaskCount, buildTrackingMessage, buildTrackingMetaParts, };
@@ -1,6 +1,6 @@
1
- // input: pending-tasks.json + channel/execution registries
2
- // output: init/onTaskLaunched/handleTaskProgress + trackers
3
- // pos: dispatched task tracking view and Slack status messages
1
+ // input: pending-tasks.json + channel/execution registries + dispatch generation
2
+ // output: generation-aware launch/progress tracking and status messages
3
+ // pos: Durable dispatch tracking used by stop and orphan-claim recovery
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { readFileSync, writeFileSync } from 'fs';
6
6
  import * as path from 'path';
@@ -55,7 +55,7 @@ function buildTrackingMessage({ taskId, machine, taskText, startedAtMs, elapsed_
55
55
  function init(adapter) {
56
56
  _adapter = adapter;
57
57
  }
58
- async function onTaskLaunched({ taskId, machine, channel, scheduleTaskId, taskText, taskHash, project, sessionName, tmuxName, pid }) {
58
+ async function onTaskLaunched({ taskId, machine, channel, scheduleTaskId, taskText, taskHash, project, sessionName, tmuxName, pid, dispatchGeneration }) {
59
59
  executionRegistry.registerDispatchExecution({
60
60
  taskId,
61
61
  machine,
@@ -73,6 +73,7 @@ async function onTaskLaunched({ taskId, machine, channel, scheduleTaskId, taskTe
73
73
  scheduleTaskId: scheduleTaskId || null, taskText: taskText || null, taskHash: taskHash || null,
74
74
  project: project || null, trackingTs: null,
75
75
  sessionName: sessionName || null, tmuxName: tmuxName || null, pid: pid || null,
76
+ dispatchGeneration: dispatchGeneration ?? null,
76
77
  });
77
78
  savePendingTasks();
78
79
  log.info(`Task registered: ${taskId} on ${machine} (channel: ${channel}, project: ${project || 'none'}, schedule: ${scheduleTaskId || 'none'}, pending: ${pendingTasks.size})`);
@@ -154,10 +155,15 @@ function findPendingTaskMatch({ scheduleTaskId, taskHash, project, taskText }) {
154
155
  function getTask(taskId) {
155
156
  return pendingTasks.get(taskId) || null;
156
157
  }
158
+ function isTaskTracked(taskHash, project, generation) {
159
+ return [...pendingTasks.entries()].some(([taskId, task]) => (task.taskHash === taskHash || taskId === taskHash)
160
+ && task.project === project
161
+ && (task.dispatchGeneration ?? null) === generation);
162
+ }
157
163
  function hasPendingTasks() {
158
164
  return pendingTasks.size > 0;
159
165
  }
160
166
  function pendingTaskCount() {
161
167
  return pendingTasks.size;
162
168
  }
163
- export { init, onTaskLaunched, handleTaskProgress, clearTask, getPendingTasksForSchedule, findPendingTaskMatch, getTask, hasPendingTasks, pendingTaskCount, buildTrackingMessage, buildTrackingMetaParts, };
169
+ export { init, onTaskLaunched, handleTaskProgress, clearTask, getPendingTasksForSchedule, findPendingTaskMatch, getTask, isTaskTracked, hasPendingTasks, pendingTaskCount, buildTrackingMessage, buildTrackingMetaParts, };
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ declare function resolveTaskGeneration(project: string | null, taskId: string | null, env?: NodeJS.ProcessEnv): string | null;
2
3
  interface CortexRunArgs {
3
4
  name?: string;
4
5
  device: string;
@@ -21,4 +22,4 @@ declare function getCortexRunHelp(): string;
21
22
  */
22
23
  declare function isHelpRequest(rawArgs: string[]): boolean;
23
24
  declare function parseCliArgs(): CortexRunArgs;
24
- export { parseCliArgs, getCortexRunHelp, isHelpRequest };
25
+ export { parseCliArgs, getCortexRunHelp, isHelpRequest, resolveTaskGeneration };
@@ -1,5 +1,9 @@
1
1
  #!/usr/bin/env node
2
- // cortex-run — CLI dispatch via sendCommand (DR-0011 §4.8 + §4.9).
2
+ // input: task lifecycle, daemon webhook, process environment
3
+ // output: remote launch/cancel CLI with dispatch generation metadata
4
+ // pos: Dispatches cortex-run work through the daemon
5
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
6
+ // cortex-run CLI dispatch via sendCommand (DR-0011 §4.8 + §4.9).
3
7
  //
4
8
  // Launch:
5
9
  // cortex-run [--device <name>] --name <name> [--stall 10m] [--gpu auto]
@@ -79,6 +83,12 @@ async function httpSendCommand(device, command) {
79
83
  clearTimeout(timer);
80
84
  }
81
85
  }
86
+ // --- Types ---
87
+ function resolveTaskGeneration(project, taskId, env = process.env) {
88
+ const sameTask = !!taskId && env.CORTEX_TASK_ID === taskId;
89
+ const sameProject = !!project && env.CORTEX_TASK_PROJECT === project;
90
+ return sameTask && sameProject ? env.CORTEX_TASK_GENERATION ?? null : null;
91
+ }
82
92
  // --- CLI parsing ---
83
93
  function getCortexRunHelp() {
84
94
  return [
@@ -240,6 +250,11 @@ function parseCliArgs() {
240
250
  // --- Launch (DR-0011 §4.8) ---
241
251
  async function cmdLaunch(args) {
242
252
  const device = args.device;
253
+ const hasTaskContext = !!args.project && !!args.taskId
254
+ && process.env.CORTEX_TASK_PROJECT === args.project
255
+ && process.env.CORTEX_TASK_ID === args.taskId;
256
+ const dispatchGeneration = resolveTaskGeneration(args.project, args.taskId);
257
+ const ownership = hasTaskContext ? { generation: dispatchGeneration } : undefined;
243
258
  if (!(await httpIsDeviceOnline(device))) {
244
259
  console.error(`[cortex-run] Error: device "${device}" is not online (cortex-client not connected)`);
245
260
  process.exit(1);
@@ -254,8 +269,12 @@ async function cmdLaunch(args) {
254
269
  // Task linkage: mark pending (belt-and-suspenders, non-blocking)
255
270
  if (args.project && args.taskId) {
256
271
  try {
257
- const result = pendingTask(null, args.project, args.taskId);
258
- if (!result.success) {
272
+ const result = pendingTask(null, args.project, args.taskId, ownership);
273
+ if ('stale' in result && result.stale) {
274
+ console.error(`[cortex-run] Error: ${result.message}`);
275
+ process.exit(1);
276
+ }
277
+ else if (!result.success) {
259
278
  console.error(`[cortex-run] Warning: pendingTask failed: ${result.message}`);
260
279
  }
261
280
  else {
@@ -282,6 +301,7 @@ async function cmdLaunch(args) {
282
301
  logTailBytes: args.logTailBytes,
283
302
  taskProject: args.project,
284
303
  taskId: args.taskId,
304
+ dispatchGeneration,
285
305
  },
286
306
  timeout: 30_000,
287
307
  });
@@ -324,7 +344,7 @@ async function cmdCancel(args) {
324
344
  process.exit(0);
325
345
  }
326
346
  // --- Main entry ---
327
- export { parseCliArgs, getCortexRunHelp, isHelpRequest };
347
+ export { parseCliArgs, getCortexRunHelp, isHelpRequest, resolveTaskGeneration };
328
348
  // Use the shared isMainModule helper so symlink invocations (e.g. via the
329
349
  // global `cortex-run` bin) follow through to realpath comparison. The
330
350
  // hand-rolled `path.resolve` variant previously here did not follow symlinks
@@ -17,6 +17,7 @@ interface ParsedValues {
17
17
  clearDependsOn: boolean;
18
18
  taskIds: string[];
19
19
  subtasksFile: string | null;
20
+ taskFile: string | null;
20
21
  bulkFile: string | null;
21
22
  status: string | null;
22
23
  hasDeps: boolean;
@@ -1,4 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ // input: Task argv, project files, lifecycle operations
3
+ // output: cortex-task command parsing and structured results
4
+ // pos: Task-system command line entry point
5
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
2
6
  import * as fs from 'node:fs';
3
7
  import { isMainModule, listProjectDirs } from '../../../core/utils.js';
4
8
  import { createLogger } from '../../../core/log.js';
@@ -8,11 +12,12 @@ import { VALID_STATUSES, PRIORITY_ORDER, filterTasks, getTaskStats, scanAllTasks
8
12
  import { lintTasks } from '../lint.js';
9
13
  import { recordVerdict, readLedger } from '../acceptance-ledger.js';
10
14
  import { loadConfig, listTemplateNames } from '../../threads/template-loader.js';
11
- import { editTask } from './task-lifecycle-edit.js';
15
+ import { editTask, findTask, readTasks } from './task-lifecycle-edit.js';
12
16
  import { assignIds, validateIds } from './task-id-utils.js';
13
17
  import { approveTask, blockTask, claimTask, clearApprovalTask, pauseTask, pendingTask, reopenTask, requestApprovalTask, resumeTask, unblockTask, unclaimTask, } from './task-state.js';
14
18
  import { completeTask, uncompleteTask } from './task-completion.js';
15
19
  import { addTask, batchEdit, bulkAddTasks, decomposeTask } from './task-mutations.js';
20
+ import { readTaskSpec } from './task-file-input.js';
16
21
  import { stopTask, stopTaskDryRun } from './task-process.js';
17
22
  import { acquireLock, assertLockHeld, getOwnerIdentity, readLock, releaseLock, } from './task-lock.js';
18
23
  const READ_COMMANDS = new Set(['list', 'all', 'query', 'show', 'deps', 'lint', 'stats', 'tree']);
@@ -47,8 +52,8 @@ const COMMAND_FLAG_ALLOWLIST = {
47
52
  show: new Set([...COMMON_FLAGS, '--json', '--task-ids']),
48
53
  deps: new Set([...COMMON_FLAGS, '--json', '--task-ids']),
49
54
  tree: new Set([...COMMON_FLAGS]),
50
- add: new Set([...COMMON_FLAGS, '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on', '--auto-lock', '--no-notify']),
51
- spawn: new Set([...COMMON_FLAGS, '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on', '--auto-lock']),
55
+ add: new Set([...COMMON_FLAGS, '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on', '--task-file', '--auto-lock', '--no-notify']),
56
+ spawn: new Set([...COMMON_FLAGS, '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on', '--task-file', '--auto-lock']),
52
57
  lint: new Set([...COMMON_FLAGS, '--json']),
53
58
  stats: new Set([...COMMON_FLAGS, '--json']),
54
59
  claim: new Set([...COMMON_FLAGS, '--task', '--agent']),
@@ -132,8 +137,8 @@ const HELP_CONFIG = {
132
137
  {
133
138
  heading: 'Mutation',
134
139
  commands: [
135
- { name: 'add', description: 'Add new task (--text, --why, --done-when, --plan, --template ...). Captures origin from env for completion wake.' },
136
- { name: 'spawn', description: 'Create a child of the current task (CORTEX_TASK_ID or --task-id); parent becomes a join node. Pair with the thread_wait tool to await it.' },
140
+ { name: 'add', description: 'Add a task from --task-file or scalar fields. Captures origin from env for completion wake.' },
141
+ { name: 'spawn', description: 'Create a child from --task-file or scalar fields; parent becomes a join node. Pair with thread_wait.' },
137
142
  { name: 'bulk-add', description: 'Bulk-add tasks from JSON file (--file, use "key" for intra-batch deps)' },
138
143
  { name: 'edit', description: 'Edit task fields (--text, --why, --done-when, ...)' },
139
144
  { name: 'batch-edit', description: 'Apply same edit to multiple tasks (--task-ids)' },
@@ -179,6 +184,7 @@ const HELP_CONFIG = {
179
184
  { flag: '--remove-depends-on <id>', description: 'Remove a dependency (edit only, repeatable)' },
180
185
  { flag: '--clear-depends-on', description: 'Clear all dependencies (edit only)' },
181
186
  { flag: '--subtasks-file <path>', description: 'JSON file with subtasks (decompose; use - for stdin)' },
187
+ { flag: '--task-file <path>', description: 'JSON task object for add/spawn (use - for stdin)' },
182
188
  { flag: '--file <path>', description: 'JSON file of tasks (bulk-add; use - for stdin)' },
183
189
  { flag: '--status <status>', description: 'Filter by status (read commands)' },
184
190
  { flag: '--has-deps', description: 'Read-only: tasks with dependencies' },
@@ -198,7 +204,7 @@ const HELP_CONFIG = {
198
204
  examples: [
199
205
  { description: 'List actionable tasks (JSON)', command: 'task list --json' },
200
206
  { description: 'Filter blocked tasks in a project', command: 'task query --project example-project --status blocked --json' },
201
- { description: 'Add a task with two dependencies', command: 'task add --project example-project --text "Run ablation" --why "Isolate variable contribution" --done-when "Results in EXP-017.md" --plan context/projects/example-project/experiments/EXP-017.md --priority high --template <name> --depends-on a111 a112' },
207
+ { description: 'Add a task from structured JSON', command: 'task add --project example-project --task-file /tmp/cortex-task-<unique-id>.json' },
202
208
  { description: 'Complete a task with note', command: 'task complete --project example-project --task-id ab12 --note "Verified: 85% accuracy"' },
203
209
  { description: 'Append a dependency', command: 'task edit --project example-project --task-id ab12 --add-depends-on cd34' },
204
210
  { description: 'Clear dependencies', command: 'task edit --project example-project --task-id ab12 --clear-depends-on' },
@@ -221,6 +227,7 @@ const STRING_OPT_KEYS = {
221
227
  '--priority': 'priority',
222
228
  '--template': 'template',
223
229
  '--subtasks-file': 'subtasksFile',
230
+ '--task-file': 'taskFile',
224
231
  '--file': 'bulkFile',
225
232
  '--status': 'status',
226
233
  '--skip-verify-reason': 'skipVerifyReason',
@@ -263,6 +270,7 @@ function createDefaults() {
263
270
  clearDependsOn: false,
264
271
  taskIds: [],
265
272
  subtasksFile: null,
273
+ taskFile: null,
266
274
  bulkFile: null,
267
275
  status: null,
268
276
  hasDeps: false,
@@ -436,6 +444,25 @@ function validateCommand(command, values) {
436
444
  throw cliError('--project is required');
437
445
  }
438
446
  }
447
+ const TASK_SPEC_FLAGS = [
448
+ '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on',
449
+ ];
450
+ function applyTaskFile(values, seen) {
451
+ if (!values.taskFile)
452
+ return;
453
+ const conflicts = TASK_SPEC_FLAGS.filter((flag) => seen.has(flag));
454
+ if (conflicts.length > 0) {
455
+ throw cliError(`--task-file cannot be combined with scalar task fields: ${conflicts.join(', ')}`);
456
+ }
457
+ const spec = readTaskSpec(values.taskFile);
458
+ values.text = spec.text;
459
+ values.why = spec.why;
460
+ values.doneWhen = spec.doneWhen;
461
+ values.plan = spec.plan;
462
+ values.priority = spec.priority;
463
+ values.template = spec.template;
464
+ values.dependsOn = spec.dependsOn;
465
+ }
439
466
  /** Context-aware defaults: a running agent already knows its project (and current task) via
440
467
  * CORTEX_* env. Fill --project from env for write commands so agents don't re-declare it.
441
468
  * `spawn` lives under the current task, so it prefers that task's project. */
@@ -454,6 +481,7 @@ function parseArgs(argv) {
454
481
  const seen = new Set();
455
482
  parseOptions(split.args, values, seen);
456
483
  validateFlagsForCommand(command, seen);
484
+ applyTaskFile(values, seen);
457
485
  applyContextDefaults(command, values);
458
486
  validateCommand(command, values);
459
487
  return { command, values };
@@ -675,16 +703,23 @@ function handleStop(v) {
675
703
  return v.dryRun ? stopTaskDryRun(v.taskId) : stopTask(v.taskId);
676
704
  }
677
705
  /** Capture provenance from env so task.completed can wake the originating session (Problem 1).
678
- * Suppressed by --no-notify. Returns null when no env context (e.g. a human at a raw shell). */
706
+ * Suppressed by --no-notify. Returns null when no env context (e.g. a human at a raw shell).
707
+ * Inside a thread (CORTEX_THREAD_ID set) only the thread id is recorded: a thread's
708
+ * SLACK_CHANNEL is the dispatch conduit, not a human session — capturing it would wake a
709
+ * context-less session there at completion and pollute the manager-qa escalation walk
710
+ * (which reads origin_channel as "the human who set the work in motion"). Thread-origin
711
+ * tasks are fire-and-forget: completion degrades to a durable project-report notice. */
679
712
  function readOriginFromEnv(noNotify) {
680
713
  if (noNotify)
681
714
  return null;
715
+ const threadId = process.env.CORTEX_THREAD_ID || null;
716
+ if (threadId)
717
+ return { sessionId: null, channel: null, threadId };
682
718
  const channel = process.env.SLACK_CHANNEL || process.env.FEISHU_CHANNEL || null;
683
719
  const sessionId = process.env.CORTEX_SESSION_ID || null;
684
- const threadId = process.env.CORTEX_THREAD_ID || null;
685
- if (!channel && !sessionId && !threadId)
720
+ if (!channel && !sessionId)
686
721
  return null;
687
- return { sessionId, channel, threadId };
722
+ return { sessionId, channel, threadId: null };
688
723
  }
689
724
  const MAX_SPAWN_DEPTH = 6;
690
725
  /** `spawn`: create a single child under the current task (CORTEX_TASK_ID, or --task-id override),
@@ -796,21 +831,36 @@ function handleVerdict(v) {
796
831
  const entry = readLedger(v.project, v.taskId).children[v.child];
797
832
  return { success: true, task_id: v.taskId, child: v.child, verdict: v.verdict, rework_round: entry?.rework_round ?? 0 };
798
833
  }
834
+ function taskOwnership(v) {
835
+ const envTaskId = process.env.CORTEX_TASK_ID;
836
+ const sameProject = process.env.CORTEX_TASK_PROJECT === v.project;
837
+ if (!process.env.CORTEX_THREAD_ID || !envTaskId || !sameProject || !v.project)
838
+ return undefined;
839
+ let selectedId = v.taskId;
840
+ if (!selectedId && v.task) {
841
+ const found = findTask(readTasks(v.project), v.task, null);
842
+ if (!('error' in found))
843
+ selectedId = found.task.id;
844
+ }
845
+ if (selectedId !== envTaskId)
846
+ return undefined;
847
+ return { generation: process.env.CORTEX_TASK_GENERATION ?? null };
848
+ }
799
849
  const WRITE_HANDLERS = {
800
850
  claim: (v) => claimTask(v.task, v.project, v.agent, v.taskId),
801
- unclaim: (v) => unclaimTask(v.task, v.project, v.taskId),
802
- pause: (v) => pauseTask(v.task, v.project, v.taskId),
803
- resume: (v) => resumeTask(v.task, v.project, v.taskId),
804
- pending: (v) => pendingTask(v.task, v.project, v.taskId),
805
- reopen: (v) => reopenTask(v.task, v.project, v.taskId),
806
- complete: (v) => completeTask(v.task, v.project, v.note, v.taskId, v.skipVerify, v.skipVerifyReason),
807
- uncomplete: (v) => uncompleteTask(v.task, v.project, v.taskId),
808
- 'request-approval': (v) => requestApprovalTask(v.task, v.project, v.taskId),
809
- approve: (v) => approveTask(v.task, v.project, v.taskId),
810
- 'clear-approval': (v) => clearApprovalTask(v.task, v.project, v.taskId),
811
- block: (v) => blockTask(v.task, v.project, v.reason, v.taskId),
851
+ unclaim: (v) => unclaimTask(v.task, v.project, v.taskId, taskOwnership(v)),
852
+ pause: (v) => pauseTask(v.task, v.project, v.taskId, taskOwnership(v)),
853
+ resume: (v) => resumeTask(v.task, v.project, v.taskId, taskOwnership(v)),
854
+ pending: (v) => pendingTask(v.task, v.project, v.taskId, taskOwnership(v)),
855
+ reopen: (v) => reopenTask(v.task, v.project, v.taskId, taskOwnership(v)),
856
+ complete: (v) => completeTask(v.task, v.project, v.note, v.taskId, v.skipVerify, v.skipVerifyReason, taskOwnership(v)),
857
+ uncomplete: (v) => uncompleteTask(v.task, v.project, v.taskId, taskOwnership(v)),
858
+ 'request-approval': (v) => requestApprovalTask(v.task, v.project, v.taskId, taskOwnership(v)),
859
+ approve: (v) => approveTask(v.task, v.project, v.taskId, taskOwnership(v)),
860
+ 'clear-approval': (v) => clearApprovalTask(v.task, v.project, v.taskId, taskOwnership(v)),
861
+ block: (v) => blockTask(v.task, v.project, v.reason, v.taskId, taskOwnership(v)),
812
862
  verdict: handleVerdict,
813
- unblock: (v) => unblockTask(v.task, v.project, v.taskId),
863
+ unblock: (v) => unblockTask(v.task, v.project, v.taskId, taskOwnership(v)),
814
864
  add: (v) => addTask(v.project, v.text, v.why, v.doneWhen, v.priority || 'medium', v.template, v.dependsOn.length > 0 ? v.dependsOn : null, v.plan, readOriginFromEnv(v.noNotify)),
815
865
  spawn: handleSpawn,
816
866
  edit: handleEdit,
@@ -1,6 +1,15 @@
1
- declare function completeTask(taskText: string | null, project: string, completionNote?: string, taskId?: string | null, skipVerify?: boolean, skipVerifyReason?: string | null): {
1
+ import { type TaskGenerationExpectation } from '../../../core/task-parser.js';
2
+ declare function completeTaskUnlocked(taskText: string | null, project: string, completionNote?: string, taskId?: string | null, skipVerify?: boolean, skipVerifyReason?: string | null, ownership?: TaskGenerationExpectation): {
2
3
  success: boolean;
3
4
  message: string;
5
+ stale?: undefined;
6
+ task_id?: undefined;
7
+ unblocked?: undefined;
8
+ verify_warning?: undefined;
9
+ } | {
10
+ success: boolean;
11
+ message: string;
12
+ stale: boolean;
4
13
  task_id?: undefined;
5
14
  unblocked?: undefined;
6
15
  verify_warning?: undefined;
@@ -14,9 +23,17 @@ declare function completeTask(taskText: string | null, project: string, completi
14
23
  preview: string;
15
24
  }[];
16
25
  verify_warning: string;
26
+ stale?: undefined;
17
27
  };
18
- declare function uncompleteTask(taskText: string | null, project: string, taskId?: string | null): {
28
+ declare function uncompleteTaskUnlocked(taskText: string | null, project: string, taskId?: string | null, ownership?: TaskGenerationExpectation): {
29
+ success: boolean;
30
+ message: string;
31
+ stale?: undefined;
32
+ } | {
19
33
  success: boolean;
20
34
  message: string;
35
+ stale: boolean;
21
36
  };
37
+ declare const completeTask: typeof completeTaskUnlocked;
38
+ declare const uncompleteTask: typeof uncompleteTaskUnlocked;
22
39
  export { completeTask, uncompleteTask };
@@ -1,12 +1,12 @@
1
- // input: node fs/path/child_process, core paths, task lifecycle
2
- // output: completeTask/uncompleteTask lifecycle transitions
3
- // pos: resolves project commits and persisted artifact evidence
1
+ // input: fs/path, git process, task generation, lifecycle storage
2
+ // output: ownership-first completeTask/uncompleteTask transitions
3
+ // pos: Verifies completion ownership, state and evidence
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import * as fs from 'node:fs';
6
6
  import * as path from 'node:path';
7
7
  import { execFileSync } from 'node:child_process';
8
- import { DATA_DIR, INSTALL_ROOT, PROJECTS_DIR, STORE_DIR, WORKSPACE_DIR, todayISO } from '../../../core/utils.js';
9
- import { clearDependsOnAll, findTask, getTasksPath, readTasks, writeTasks } from './task-lifecycle-edit.js';
8
+ import { DATA_DIR, INSTALL_ROOT, PROJECTS_DIR, STORE_DIR, WORKSPACE_DIR } from '../../../core/utils.js';
9
+ import { clearDependsOnAll, findTask, getTasksPath, readTasks, taskFileProjects, withTaskFileMutationLock, withTaskFileMutationLocks, writeTasks, } from './task-lifecycle-edit.js';
10
10
  const EXPLICIT_SHA = /\b(?:implementation\s+sha|commit(?:\s+sha)?|sha)\s*[:=#]?\s*`?([0-9a-f]{7,40})(?![0-9a-f])`?/gi;
11
11
  function runGit(repo, args, input) {
12
12
  try {
@@ -129,16 +129,13 @@ function completionStateError(task) {
129
129
  return 'Cannot complete a blocked task — unblock it first';
130
130
  return null;
131
131
  }
132
- function loadCompletableTask(taskText, project, taskId) {
132
+ function loadCompletionTask(taskText, project, taskId) {
133
133
  const tasks = readTasks(project);
134
134
  if (tasks.length === 0 && !fs.existsSync(getTasksPath(project))) {
135
135
  return { error: `TASKS.yaml not found for project ${project}` };
136
136
  }
137
137
  const found = findTask(tasks, taskText, taskId);
138
- if ('error' in found)
139
- return found;
140
- const stateError = completionStateError(found.task);
141
- return stateError ? { error: stateError } : { tasks, task: found.task };
138
+ return 'error' in found ? found : { tasks, task: found.task };
142
139
  }
143
140
  function completionWarning(project, task, completionNote, skipVerify, skipVerifyReason) {
144
141
  if (skipVerify)
@@ -147,25 +144,33 @@ function completionWarning(project, task, completionNote, skipVerify, skipVerify
147
144
  return null;
148
145
  return 'no evidence of work: no verified implementation SHA, persisted thread artifact, matching git commit, or Done-when artifact. Re-run with --skip-verify to bypass.';
149
146
  }
150
- function markTaskCompleted(task, completionNote, today) {
147
+ function markTaskCompleted(task, completionNote, completedAt, ownership) {
151
148
  task.status = 'done';
152
149
  task.claimed_by = null;
153
150
  task.claimed_at = null;
151
+ task.dispatch_generation = ownership?.generation ?? null;
154
152
  task.blocked_by = null;
155
153
  task.approval_needed = false;
156
154
  task.paused = false;
157
155
  task.pending_at = null;
158
- task.completed_at = today;
156
+ task.completed_at = completedAt;
159
157
  task.completed_note = completionNote || null;
160
158
  }
161
- function completeTask(taskText, project, completionNote = '', taskId = null, skipVerify = false, skipVerifyReason = null) {
162
- const loaded = loadCompletableTask(taskText, project, taskId);
159
+ function completeTaskUnlocked(taskText, project, completionNote = '', taskId = null, skipVerify = false, skipVerifyReason = null, ownership) {
160
+ const loaded = loadCompletionTask(taskText, project, taskId);
163
161
  if ('error' in loaded)
164
162
  return { success: false, message: loaded.error };
165
163
  const { task, tasks } = loaded;
164
+ if (ownership && task.dispatch_generation !== ownership.generation) {
165
+ return { success: false, message: 'Stale task dispatch generation; completion ignored', stale: true };
166
+ }
167
+ const stateError = completionStateError(task);
168
+ if (stateError)
169
+ return { success: false, message: stateError };
166
170
  const verifyWarning = completionWarning(project, task, completionNote, skipVerify, skipVerifyReason);
167
- const today = todayISO();
168
- markTaskCompleted(task, completionNote, today);
171
+ const completedAt = new Date().toISOString();
172
+ const today = completedAt.slice(0, 10);
173
+ markTaskCompleted(task, completionNote, completedAt, ownership);
169
174
  writeTasks(project, tasks);
170
175
  const unblockResult = task.id ? clearDependsOnAll(task.id) : { count: 0, tasks: [] };
171
176
  let message = `Task completed on ${today}`;
@@ -175,7 +180,7 @@ function completeTask(taskText, project, completionNote = '', taskId = null, ski
175
180
  }
176
181
  return { success: true, message, task_id: task.id, unblocked: unblockResult.tasks, verify_warning: verifyWarning };
177
182
  }
178
- function uncompleteTask(taskText, project, taskId = null) {
183
+ function uncompleteTaskUnlocked(taskText, project, taskId = null, ownership) {
179
184
  const tasks = readTasks(project);
180
185
  if (tasks.length === 0 && !fs.existsSync(getTasksPath(project))) {
181
186
  return { success: false, message: `TASKS.yaml not found for project ${project}` };
@@ -184,12 +189,21 @@ function uncompleteTask(taskText, project, taskId = null) {
184
189
  if ('error' in found)
185
190
  return { success: false, message: found.error };
186
191
  const task = found.task;
192
+ if (ownership && task.dispatch_generation !== ownership.generation) {
193
+ return { success: false, message: 'Stale task dispatch generation; mutation ignored', stale: true };
194
+ }
187
195
  if (task.status !== 'done')
188
196
  return { success: false, message: 'Task is not completed' };
189
197
  task.status = 'open';
190
198
  task.completed_at = null;
191
199
  task.completed_note = null;
200
+ task.dispatch_generation = null;
192
201
  writeTasks(project, tasks);
193
202
  return { success: true, message: 'Task marked as incomplete' };
194
203
  }
204
+ function lockCompletionMutation(mutation) {
205
+ return ((...args) => withTaskFileMutationLock(args[1], () => mutation(...args)));
206
+ }
207
+ const completeTask = ((...args) => withTaskFileMutationLocks([...taskFileProjects(), args[1]], () => completeTaskUnlocked(...args)));
208
+ const uncompleteTask = lockCompletionMutation(uncompleteTaskUnlocked);
195
209
  export { completeTask, uncompleteTask };
@@ -0,0 +1,10 @@
1
+ export interface TaskFileSpec {
2
+ text: string;
3
+ why: string | null;
4
+ doneWhen: string | null;
5
+ plan: string | null;
6
+ priority: string | null;
7
+ template: string | null;
8
+ dependsOn: string[];
9
+ }
10
+ export declare function readTaskSpec(source: string, readStdin?: () => string): TaskFileSpec;