@cortex-agent/server 2026.5.19-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (503) hide show
  1. package/defaults/.claude/settings.json +13 -0
  2. package/defaults/CORTEX.md +15 -0
  3. package/defaults/config/budget.json +4 -0
  4. package/defaults/config/session-hooks.json +7 -0
  5. package/defaults/config/thread-templates.json +528 -0
  6. package/defaults/context/CORTEX.md +40 -0
  7. package/defaults/context/decisions/DR-0012.md +54 -0
  8. package/defaults/context/ideas/CORTEX.md +10 -0
  9. package/defaults/context/projects/CORTEX.md +25 -0
  10. package/defaults/context/scans/CORTEX.md +13 -0
  11. package/defaults/context/user/CORTEX.md +21 -0
  12. package/defaults/data/schedules.json +52 -0
  13. package/defaults/gitignore +44 -0
  14. package/defaults/hooks/ask-user-question-hook.mjs +66 -0
  15. package/defaults/hooks/cortex-md-injector.mjs +237 -0
  16. package/defaults/hooks/exit-plan-mode-hook.mjs +84 -0
  17. package/defaults/hooks/memory-ref-tracker.mjs +154 -0
  18. package/defaults/hooks/new-session-hook.mjs +83 -0
  19. package/defaults/hooks/post-task-hook.mjs +63 -0
  20. package/defaults/hooks/rules-loader.mjs +212 -0
  21. package/defaults/hooks/sensitive-file-edit.mjs +84 -0
  22. package/defaults/hooks/session-activity-tracker.mjs +254 -0
  23. package/defaults/hooks/task-status-check.mjs +218 -0
  24. package/defaults/hooks/tasks-yaml-guard.mjs +230 -0
  25. package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +5 -0
  26. package/defaults/plugins/cortex-coder/skills/cli-standards/SKILL.md +208 -0
  27. package/defaults/plugins/cortex-coder/skills/code-standards/SKILL.md +146 -0
  28. package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +164 -0
  29. package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +5 -0
  30. package/defaults/plugins/cortex-common/skills/compound/SKILL.md +349 -0
  31. package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +104 -0
  32. package/defaults/plugins/cortex-common/skills/critique/SKILL.md +88 -0
  33. package/defaults/plugins/cortex-common/skills/debug-campaign/SKILL.md +508 -0
  34. package/defaults/plugins/cortex-common/skills/diagnose/SKILL.md +169 -0
  35. package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +135 -0
  36. package/defaults/plugins/cortex-common/skills/solution-design/SKILL.md +183 -0
  37. package/defaults/plugins/cortex-common/skills/synthesize/SKILL.md +120 -0
  38. package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +5 -0
  39. package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +89 -0
  40. package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +163 -0
  41. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +425 -0
  42. package/defaults/plugins/cortex-system/.claude-plugin/plugin.json +5 -0
  43. package/defaults/plugins/cortex-system/skills/approval/SKILL.md +84 -0
  44. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +199 -0
  45. package/defaults/plugins/cortex-system/skills/deep-retrospective/CORTEX.md +8 -0
  46. package/defaults/plugins/cortex-system/skills/deep-retrospective/SKILL.md +201 -0
  47. package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/CORTEX.md +8 -0
  48. package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/extract_session.py +165 -0
  49. package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/scan_logs.py +402 -0
  50. package/defaults/plugins/cortex-system/skills/evolve/SKILL.md +115 -0
  51. package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +262 -0
  52. package/defaults/plugins/cortex-system/skills/gravity/SKILL.md +125 -0
  53. package/defaults/plugins/cortex-system/skills/orient/SKILL.md +310 -0
  54. package/defaults/plugins/cortex-system/skills/orient-project/SKILL.md +85 -0
  55. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +167 -0
  56. package/defaults/plugins/cortex-system/skills/refresh-skills/SKILL.md +153 -0
  57. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +209 -0
  58. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +478 -0
  59. package/defaults/plugins/cortex-system/skills/user-learn/SKILL.md +95 -0
  60. package/defaults/prompts/directives/coder-reviewer.md +106 -0
  61. package/defaults/prompts/directives/coder.md +90 -0
  62. package/defaults/prompts/directives/director.md +97 -0
  63. package/defaults/prompts/directives/doc-reviewer.md +93 -0
  64. package/defaults/prompts/directives/doc-writer.md +85 -0
  65. package/defaults/prompts/directives/executor-reviewer.md +96 -0
  66. package/defaults/prompts/directives/executor.md +85 -0
  67. package/defaults/prompts/directives/milestone-executor.md +119 -0
  68. package/defaults/prompts/directives/milestone-reviewer.md +108 -0
  69. package/defaults/prompts/directives/plan-executor.md +121 -0
  70. package/defaults/prompts/directives/plan-reviewer.md +99 -0
  71. package/defaults/prompts/systemPrompts/coder.md +64 -0
  72. package/defaults/prompts/systemPrompts/direct.md +92 -0
  73. package/defaults/prompts/systemPrompts/web-opus-4-6.md +68 -0
  74. package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +76 -0
  75. package/defaults/prompts/systemPrompts/web.md +50 -0
  76. package/defaults/prompts/systemPrompts/worker.md +67 -0
  77. package/defaults/rules/correction-propagation.md +31 -0
  78. package/defaults/rules/decision-records.md +49 -0
  79. package/defaults/rules/experiment-format.md +165 -0
  80. package/defaults/rules/issues-md.md +37 -0
  81. package/defaults/rules/meta-conventions.md +45 -0
  82. package/defaults/rules/mission-md.md +47 -0
  83. package/defaults/rules/overview-md.md +41 -0
  84. package/defaults/rules/roadmap-md.md +55 -0
  85. package/defaults/rules/status-md.md +49 -0
  86. package/defaults/rules/task-system.md +53 -0
  87. package/dist/agent-adapter/capabilities.d.ts +12 -0
  88. package/dist/agent-adapter/capabilities.js +52 -0
  89. package/dist/agent-adapter/claude/adapter-tui.d.ts +140 -0
  90. package/dist/agent-adapter/claude/adapter-tui.js +422 -0
  91. package/dist/agent-adapter/claude/adapter.d.ts +85 -0
  92. package/dist/agent-adapter/claude/adapter.js +771 -0
  93. package/dist/agent-adapter/claude/cost-from-usage.d.ts +62 -0
  94. package/dist/agent-adapter/claude/cost-from-usage.js +97 -0
  95. package/dist/agent-adapter/claude/defaults.d.ts +30 -0
  96. package/dist/agent-adapter/claude/defaults.js +49 -0
  97. package/dist/agent-adapter/claude/event-parser.d.ts +28 -0
  98. package/dist/agent-adapter/claude/event-parser.js +173 -0
  99. package/dist/agent-adapter/claude/hooks-builder.d.ts +36 -0
  100. package/dist/agent-adapter/claude/hooks-builder.js +57 -0
  101. package/dist/agent-adapter/claude/jsonl-tail.d.ts +68 -0
  102. package/dist/agent-adapter/claude/jsonl-tail.js +344 -0
  103. package/dist/agent-adapter/claude/spawn-args.d.ts +38 -0
  104. package/dist/agent-adapter/claude/spawn-args.js +83 -0
  105. package/dist/agent-adapter/claude/tmux-control.d.ts +69 -0
  106. package/dist/agent-adapter/claude/tmux-control.js +127 -0
  107. package/dist/agent-adapter/claude/tool-summarizers.d.ts +2 -0
  108. package/dist/agent-adapter/claude/tool-summarizers.js +24 -0
  109. package/dist/agent-adapter/codex/adapter.d.ts +42 -0
  110. package/dist/agent-adapter/codex/adapter.js +916 -0
  111. package/dist/agent-adapter/codex/event-parser.d.ts +17 -0
  112. package/dist/agent-adapter/codex/event-parser.js +41 -0
  113. package/dist/agent-adapter/codex/spawn-args.d.ts +6 -0
  114. package/dist/agent-adapter/codex/spawn-args.js +30 -0
  115. package/dist/agent-adapter/index.d.ts +8 -0
  116. package/dist/agent-adapter/index.js +33 -0
  117. package/dist/agent-adapter/normalize/event-stream.d.ts +6 -0
  118. package/dist/agent-adapter/normalize/event-stream.js +47 -0
  119. package/dist/agent-adapter/normalize/event-types.d.ts +58 -0
  120. package/dist/agent-adapter/normalize/event-types.js +5 -0
  121. package/dist/agent-adapter/normalize/hooks.d.ts +26 -0
  122. package/dist/agent-adapter/normalize/hooks.js +5 -0
  123. package/dist/agent-adapter/normalize/prompt-builder.d.ts +6 -0
  124. package/dist/agent-adapter/normalize/prompt-builder.js +23 -0
  125. package/dist/agent-adapter/normalize/tool-names.d.ts +6 -0
  126. package/dist/agent-adapter/normalize/tool-names.js +73 -0
  127. package/dist/agent-adapter/pi/adapter.d.ts +60 -0
  128. package/dist/agent-adapter/pi/adapter.js +626 -0
  129. package/dist/agent-adapter/pi/agent-dir.d.ts +11 -0
  130. package/dist/agent-adapter/pi/agent-dir.js +34 -0
  131. package/dist/agent-adapter/pi/event-parser.d.ts +26 -0
  132. package/dist/agent-adapter/pi/event-parser.js +313 -0
  133. package/dist/agent-adapter/pi/framing.d.ts +6 -0
  134. package/dist/agent-adapter/pi/framing.js +35 -0
  135. package/dist/agent-adapter/pi/hook-bridge.d.ts +59 -0
  136. package/dist/agent-adapter/pi/hook-bridge.js +233 -0
  137. package/dist/agent-adapter/pi/mcp-bridge.d.ts +26 -0
  138. package/dist/agent-adapter/pi/mcp-bridge.js +140 -0
  139. package/dist/agent-adapter/pi/pi-ext-types.d.ts +90 -0
  140. package/dist/agent-adapter/pi/pi-ext-types.js +5 -0
  141. package/dist/agent-adapter/pi/spawn-args.d.ts +20 -0
  142. package/dist/agent-adapter/pi/spawn-args.js +54 -0
  143. package/dist/agent-adapter/pi/tool-shims.d.ts +2 -0
  144. package/dist/agent-adapter/pi/tool-shims.js +181 -0
  145. package/dist/agent-adapter/types.d.ts +94 -0
  146. package/dist/agent-adapter/types.js +5 -0
  147. package/dist/core/async-mutex.d.ts +6 -0
  148. package/dist/core/async-mutex.js +36 -0
  149. package/dist/core/cli-utils.d.ts +37 -0
  150. package/dist/core/cli-utils.js +69 -0
  151. package/dist/core/config-generator.d.ts +9 -0
  152. package/dist/core/config-generator.js +58 -0
  153. package/dist/core/gateway-generator.d.ts +46 -0
  154. package/dist/core/gateway-generator.js +336 -0
  155. package/dist/core/log.d.ts +7 -0
  156. package/dist/core/log.js +103 -0
  157. package/dist/core/paths.d.ts +32 -0
  158. package/dist/core/paths.js +49 -0
  159. package/dist/core/profile-generator.d.ts +65 -0
  160. package/dist/core/profile-generator.js +310 -0
  161. package/dist/core/running-executions.d.ts +88 -0
  162. package/dist/core/running-executions.js +186 -0
  163. package/dist/core/status-format.d.ts +18 -0
  164. package/dist/core/status-format.js +31 -0
  165. package/dist/core/task-parser.d.ts +69 -0
  166. package/dist/core/task-parser.js +423 -0
  167. package/dist/core/types/agent-types.d.ts +31 -0
  168. package/dist/core/types/agent-types.js +5 -0
  169. package/dist/core/types/thread-types.d.ts +261 -0
  170. package/dist/core/types/thread-types.js +5 -0
  171. package/dist/core/utils.d.ts +29 -0
  172. package/dist/core/utils.js +98 -0
  173. package/dist/core/version.d.ts +3 -0
  174. package/dist/core/version.js +12 -0
  175. package/dist/domain/agents/config.d.ts +58 -0
  176. package/dist/domain/agents/config.js +313 -0
  177. package/dist/domain/agents/facade.d.ts +52 -0
  178. package/dist/domain/agents/facade.js +264 -0
  179. package/dist/domain/agents/index.d.ts +2 -0
  180. package/dist/domain/agents/index.js +4 -0
  181. package/dist/domain/agents/profile-manager.d.ts +54 -0
  182. package/dist/domain/agents/profile-manager.js +161 -0
  183. package/dist/domain/costs/codex-event-format.d.ts +4 -0
  184. package/dist/domain/costs/codex-event-format.js +66 -0
  185. package/dist/domain/costs/codex-usage-monitor.d.ts +7 -0
  186. package/dist/domain/costs/codex-usage-monitor.js +72 -0
  187. package/dist/domain/costs/cost-tracker.d.ts +115 -0
  188. package/dist/domain/costs/cost-tracker.js +327 -0
  189. package/dist/domain/costs/gateway-manager.d.ts +6 -0
  190. package/dist/domain/costs/gateway-manager.js +228 -0
  191. package/dist/domain/costs/rate-limit-parser.d.ts +11 -0
  192. package/dist/domain/costs/rate-limit-parser.js +87 -0
  193. package/dist/domain/costs/rate-limit-throttle.d.ts +32 -0
  194. package/dist/domain/costs/rate-limit-throttle.js +129 -0
  195. package/dist/domain/executions/registry.d.ts +20 -0
  196. package/dist/domain/executions/registry.js +124 -0
  197. package/dist/domain/mcp/core-server.d.ts +2 -0
  198. package/dist/domain/mcp/core-server.js +34 -0
  199. package/dist/domain/mcp/server.d.ts +3 -0
  200. package/dist/domain/mcp/server.js +78 -0
  201. package/dist/domain/mcp/tools/context.d.ts +23 -0
  202. package/dist/domain/mcp/tools/context.js +51 -0
  203. package/dist/domain/mcp/tools/cortex-md.d.ts +17 -0
  204. package/dist/domain/mcp/tools/cortex-md.js +36 -0
  205. package/dist/domain/mcp/tools/cost.d.ts +2 -0
  206. package/dist/domain/mcp/tools/cost.js +54 -0
  207. package/dist/domain/mcp/tools/executions.d.ts +2 -0
  208. package/dist/domain/mcp/tools/executions.js +94 -0
  209. package/dist/domain/mcp/tools/schedule.d.ts +23 -0
  210. package/dist/domain/mcp/tools/schedule.js +245 -0
  211. package/dist/domain/mcp/tools/slack.d.ts +21 -0
  212. package/dist/domain/mcp/tools/slack.js +124 -0
  213. package/dist/domain/mcp/tools/task-ops.d.ts +2 -0
  214. package/dist/domain/mcp/tools/task-ops.js +509 -0
  215. package/dist/domain/mcp/tools/tui-ask.d.ts +31 -0
  216. package/dist/domain/mcp/tools/tui-ask.js +108 -0
  217. package/dist/domain/mcp/tools/tui-plan.d.ts +28 -0
  218. package/dist/domain/mcp/tools/tui-plan.js +118 -0
  219. package/dist/domain/mcp/tui-server.d.ts +2 -0
  220. package/dist/domain/mcp/tui-server.js +69 -0
  221. package/dist/domain/memory/consolidate.d.ts +55 -0
  222. package/dist/domain/memory/consolidate.js +471 -0
  223. package/dist/domain/memory/cortex-md-injector.d.ts +30 -0
  224. package/dist/domain/memory/cortex-md-injector.js +123 -0
  225. package/dist/domain/memory/cortex-md-scanner.d.ts +9 -0
  226. package/dist/domain/memory/cortex-md-scanner.js +67 -0
  227. package/dist/domain/memory/index-regen.d.ts +19 -0
  228. package/dist/domain/memory/index-regen.js +398 -0
  229. package/dist/domain/memory/rules-loader.d.ts +27 -0
  230. package/dist/domain/memory/rules-loader.js +97 -0
  231. package/dist/domain/memory/skill-scanner.d.ts +5 -0
  232. package/dist/domain/memory/skill-scanner.js +132 -0
  233. package/dist/domain/memory/user-context.d.ts +5 -0
  234. package/dist/domain/memory/user-context.js +34 -0
  235. package/dist/domain/memory/watcher.d.ts +2 -0
  236. package/dist/domain/memory/watcher.js +81 -0
  237. package/dist/domain/monitor/disk-monitor.d.ts +20 -0
  238. package/dist/domain/monitor/disk-monitor.js +97 -0
  239. package/dist/domain/monitor/gpu-monitor.d.ts +26 -0
  240. package/dist/domain/monitor/gpu-monitor.js +135 -0
  241. package/dist/domain/remote/client-bootstrap.d.ts +1 -0
  242. package/dist/domain/remote/client-bootstrap.js +139 -0
  243. package/dist/domain/remote/client-hot-reload.d.ts +18 -0
  244. package/dist/domain/remote/client-hot-reload.js +142 -0
  245. package/dist/domain/remote/client-manager.d.ts +50 -0
  246. package/dist/domain/remote/client-manager.js +452 -0
  247. package/dist/domain/remote/cortex-client.d.ts +1 -0
  248. package/dist/domain/remote/cortex-client.js +704 -0
  249. package/dist/domain/scheduling/job-registry.d.ts +31 -0
  250. package/dist/domain/scheduling/job-registry.js +34 -0
  251. package/dist/domain/scheduling/jobs/_shared.d.ts +14 -0
  252. package/dist/domain/scheduling/jobs/_shared.js +45 -0
  253. package/dist/domain/scheduling/jobs/memory-index-regen.d.ts +1 -0
  254. package/dist/domain/scheduling/jobs/memory-index-regen.js +16 -0
  255. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +11 -0
  256. package/dist/domain/scheduling/jobs/scheduled-task.js +186 -0
  257. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +41 -0
  258. package/dist/domain/scheduling/jobs/target-dispatch.js +48 -0
  259. package/dist/domain/scheduling/jobs/task-archive.d.ts +1 -0
  260. package/dist/domain/scheduling/jobs/task-archive.js +19 -0
  261. package/dist/domain/scheduling/jobs/task-dispatch.d.ts +12 -0
  262. package/dist/domain/scheduling/jobs/task-dispatch.js +214 -0
  263. package/dist/domain/scheduling/runner.d.ts +13 -0
  264. package/dist/domain/scheduling/runner.js +24 -0
  265. package/dist/domain/scheduling/schedule-cli.d.ts +16 -0
  266. package/dist/domain/scheduling/schedule-cli.js +268 -0
  267. package/dist/domain/scheduling/schedule-command.d.ts +4 -0
  268. package/dist/domain/scheduling/schedule-command.js +274 -0
  269. package/dist/domain/scheduling/scheduler.d.ts +86 -0
  270. package/dist/domain/scheduling/scheduler.js +544 -0
  271. package/dist/domain/sessions/session-backup.d.ts +49 -0
  272. package/dist/domain/sessions/session-backup.js +217 -0
  273. package/dist/domain/sessions/session-hooks.d.ts +103 -0
  274. package/dist/domain/sessions/session-hooks.js +311 -0
  275. package/dist/domain/sessions/session-registry.d.ts +21 -0
  276. package/dist/domain/sessions/session-registry.js +31 -0
  277. package/dist/domain/sessions/session.d.ts +3 -0
  278. package/dist/domain/sessions/session.js +14 -0
  279. package/dist/domain/tasks/archiver.d.ts +9 -0
  280. package/dist/domain/tasks/archiver.js +123 -0
  281. package/dist/domain/tasks/dispatch-utils.d.ts +37 -0
  282. package/dist/domain/tasks/dispatch-utils.js +143 -0
  283. package/dist/domain/tasks/dispatcher.d.ts +48 -0
  284. package/dist/domain/tasks/dispatcher.js +285 -0
  285. package/dist/domain/tasks/lint.d.ts +12 -0
  286. package/dist/domain/tasks/lint.js +102 -0
  287. package/dist/domain/tasks/mutator.d.ts +21 -0
  288. package/dist/domain/tasks/mutator.js +208 -0
  289. package/dist/domain/tasks/parser.d.ts +1 -0
  290. package/dist/domain/tasks/parser.js +6 -0
  291. package/dist/domain/tasks/pending-tracker.d.ts +67 -0
  292. package/dist/domain/tasks/pending-tracker.js +163 -0
  293. package/dist/domain/tasks/recommendation/extractor.d.ts +12 -0
  294. package/dist/domain/tasks/recommendation/extractor.js +563 -0
  295. package/dist/domain/tasks/recommendation/patterns.d.ts +11 -0
  296. package/dist/domain/tasks/recommendation/patterns.js +99 -0
  297. package/dist/domain/tasks/recommendation/types.d.ts +67 -0
  298. package/dist/domain/tasks/recommendation/types.js +5 -0
  299. package/dist/domain/tasks/store.d.ts +1 -0
  300. package/dist/domain/tasks/store.js +3 -0
  301. package/dist/domain/tasks/system/cortex-run.d.ts +24 -0
  302. package/dist/domain/tasks/system/cortex-run.js +342 -0
  303. package/dist/domain/tasks/system/task-cli.d.ts +49 -0
  304. package/dist/domain/tasks/system/task-cli.js +664 -0
  305. package/dist/domain/tasks/system/task-completion.d.ts +22 -0
  306. package/dist/domain/tasks/system/task-completion.js +89 -0
  307. package/dist/domain/tasks/system/task-id-utils.d.ts +24 -0
  308. package/dist/domain/tasks/system/task-id-utils.js +84 -0
  309. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +34 -0
  310. package/dist/domain/tasks/system/task-lifecycle-edit.js +208 -0
  311. package/dist/domain/tasks/system/task-lock.d.ts +25 -0
  312. package/dist/domain/tasks/system/task-lock.js +139 -0
  313. package/dist/domain/tasks/system/task-mutations.d.ts +31 -0
  314. package/dist/domain/tasks/system/task-mutations.js +110 -0
  315. package/dist/domain/tasks/system/task-process.d.ts +37 -0
  316. package/dist/domain/tasks/system/task-process.js +119 -0
  317. package/dist/domain/tasks/system/task-state.d.ts +70 -0
  318. package/dist/domain/tasks/system/task-state.js +176 -0
  319. package/dist/domain/threads/artifact-io.d.ts +18 -0
  320. package/dist/domain/threads/artifact-io.js +182 -0
  321. package/dist/domain/threads/auto-thread.d.ts +3 -0
  322. package/dist/domain/threads/auto-thread.js +19 -0
  323. package/dist/domain/threads/hook-runner.d.ts +4 -0
  324. package/dist/domain/threads/hook-runner.js +250 -0
  325. package/dist/domain/threads/index.d.ts +5 -0
  326. package/dist/domain/threads/index.js +7 -0
  327. package/dist/domain/threads/prompt-builder.d.ts +25 -0
  328. package/dist/domain/threads/prompt-builder.js +176 -0
  329. package/dist/domain/threads/runner.d.ts +83 -0
  330. package/dist/domain/threads/runner.js +434 -0
  331. package/dist/domain/threads/state-machine.d.ts +61 -0
  332. package/dist/domain/threads/state-machine.js +440 -0
  333. package/dist/domain/threads/template-loader.d.ts +20 -0
  334. package/dist/domain/threads/template-loader.js +189 -0
  335. package/dist/domain/threads/template-resolver.d.ts +1 -0
  336. package/dist/domain/threads/template-resolver.js +95 -0
  337. package/dist/domain/threads/utils.d.ts +19 -0
  338. package/dist/domain/threads/utils.js +49 -0
  339. package/dist/entry/app.d.ts +1 -0
  340. package/dist/entry/app.js +234 -0
  341. package/dist/entry/cli.d.ts +12 -0
  342. package/dist/entry/cli.js +254 -0
  343. package/dist/entry/daemon.d.ts +11 -0
  344. package/dist/entry/daemon.js +521 -0
  345. package/dist/entry/init.d.ts +93 -0
  346. package/dist/entry/init.js +1299 -0
  347. package/dist/entry/startup-helpers.d.ts +2 -0
  348. package/dist/entry/startup-helpers.js +56 -0
  349. package/dist/entry/startup-notify.d.ts +10 -0
  350. package/dist/entry/startup-notify.js +20 -0
  351. package/dist/events/event-bus.d.ts +42 -0
  352. package/dist/events/event-bus.js +84 -0
  353. package/dist/events/event-logger.d.ts +12 -0
  354. package/dist/events/event-logger.js +135 -0
  355. package/dist/events/event-replay.d.ts +1 -0
  356. package/dist/events/event-replay.js +51 -0
  357. package/dist/events/event-types.d.ts +145 -0
  358. package/dist/events/event-types.js +5 -0
  359. package/dist/events/index.d.ts +5 -0
  360. package/dist/events/index.js +6 -0
  361. package/dist/hooks/ask-user-question-hook.mjs +66 -0
  362. package/dist/hooks/cortex-md-injector.mjs +237 -0
  363. package/dist/hooks/exit-plan-mode-hook.mjs +84 -0
  364. package/dist/hooks/memory-ref-tracker.mjs +154 -0
  365. package/dist/hooks/new-session-hook.mjs +83 -0
  366. package/dist/hooks/post-task-hook.mjs +63 -0
  367. package/dist/hooks/rules-loader.mjs +212 -0
  368. package/dist/hooks/sensitive-file-edit.mjs +84 -0
  369. package/dist/hooks/session-activity-tracker.mjs +254 -0
  370. package/dist/hooks/task-status-check.mjs +218 -0
  371. package/dist/hooks/tasks-yaml-guard.mjs +230 -0
  372. package/dist/orchestration/agent-runner.d.ts +72 -0
  373. package/dist/orchestration/agent-runner.js +289 -0
  374. package/dist/orchestration/busy-tracker.d.ts +12 -0
  375. package/dist/orchestration/busy-tracker.js +35 -0
  376. package/dist/orchestration/channel-queue.d.ts +18 -0
  377. package/dist/orchestration/channel-queue.js +32 -0
  378. package/dist/orchestration/dispatch-reconciler.d.ts +1 -0
  379. package/dist/orchestration/dispatch-reconciler.js +16 -0
  380. package/dist/orchestration/durable-helpers.d.ts +4 -0
  381. package/dist/orchestration/durable-helpers.js +42 -0
  382. package/dist/orchestration/interactions/ask-user-question.d.ts +32 -0
  383. package/dist/orchestration/interactions/ask-user-question.js +182 -0
  384. package/dist/orchestration/interactions/command-action-router.d.ts +47 -0
  385. package/dist/orchestration/interactions/command-action-router.js +91 -0
  386. package/dist/orchestration/interactions/interaction-handlers.d.ts +5 -0
  387. package/dist/orchestration/interactions/interaction-handlers.js +279 -0
  388. package/dist/orchestration/interactions/plan-approvals.d.ts +47 -0
  389. package/dist/orchestration/interactions/plan-approvals.js +77 -0
  390. package/dist/orchestration/interactions/plan-handler.d.ts +6 -0
  391. package/dist/orchestration/interactions/plan-handler.js +12 -0
  392. package/dist/orchestration/lifecycle.d.ts +50 -0
  393. package/dist/orchestration/lifecycle.js +308 -0
  394. package/dist/orchestration/orchestrator.d.ts +29 -0
  395. package/dist/orchestration/orchestrator.js +25 -0
  396. package/dist/orchestration/routing/commands/cancel.d.ts +10 -0
  397. package/dist/orchestration/routing/commands/cancel.js +136 -0
  398. package/dist/orchestration/routing/commands/channel.d.ts +11 -0
  399. package/dist/orchestration/routing/commands/channel.js +219 -0
  400. package/dist/orchestration/routing/commands/command-context.d.ts +29 -0
  401. package/dist/orchestration/routing/commands/command-context.js +4 -0
  402. package/dist/orchestration/routing/commands/cost.d.ts +3 -0
  403. package/dist/orchestration/routing/commands/cost.js +22 -0
  404. package/dist/orchestration/routing/commands/device.d.ts +6 -0
  405. package/dist/orchestration/routing/commands/device.js +83 -0
  406. package/dist/orchestration/routing/commands/dispatch.d.ts +2 -0
  407. package/dist/orchestration/routing/commands/dispatch.js +49 -0
  408. package/dist/orchestration/routing/commands/index.d.ts +15 -0
  409. package/dist/orchestration/routing/commands/index.js +130 -0
  410. package/dist/orchestration/routing/commands/mode.d.ts +13 -0
  411. package/dist/orchestration/routing/commands/mode.js +290 -0
  412. package/dist/orchestration/routing/commands/nvtop.d.ts +3 -0
  413. package/dist/orchestration/routing/commands/nvtop.js +103 -0
  414. package/dist/orchestration/routing/commands/orient.d.ts +2 -0
  415. package/dist/orchestration/routing/commands/orient.js +3 -0
  416. package/dist/orchestration/routing/commands/schedule.d.ts +4 -0
  417. package/dist/orchestration/routing/commands/schedule.js +132 -0
  418. package/dist/orchestration/routing/commands/sendfile.d.ts +2 -0
  419. package/dist/orchestration/routing/commands/sendfile.js +92 -0
  420. package/dist/orchestration/routing/commands/session.d.ts +9 -0
  421. package/dist/orchestration/routing/commands/session.js +153 -0
  422. package/dist/orchestration/routing/commands/status.d.ts +7 -0
  423. package/dist/orchestration/routing/commands/status.js +180 -0
  424. package/dist/orchestration/routing/commands/tail.d.ts +2 -0
  425. package/dist/orchestration/routing/commands/tail.js +73 -0
  426. package/dist/orchestration/routing/commands/task.d.ts +6 -0
  427. package/dist/orchestration/routing/commands/task.js +142 -0
  428. package/dist/orchestration/routing/commands/thread-handlers.d.ts +2 -0
  429. package/dist/orchestration/routing/commands/thread-handlers.js +138 -0
  430. package/dist/orchestration/routing/commands/thread.d.ts +2 -0
  431. package/dist/orchestration/routing/commands/thread.js +2 -0
  432. package/dist/orchestration/routing/edit-handler.d.ts +24 -0
  433. package/dist/orchestration/routing/edit-handler.js +161 -0
  434. package/dist/orchestration/routing/file-handler.d.ts +6 -0
  435. package/dist/orchestration/routing/file-handler.js +23 -0
  436. package/dist/orchestration/routing/hook-bridge-subscribers.d.ts +4 -0
  437. package/dist/orchestration/routing/hook-bridge-subscribers.js +79 -0
  438. package/dist/orchestration/routing/hook-bridge.d.ts +30 -0
  439. package/dist/orchestration/routing/hook-bridge.js +112 -0
  440. package/dist/orchestration/routing/message-router.d.ts +6 -0
  441. package/dist/orchestration/routing/message-router.js +70 -0
  442. package/dist/orchestration/routing/webhook.d.ts +10 -0
  443. package/dist/orchestration/routing/webhook.js +239 -0
  444. package/dist/orchestration/status-helpers.d.ts +66 -0
  445. package/dist/orchestration/status-helpers.js +222 -0
  446. package/dist/orchestration/superseded-edits.d.ts +22 -0
  447. package/dist/orchestration/superseded-edits.js +31 -0
  448. package/dist/orchestration/thread-executor.d.ts +31 -0
  449. package/dist/orchestration/thread-executor.js +234 -0
  450. package/dist/platform/adapter.d.ts +28 -0
  451. package/dist/platform/adapter.js +5 -0
  452. package/dist/platform/adapters/feishu.d.ts +66 -0
  453. package/dist/platform/adapters/feishu.js +558 -0
  454. package/dist/platform/adapters/index.d.ts +16 -0
  455. package/dist/platform/adapters/index.js +65 -0
  456. package/dist/platform/adapters/slack.d.ts +90 -0
  457. package/dist/platform/adapters/slack.js +630 -0
  458. package/dist/platform/index.d.ts +12 -0
  459. package/dist/platform/index.js +10 -0
  460. package/dist/platform/interactive-builder.d.ts +27 -0
  461. package/dist/platform/interactive-builder.js +120 -0
  462. package/dist/platform/testing.d.ts +100 -0
  463. package/dist/platform/testing.js +190 -0
  464. package/dist/platform/tool-trace.d.ts +33 -0
  465. package/dist/platform/tool-trace.js +165 -0
  466. package/dist/platform/types.d.ts +176 -0
  467. package/dist/platform/types.js +5 -0
  468. package/dist/platform/utils/rate-limiter.d.ts +92 -0
  469. package/dist/platform/utils/rate-limiter.js +213 -0
  470. package/dist/platform/virtual-message.d.ts +68 -0
  471. package/dist/platform/virtual-message.js +464 -0
  472. package/dist/store/atomic-write.d.ts +6 -0
  473. package/dist/store/atomic-write.js +18 -0
  474. package/dist/store/channel-repo.d.ts +21 -0
  475. package/dist/store/channel-repo.js +55 -0
  476. package/dist/store/conversation-ledger-repo.d.ts +86 -0
  477. package/dist/store/conversation-ledger-repo.js +220 -0
  478. package/dist/store/cost-repo.d.ts +57 -0
  479. package/dist/store/cost-repo.js +135 -0
  480. package/dist/store/execution-repo.d.ts +172 -0
  481. package/dist/store/execution-repo.js +343 -0
  482. package/dist/store/in-memory-repository.d.ts +14 -0
  483. package/dist/store/in-memory-repository.js +31 -0
  484. package/dist/store/json-repository.d.ts +51 -0
  485. package/dist/store/json-repository.js +118 -0
  486. package/dist/store/outbound-queue.d.ts +65 -0
  487. package/dist/store/outbound-queue.js +269 -0
  488. package/dist/store/profile-repo.d.ts +36 -0
  489. package/dist/store/profile-repo.js +144 -0
  490. package/dist/store/project-dir-repo.d.ts +22 -0
  491. package/dist/store/project-dir-repo.js +60 -0
  492. package/dist/store/schedule-repo.d.ts +92 -0
  493. package/dist/store/schedule-repo.js +88 -0
  494. package/dist/store/session-registry-repo.d.ts +38 -0
  495. package/dist/store/session-registry-repo.js +96 -0
  496. package/dist/store/session-repo.d.ts +14 -0
  497. package/dist/store/session-repo.js +56 -0
  498. package/dist/store/task-repo.d.ts +41 -0
  499. package/dist/store/task-repo.js +137 -0
  500. package/dist/store/thread-repo.d.ts +50 -0
  501. package/dist/store/thread-repo.js +190 -0
  502. package/package.json +58 -0
  503. package/scripts/postinstall-restart-trigger.mjs +39 -0
@@ -0,0 +1,14 @@
1
+ // input: sessions.json file, channel ID, backend name
2
+ // output: { getSessionAsync, setSessionAsync, deleteSessionAsync } — channel session CRUD
3
+ // pos: thin re-export layer, all session CRUD goes through store/session-repo.ts (AsyncMutex serialization)
4
+ // >>> If I am updated, update my header comment and CORTEX.md <<<
5
+ import { sessionRepo } from '../../store/session-repo.js';
6
+ export async function getSessionAsync(channel, backend) {
7
+ return sessionRepo.getSessionAsync(channel, backend);
8
+ }
9
+ export async function setSessionAsync(channel, sessionId, backend) {
10
+ return sessionRepo.setSessionAsync(channel, sessionId, backend);
11
+ }
12
+ export async function deleteSessionAsync(channel, backend) {
13
+ return sessionRepo.deleteSessionAsync(channel, backend);
14
+ }
@@ -0,0 +1,9 @@
1
+ declare function runTaskArchiver(): Promise<{
2
+ archived: Array<{
3
+ project: string;
4
+ ids: string[];
5
+ }>;
6
+ skipped: string[];
7
+ errors: string[];
8
+ }>;
9
+ export { runTaskArchiver };
@@ -0,0 +1,123 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { execSync } from 'child_process';
4
+ import { PROJECTS_DIR, DATA_DIR } from '../../core/utils.js';
5
+ import { createLogger } from '../../core/log.js';
6
+ import { parseTasksFile, serializeTasksFile } from '../../core/task-parser.js';
7
+ import { taskStore } from './store.js';
8
+ const log = createLogger('task-archiver');
9
+ const ARCHIVE_AGE_DAYS = 3;
10
+ function isOlderThan(dateStr, days) {
11
+ const completed = new Date(dateStr + 'T00:00:00Z');
12
+ const cutoff = new Date();
13
+ cutoff.setUTCDate(cutoff.getUTCDate() - days);
14
+ cutoff.setUTCHours(0, 0, 0, 0);
15
+ return completed < cutoff;
16
+ }
17
+ function formatTaskForArchive(task) {
18
+ const lines = [];
19
+ lines.push(`- [x] ${task.text} [id: ${task.id}]`);
20
+ if (task.why)
21
+ lines.push(` Why: ${task.why}`);
22
+ if (task.done_when)
23
+ lines.push(` Done when: ${task.done_when}`);
24
+ lines.push(` Priority: ${task.priority}`);
25
+ if (task.completed_at)
26
+ lines.push(` Completed: ${task.completed_at}${task.completed_note ? ` (${task.completed_note})` : ''}`);
27
+ return lines.join('\n');
28
+ }
29
+ function processProject(projectName) {
30
+ const tasksPath = path.join(PROJECTS_DIR, projectName, 'TASKS.yaml');
31
+ if (!fs.existsSync(tasksPath))
32
+ return null;
33
+ const content = fs.readFileSync(tasksPath, 'utf8');
34
+ const tasks = parseTasksFile(content, projectName);
35
+ const toArchive = [];
36
+ const toKeep = [];
37
+ for (const task of tasks) {
38
+ if (task.status === 'done' && task.completed_at && isOlderThan(task.completed_at, ARCHIVE_AGE_DAYS)) {
39
+ toArchive.push(task);
40
+ }
41
+ else {
42
+ toKeep.push(task);
43
+ }
44
+ }
45
+ if (toArchive.length === 0)
46
+ return null;
47
+ const archivedIds = toArchive.map((t) => t.id).filter(Boolean);
48
+ log.info(`${projectName}: archiving ${toArchive.length} tasks (${archivedIds.join(', ')})`);
49
+ const archivePath = path.join(PROJECTS_DIR, projectName, 'tasks-archive.md');
50
+ let archiveContent;
51
+ if (fs.existsSync(archivePath)) {
52
+ archiveContent = fs.readFileSync(archivePath, 'utf8').trimEnd() + '\n';
53
+ }
54
+ else {
55
+ archiveContent = `# ${projectName} — Tasks Archive\n\n> Archived completed tasks. Current tasks in TASKS.yaml.\n`;
56
+ }
57
+ for (const task of toArchive) {
58
+ archiveContent += '\n' + formatTaskForArchive(task) + '\n';
59
+ }
60
+ fs.writeFileSync(tasksPath, serializeTasksFile(toKeep));
61
+ fs.writeFileSync(archivePath, archiveContent);
62
+ return { project: projectName, ids: archivedIds };
63
+ }
64
+ function gitCommit(results) {
65
+ const files = [];
66
+ for (const r of results) {
67
+ const projectDir = path.join(PROJECTS_DIR, r.project);
68
+ files.push(path.join(projectDir, 'TASKS.yaml'));
69
+ files.push(path.join(projectDir, 'tasks-archive.md'));
70
+ }
71
+ try {
72
+ const gitArgs = files.map((f) => `"${f}"`).join(' ');
73
+ execSync(`git add ${gitArgs}`, { cwd: DATA_DIR, stdio: 'pipe' });
74
+ const status = execSync('git diff --cached --stat', { cwd: DATA_DIR, encoding: 'utf8' });
75
+ if (!status.trim()) {
76
+ log.info('No changes to commit');
77
+ return;
78
+ }
79
+ const summary = results.map((r) => `${r.project}: ${r.ids.length} tasks`).join('; ');
80
+ const msg = `auto-archive: completed tasks (${summary})`;
81
+ execSync(`git commit -m "${msg}"`, { cwd: DATA_DIR, stdio: 'pipe' });
82
+ log.info(`Committed: ${msg}`);
83
+ }
84
+ catch (e) {
85
+ log.error('Git commit failed:', e.message);
86
+ }
87
+ }
88
+ async function runTaskArchiver() {
89
+ return taskStore.runExclusive(() => {
90
+ log.info('Starting scan...');
91
+ const results = {
92
+ archived: [], skipped: [], errors: [],
93
+ };
94
+ let projectNames;
95
+ try {
96
+ projectNames = fs.readdirSync(PROJECTS_DIR, { withFileTypes: true })
97
+ .filter((d) => d.isDirectory()).map((d) => d.name);
98
+ }
99
+ catch (e) {
100
+ results.errors.push(`Failed to read projects dir: ${e.message}`);
101
+ return results;
102
+ }
103
+ for (const name of projectNames) {
104
+ try {
105
+ const result = processProject(name);
106
+ if (result)
107
+ results.archived.push(result);
108
+ else
109
+ results.skipped.push(name);
110
+ }
111
+ catch (e) {
112
+ results.errors.push(`${name}: ${e.message}`);
113
+ log.error(`Error processing ${name}:`, e.message);
114
+ }
115
+ }
116
+ if (results.archived.length > 0)
117
+ gitCommit(results.archived);
118
+ const archivedCount = results.archived.reduce((sum, r) => sum + r.ids.length, 0);
119
+ log.info(`Done. Archived ${archivedCount} tasks from ${results.archived.length} project(s)`);
120
+ return results;
121
+ });
122
+ }
123
+ export { runTaskArchiver };
@@ -0,0 +1,37 @@
1
+ export interface MachineEntry {
2
+ cortexPath: string;
3
+ gpuCount: number;
4
+ ssh?: string;
5
+ win?: boolean;
6
+ }
7
+ export type MachineRegistry = Record<string, MachineEntry>;
8
+ export declare function setAdminNotifier(fn: (text: string) => void): void;
9
+ /**
10
+ * Load machines.json from disk into memory.
11
+ * On first call (startup), throws if file is missing or malformed.
12
+ * On subsequent calls (hot-reload), logs errors and keeps old config.
13
+ */
14
+ declare function loadMachinesFromFile(failOnError?: boolean): void;
15
+ /**
16
+ * Return the current in-memory machine registry.
17
+ */
18
+ declare function getMachineRegistry(): MachineRegistry;
19
+ /**
20
+ * Return the first machine key in the registry as the local/default machine.
21
+ * Falls back to 'local' if no machines are registered.
22
+ */
23
+ declare function getLocalMachine(): string;
24
+ /**
25
+ * Start watching machines.json for changes. Reloads on file edit.
26
+ * Handles atomic file replacement (rename event) by re-creating the watcher.
27
+ */
28
+ declare function startMachineRegistryWatcher(): void;
29
+ /**
30
+ * Stop watching machines.json (for tests / graceful shutdown).
31
+ */
32
+ declare function stopMachineRegistryWatcher(): void;
33
+ declare function generateTaskId(): string;
34
+ declare function buildDispatchSessionName(taskId: any): string;
35
+ /** Test-only: directly set the in-memory machine registry. */
36
+ declare function _testSetRegistry(registry: MachineRegistry): void;
37
+ export { getMachineRegistry, getLocalMachine, loadMachinesFromFile, startMachineRegistryWatcher, stopMachineRegistryWatcher, generateTaskId, buildDispatchSessionName, _testSetRegistry, };
@@ -0,0 +1,143 @@
1
+ // input: machines.json config (hot-reloadable)
2
+ // output: getMachineRegistry + task ID generators
3
+ // pos: device registry and task ID generation utilities
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import * as crypto from 'crypto';
6
+ import { readFileSync, watch, existsSync } from 'fs';
7
+ import * as path from 'path';
8
+ import { CONFIG_DIR } from '../../core/utils.js';
9
+ import { createLogger } from '../../core/log.js';
10
+ const log = createLogger('machine-registry');
11
+ const MACHINES_FILE = path.join(CONFIG_DIR, 'machines.json');
12
+ let _registry = {};
13
+ let _loaded = false;
14
+ let _watcher = null;
15
+ let _reloadTimer = null;
16
+ // --- Admin notification (hot-reload → Slack) ---
17
+ let _adminNotifier = null;
18
+ export function setAdminNotifier(fn) { _adminNotifier = fn; }
19
+ /**
20
+ * Load machines.json from disk into memory.
21
+ * On first call (startup), throws if file is missing or malformed.
22
+ * On subsequent calls (hot-reload), logs errors and keeps old config.
23
+ */
24
+ function loadMachinesFromFile(failOnError = true) {
25
+ try {
26
+ const raw = readFileSync(MACHINES_FILE, 'utf-8');
27
+ const parsed = JSON.parse(raw);
28
+ // Basic validation: ensure every entry has cortexPath and gpuCount
29
+ for (const [name, entry] of Object.entries(parsed)) {
30
+ if (typeof entry.cortexPath !== 'string' || typeof entry.gpuCount !== 'number') {
31
+ throw new Error(`Invalid machine entry "${name}": requires cortexPath (string) and gpuCount (number)`);
32
+ }
33
+ }
34
+ const oldKeys = Object.keys(_registry).sort().join(',');
35
+ const newKeys = Object.keys(parsed).sort().join(',');
36
+ const isReload = _loaded;
37
+ _registry = parsed;
38
+ _loaded = true;
39
+ if (isReload) {
40
+ if (oldKeys !== newKeys) {
41
+ log.info(`Hot-reload: machines changed [${oldKeys}] → [${newKeys}]`);
42
+ _adminNotifier?.(`:arrows_counterclockwise: \`machines.json\` hot-reloaded: [${oldKeys}] → [${newKeys}]`);
43
+ }
44
+ else {
45
+ log.info(`Hot-reload: ${Object.keys(parsed).length} machines reloaded`);
46
+ _adminNotifier?.(`:arrows_counterclockwise: \`machines.json\` hot-reloaded (${Object.keys(parsed).length} machines)`);
47
+ }
48
+ }
49
+ else {
50
+ log.info(`Loaded ${Object.keys(parsed).length} machines: ${Object.keys(parsed).join(', ')}`);
51
+ }
52
+ }
53
+ catch (e) {
54
+ const msg = `[machine-registry] Failed to load ${MACHINES_FILE}: ${e.message}`;
55
+ if (failOnError) {
56
+ throw new Error(msg);
57
+ }
58
+ log.error(msg + ' — keeping previous config');
59
+ _adminNotifier?.(`:warning: \`machines.json\` hot-reload FAILED — keeping previous config`);
60
+ }
61
+ }
62
+ /**
63
+ * Return the current in-memory machine registry.
64
+ */
65
+ function getMachineRegistry() {
66
+ return _registry;
67
+ }
68
+ /**
69
+ * Return the first machine key in the registry as the local/default machine.
70
+ * Falls back to 'local' if no machines are registered.
71
+ */
72
+ function getLocalMachine() {
73
+ return Object.keys(_registry)[0] || 'local';
74
+ }
75
+ /**
76
+ * Start watching machines.json for changes. Reloads on file edit.
77
+ * Handles atomic file replacement (rename event) by re-creating the watcher.
78
+ */
79
+ function startMachineRegistryWatcher() {
80
+ if (!existsSync(MACHINES_FILE))
81
+ return;
82
+ const setup = () => {
83
+ try {
84
+ if (_watcher)
85
+ _watcher.close();
86
+ _watcher = watch(MACHINES_FILE, (eventType) => {
87
+ if (eventType === 'rename') {
88
+ // File was atomically replaced — inode changed, watcher is dead.
89
+ // Re-create after a short delay to let the new file settle.
90
+ setTimeout(() => setup(), 100);
91
+ return; // setup() will handle the reload after the new watcher fires
92
+ }
93
+ if (_reloadTimer)
94
+ clearTimeout(_reloadTimer);
95
+ _reloadTimer = setTimeout(() => {
96
+ _reloadTimer = null;
97
+ loadMachinesFromFile(false); // hot-reload: don't crash on error
98
+ }, 300);
99
+ });
100
+ }
101
+ catch (e) {
102
+ log.error(`Failed to watch machines.json: ${e.message}`);
103
+ }
104
+ };
105
+ setup();
106
+ }
107
+ /**
108
+ * Stop watching machines.json (for tests / graceful shutdown).
109
+ */
110
+ function stopMachineRegistryWatcher() {
111
+ if (_watcher) {
112
+ _watcher.close();
113
+ _watcher = null;
114
+ }
115
+ if (_reloadTimer) {
116
+ clearTimeout(_reloadTimer);
117
+ _reloadTimer = null;
118
+ }
119
+ }
120
+ // --- Auto-load at import time (equivalent to the old hardcoded constant) ---
121
+ // This ensures getMachineRegistry() works immediately for all consumers.
122
+ // app.ts also calls loadMachinesFromFile() explicitly + starts the watcher.
123
+ if (existsSync(MACHINES_FILE)) {
124
+ try {
125
+ loadMachinesFromFile();
126
+ }
127
+ catch (e) {
128
+ log.error(`Auto-load failed: ${e.message}`);
129
+ }
130
+ }
131
+ // --- Task ID utilities ---
132
+ function generateTaskId() {
133
+ return crypto.randomBytes(2).toString('hex');
134
+ }
135
+ function buildDispatchSessionName(taskId) {
136
+ return `task-dispatch-${taskId}`;
137
+ }
138
+ /** Test-only: directly set the in-memory machine registry. */
139
+ function _testSetRegistry(registry) {
140
+ _registry = { ...registry };
141
+ _loaded = true;
142
+ }
143
+ export { getMachineRegistry, getLocalMachine, loadMachinesFromFile, startMachineRegistryWatcher, stopMachineRegistryWatcher, generateTaskId, buildDispatchSessionName, _testSetRegistry, };
@@ -0,0 +1,48 @@
1
+ import type { ExecutionRecord } from '../executions/registry.js';
2
+ interface OccupancyGpuInfo {
3
+ index: number;
4
+ occupied: boolean;
5
+ processes: {
6
+ pid: string;
7
+ name: string;
8
+ memoryMB: number;
9
+ }[];
10
+ }
11
+ interface GpuOccupancyResult {
12
+ gpus: OccupancyGpuInfo[];
13
+ freeIndices: number[];
14
+ allOccupied: boolean;
15
+ error?: string;
16
+ }
17
+ interface DispatchMatch {
18
+ source: string;
19
+ taskId: string | null;
20
+ machine: string | null;
21
+ }
22
+ interface SelectAndClaimResult {
23
+ task: any;
24
+ prompt: string;
25
+ template: string | null;
26
+ }
27
+ interface DispatchOutcome {
28
+ success: boolean;
29
+ skipped: boolean;
30
+ }
31
+ interface FilterDeps {
32
+ findActiveDispatchMatch?: (task: any, scheduleTaskId: string) => DispatchMatch | null;
33
+ checkRealGpuOccupancy?: (machine: string) => Promise<GpuOccupancyResult>;
34
+ }
35
+ declare function isValidDispatchPrompt(value: unknown): boolean;
36
+ declare function filterLockedProjects(tasks: any[]): any[];
37
+ declare function checkRealGpuOccupancy(machine: string): Promise<GpuOccupancyResult>;
38
+ declare function selectTask(tasks: any[] | null): any | null;
39
+ declare function findActiveDispatchMatch(task: any, scheduleTaskId: string): DispatchMatch | null;
40
+ declare function filterDispatchableTasks(tasks: any[] | null, scheduleTaskId: string, gpuBusyCounts?: Map<string, number>, deps?: FilterDeps): Promise<any[]>;
41
+ declare function computeNextInterval(outcome: DispatchOutcome): number;
42
+ declare function hasRunningExecutionForSchedule(records: Pick<ExecutionRecord, 'status' | 'kind' | 'scheduleTaskId'>[], scheduleTaskId: string): boolean;
43
+ declare function updateScheduleInterval(scheduler: any, scheduleTaskId: string, newIntervalMs: number): Promise<void>;
44
+ declare function selectAndClaimTask({ scheduleTaskId, dryRun }: {
45
+ scheduleTaskId: string;
46
+ dryRun?: boolean;
47
+ }): Promise<SelectAndClaimResult | null>;
48
+ export { selectAndClaimTask, hasRunningExecutionForSchedule, computeNextInterval, updateScheduleInterval, isValidDispatchPrompt, selectTask, filterLockedProjects, filterDispatchableTasks, findActiveDispatchMatch, checkRealGpuOccupancy, };
@@ -0,0 +1,285 @@
1
+ // input: task-store, client-manager, execution-registry
2
+ // output: selectAndClaimTask + schedule/interval helpers
3
+ // pos: programmatic dispatch for task selection and claiming
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { createLogger } from '../../core/log.js';
6
+ import { isProjectLocked } from './system/task-lock.js';
7
+ const log = createLogger('task-dispatch');
8
+ const gpuLog = createLogger('gpu-preflight');
9
+ import { getMachineRegistry, getLocalMachine } from './dispatch-utils.js';
10
+ import { isDeviceOnline } from '../remote/client-manager.js'; // still needed for online check before queryGpuSnapshot
11
+ import { queryGpuSnapshot } from '../monitor/gpu-monitor.js';
12
+ import * as executionRegistry from '../executions/registry.js';
13
+ import { taskStore } from './store.js';
14
+ import { taskMutator } from './mutator.js';
15
+ import { listTemplateNames } from '../threads/template-loader.js';
16
+ // --- Null/empty prompt guard (ISS-CS-005 durable fix) ---
17
+ function isValidDispatchPrompt(value) {
18
+ if (!value || typeof value === 'object')
19
+ return false;
20
+ const s = typeof value === 'string' ? value : String(value);
21
+ if (!s.trim())
22
+ return false;
23
+ if (s === 'null' || s === 'undefined')
24
+ return false;
25
+ return true;
26
+ }
27
+ // --- Locked-project filter: skip tasks from projects with active locks ---
28
+ function filterLockedProjects(tasks) {
29
+ if (!tasks || tasks.length === 0)
30
+ return tasks;
31
+ const projectCache = new Map();
32
+ const lockedProjects = new Map();
33
+ const filtered = tasks.filter(task => {
34
+ if (!projectCache.has(task.project)) {
35
+ const result = isProjectLocked(task.project);
36
+ projectCache.set(task.project, result.locked);
37
+ if (result.locked && result.owner) {
38
+ lockedProjects.set(task.project, result.owner);
39
+ }
40
+ }
41
+ return !projectCache.get(task.project);
42
+ });
43
+ if (lockedProjects.size > 0) {
44
+ const skippedCount = tasks.length - filtered.length;
45
+ const details = Array.from(lockedProjects.entries())
46
+ .map(([p, o]) => `${p}:${o}`)
47
+ .join(', ');
48
+ log.info(`Skipping ${skippedCount} task(s) from locked projects: [${details}]`);
49
+ }
50
+ return filtered;
51
+ }
52
+ // --- GPU conflict detection via gpu-monitor ---
53
+ const IDLE_PROCESS_PATTERNS = [/Xorg/i, /gnome-shell/i, /compiz/i];
54
+ async function checkRealGpuOccupancy(machine) {
55
+ const reg = getMachineRegistry()[machine];
56
+ if (!reg)
57
+ return { gpus: [], freeIndices: [], allOccupied: false, error: `Unknown machine: ${machine}` };
58
+ if (reg.gpuCount === 0)
59
+ return { gpus: [], freeIndices: [], allOccupied: false };
60
+ // Check device online via client-manager
61
+ if (!isDeviceOnline(machine)) {
62
+ gpuLog.info(`Device ${machine} offline, skipping GPU check`);
63
+ return { gpus: [], freeIndices: [], allOccupied: true, error: `Device ${machine} offline` };
64
+ }
65
+ try {
66
+ const snapshot = await queryGpuSnapshot(machine);
67
+ if (snapshot.gpus.length === 0) {
68
+ gpuLog.info(`nvidia-smi unavailable on ${machine}, allowing dispatch`);
69
+ const gpuCount = reg.gpuCount || 0;
70
+ const freeIndices = Array.from({ length: gpuCount }, (_, i) => i);
71
+ return { gpus: [], freeIndices, allOccupied: false };
72
+ }
73
+ // Derive occupancy from snapshot, filtering out idle system processes
74
+ const gpus = snapshot.gpus.map(g => {
75
+ const activeProcs = g.processes
76
+ .filter(p => !IDLE_PROCESS_PATTERNS.some(pat => pat.test(p.name)))
77
+ .map(p => ({ pid: p.pid, name: p.name, memoryMB: p.memoryMB }));
78
+ return { index: g.index, occupied: activeProcs.length > 0, processes: activeProcs };
79
+ });
80
+ const freeIndices = gpus.filter(g => !g.occupied).map(g => g.index);
81
+ const allOccupied = gpus.length > 0 && freeIndices.length === 0;
82
+ gpuLog.info(`${machine}: ${gpus.length} GPU(s), ${freeIndices.length} free [${freeIndices.join(',')}]`);
83
+ return { gpus, freeIndices, allOccupied };
84
+ }
85
+ catch (err) {
86
+ gpuLog.error(`Failed to check GPU on ${machine}: ${err.message}`);
87
+ const gpuCount = reg.gpuCount || 0;
88
+ const freeIndices = Array.from({ length: gpuCount }, (_, i) => i);
89
+ return { gpus: [], freeIndices, allOccupied: false, error: err.message };
90
+ }
91
+ }
92
+ // --- Task selection ---
93
+ function selectTask(tasks) {
94
+ if (!tasks || tasks.length === 0)
95
+ return null;
96
+ return tasks[0];
97
+ }
98
+ // --- Duplicate detection (execution registry only, no pending tracker) ---
99
+ function findActiveDispatchMatch(task, scheduleTaskId) {
100
+ const executionMatch = executionRegistry.findRunningDispatchMatch({
101
+ scheduleTaskId,
102
+ taskHash: task.id,
103
+ project: task.project,
104
+ taskText: task.text,
105
+ });
106
+ if (executionMatch) {
107
+ return {
108
+ source: 'execution',
109
+ taskId: executionMatch.dispatch?.taskId || null,
110
+ machine: executionMatch.dispatch?.machine || null,
111
+ };
112
+ }
113
+ return null;
114
+ }
115
+ // --- Unknown-template warning dedup (per-process, per-(task_hash, template) pair) ---
116
+ const _unknownTemplateWarnedKeys = new Set();
117
+ function warnOnceUnknownTemplate(task) {
118
+ const key = `${task.id || task.text}::${task.template}`;
119
+ if (_unknownTemplateWarnedKeys.has(key))
120
+ return;
121
+ _unknownTemplateWarnedKeys.add(key);
122
+ log.warn(`Skipping task with unknown template "${task.template}": [${task.project}] ${String(task.text).substring(0, 80)}`);
123
+ }
124
+ // --- Filter dispatchable tasks ---
125
+ async function filterDispatchableTasks(tasks, scheduleTaskId, gpuBusyCounts = new Map(), deps = {}) {
126
+ if (!tasks || tasks.length === 0)
127
+ return [];
128
+ const findDuplicate = deps.findActiveDispatchMatch || findActiveDispatchMatch;
129
+ const checkGpu = deps.checkRealGpuOccupancy || checkRealGpuOccupancy;
130
+ const gpuStatusCache = new Map();
131
+ // Fail-open if templates haven't been loaded yet (size === 0): let downstream
132
+ // createThread surface the error rather than silently dropping every task.
133
+ const validTemplates = new Set(listTemplateNames());
134
+ const eligible = [];
135
+ for (const task of tasks) {
136
+ if (!task.template) {
137
+ continue;
138
+ }
139
+ if (validTemplates.size > 0 && !validTemplates.has(task.template)) {
140
+ warnOnceUnknownTemplate(task);
141
+ continue;
142
+ }
143
+ // Check remote GPU device is online (local machine is always reachable)
144
+ if (task.gpu && task.gpu !== getLocalMachine() && !isDeviceOnline(task.gpu)) {
145
+ continue;
146
+ }
147
+ if (task.gpu) {
148
+ const targetMachine = task.gpu.toLowerCase();
149
+ const reg = getMachineRegistry()[targetMachine];
150
+ const totalSlots = reg?.gpuCount ?? 0;
151
+ const usedSlots = gpuBusyCounts.get(targetMachine) || 0;
152
+ const neededSlots = task.gpu_count || 1;
153
+ if (usedSlots + neededSlots > totalSlots)
154
+ continue;
155
+ }
156
+ const duplicateMatch = findDuplicate(task, scheduleTaskId);
157
+ if (duplicateMatch)
158
+ continue;
159
+ if (task.gpu) {
160
+ const targetMachine = task.gpu.toLowerCase();
161
+ let gpuStatus = gpuStatusCache.get(targetMachine);
162
+ if (!gpuStatus) {
163
+ gpuStatus = await checkGpu(targetMachine);
164
+ gpuStatusCache.set(targetMachine, gpuStatus);
165
+ }
166
+ const neededSlots = task.gpu_count || 1;
167
+ if (gpuStatus.allOccupied || gpuStatus.freeIndices.length < neededSlots)
168
+ continue;
169
+ const assignedIndices = gpuStatus.freeIndices.slice(0, neededSlots);
170
+ task._assignedGpuIndex = neededSlots === 1 ? assignedIndices[0] : assignedIndices.join(',');
171
+ const remainingFree = gpuStatus.freeIndices.slice(neededSlots);
172
+ gpuStatusCache.set(targetMachine, { ...gpuStatus, freeIndices: remainingFree, allOccupied: remainingFree.length === 0 });
173
+ }
174
+ eligible.push(task);
175
+ }
176
+ return eligible;
177
+ }
178
+ // --- Interval computation ---
179
+ function computeNextInterval(outcome) {
180
+ if (!outcome.success && !outcome.skipped)
181
+ return 2 * 60 * 1000;
182
+ return 30 * 1000;
183
+ }
184
+ function hasRunningExecutionForSchedule(records, scheduleTaskId) {
185
+ return records.some((record) => record.status === 'running' &&
186
+ record.kind === 'scheduled' &&
187
+ record.scheduleTaskId === scheduleTaskId);
188
+ }
189
+ async function updateScheduleInterval(scheduler, scheduleTaskId, newIntervalMs) {
190
+ if (!scheduleTaskId)
191
+ return;
192
+ const task = await scheduler.get(scheduleTaskId);
193
+ if (!task || task.type !== 'interval')
194
+ return;
195
+ if (task.intervalMs === newIntervalMs)
196
+ return;
197
+ await scheduler.setInterval(scheduleTaskId, newIntervalMs);
198
+ }
199
+ // --- Dispatch prompt assembly ---
200
+ function buildDispatchPrompt(task) {
201
+ const sections = [];
202
+ const taskSpec = [
203
+ '## Task',
204
+ '',
205
+ `**Project:** ${task.project}`,
206
+ `**Task:** ${task.text}`,
207
+ ];
208
+ if (task.why)
209
+ taskSpec.push(`**Why:** ${task.why}`);
210
+ if (task.done_when)
211
+ taskSpec.push(`**Done when:** ${task.done_when}`);
212
+ taskSpec.push(`**Task ID:** ${task.id}`);
213
+ if (task.plan)
214
+ taskSpec.push(`**Plan (MUST read):** ${task.plan}`);
215
+ sections.push(taskSpec.join('\n'));
216
+ const completion = [
217
+ '## When Done',
218
+ '',
219
+ '**CRITICAL: Before marking any task complete, verify ALL done_when conditions are actually satisfied.**',
220
+ '',
221
+ `If launching experiments via cortex-run, ALWAYS pass task info so cortex-run can manage task status:`,
222
+ ` cortex-run --name NAME --task-project ${task.project} --task-id ${task.id} -- COMMAND`,
223
+ `cortex-run will auto-mark the task pending on start, then complete on success / block on failure.`,
224
+ '',
225
+ `If NOT using cortex-run, verify done_when conditions, then run:`,
226
+ ` cortex-task complete --project ${task.project} --task-id ${task.id} --note "your completion note"`,
227
+ '',
228
+ '- Update the project STATUS.md if the work changed project state',
229
+ '- Commit and push all files you modified in the Cortex repository. Remember to clean any temporary files you created.',
230
+ ' - If push is rejected, resolve the conflict, amend your commit, and push again.',
231
+ ];
232
+ sections.push(completion.join('\n'));
233
+ return sections.join('\n\n');
234
+ }
235
+ // --- Main entry point: select and claim a task for local execution ---
236
+ async function selectAndClaimTask({ scheduleTaskId, dryRun = false }) {
237
+ log.info('Starting task selection cycle');
238
+ // Get actionable tasks + GPU busy machines
239
+ let tasks = taskStore.getActionable();
240
+ tasks = filterLockedProjects(tasks);
241
+ const gpuBusyMachines = taskStore.getGpuBusyMachines();
242
+ log.info(`Found ${tasks.length} actionable task(s)`);
243
+ // Filter to dispatchable tasks
244
+ const dispatchableTasks = await filterDispatchableTasks(tasks, scheduleTaskId, gpuBusyMachines);
245
+ log.info(`${dispatchableTasks.length} task(s) dispatchable after preflight`);
246
+ // Select task
247
+ const selectedTask = selectTask(dispatchableTasks);
248
+ if (!selectedTask) {
249
+ log.info('No dispatchable tasks available');
250
+ return null;
251
+ }
252
+ log.info(`Selected: [${selectedTask.project}] ${selectedTask.text}`);
253
+ // Guard: reject null/empty/whitespace task text before prompt assembly (ISS-CS-005 mitigation).
254
+ // Logged at warn level for visibility (repeated triggers = someone is putting bad data into TASKS.yaml).
255
+ // The defensive unclaim below clears any stale [in-progress] tag from a prior cycle — the task
256
+ // hasn't been claimed by this dispatch pass yet, but may have been claimed-then-aborted earlier.
257
+ if (!isValidDispatchPrompt(selectedTask.text)) {
258
+ log.warn(`Guard dropped task with null/empty text: [${selectedTask.project}] ${selectedTask.id} (schedule=${scheduleTaskId})`);
259
+ await taskMutator.unclaim(selectedTask.id);
260
+ return null;
261
+ }
262
+ // Dry run: return without claiming
263
+ if (dryRun) {
264
+ return {
265
+ task: selectedTask,
266
+ prompt: buildDispatchPrompt(selectedTask),
267
+ template: selectedTask.template || null,
268
+ };
269
+ }
270
+ // Claim task
271
+ const claimResult = await taskMutator.claim(selectedTask.id, 'task-dispatcher');
272
+ if (!claimResult.success) {
273
+ log.info(`Claim failed: ${claimResult.message}`);
274
+ return null;
275
+ }
276
+ const prompt = buildDispatchPrompt(selectedTask);
277
+ return {
278
+ task: selectedTask,
279
+ prompt,
280
+ template: selectedTask.template || null,
281
+ };
282
+ }
283
+ export { selectAndClaimTask, hasRunningExecutionForSchedule, computeNextInterval, updateScheduleInterval, isValidDispatchPrompt,
284
+ // For testing
285
+ selectTask, filterLockedProjects, filterDispatchableTasks, findActiveDispatchMatch, checkRealGpuOccupancy, };
@@ -0,0 +1,12 @@
1
+ import { type Task } from '../../core/task-parser.js';
2
+ export declare function findCycles(tasks: Task[]): string[][];
3
+ export interface LintOptions {
4
+ validTemplateNames?: Set<string> | null;
5
+ }
6
+ export declare function lintTasks(tasks: Task[], options?: LintOptions): {
7
+ ok: boolean;
8
+ errors: any[];
9
+ warnings: any[];
10
+ info: any[];
11
+ summary: any;
12
+ };