@stackmemoryai/stackmemory 0.5.57 → 0.5.59

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 (611) hide show
  1. package/bin/codex-smd +6 -0
  2. package/dist/cli/codex-sm-danger.js +21 -0
  3. package/dist/cli/codex-sm-danger.js.map +7 -0
  4. package/dist/cli/commands/handoff.js +33 -3
  5. package/dist/cli/commands/handoff.js.map +2 -2
  6. package/dist/cli/commands/search.js +20 -3
  7. package/dist/cli/commands/search.js.map +2 -2
  8. package/dist/core/database/sqlite-adapter.js +13 -3
  9. package/dist/core/database/sqlite-adapter.js.map +2 -2
  10. package/dist/core/errors/error-utils.js +208 -0
  11. package/dist/core/errors/error-utils.js.map +7 -0
  12. package/dist/core/errors/index.js +13 -4
  13. package/dist/core/errors/index.js.map +2 -2
  14. package/dist/core/merge/unified-merge-resolver.js +303 -0
  15. package/dist/core/merge/unified-merge-resolver.js.map +7 -0
  16. package/dist/core/monitoring/logger.js +61 -9
  17. package/dist/core/monitoring/logger.js.map +2 -2
  18. package/dist/core/security/index.js +35 -0
  19. package/dist/core/security/index.js.map +7 -0
  20. package/dist/core/security/input-sanitizer.js +321 -0
  21. package/dist/core/security/input-sanitizer.js.map +7 -0
  22. package/dist/core/session/enhanced-handoff.js +136 -2
  23. package/dist/core/session/enhanced-handoff.js.map +3 -3
  24. package/dist/integrations/linear/client.js +5 -1
  25. package/dist/integrations/linear/client.js.map +2 -2
  26. package/dist/integrations/mcp/remote-server.js +27 -36
  27. package/dist/integrations/mcp/remote-server.js.map +2 -2
  28. package/dist/integrations/mcp/server.js +44 -29
  29. package/dist/integrations/mcp/server.js.map +3 -3
  30. package/dist/scripts/benchmark-performance.js +48 -0
  31. package/dist/scripts/benchmark-performance.js.map +7 -0
  32. package/dist/scripts/check-redis.js +42 -0
  33. package/dist/scripts/check-redis.js.map +7 -0
  34. package/dist/scripts/initialize.js +116 -0
  35. package/dist/scripts/initialize.js.map +7 -0
  36. package/dist/scripts/list-linear-tasks.js +124 -0
  37. package/dist/scripts/list-linear-tasks.js.map +7 -0
  38. package/dist/scripts/measure-handoff-impact.js +340 -0
  39. package/dist/scripts/measure-handoff-impact.js.map +7 -0
  40. package/dist/scripts/query-chromadb.js +160 -0
  41. package/dist/scripts/query-chromadb.js.map +7 -0
  42. package/dist/scripts/show-linear-summary.js +119 -0
  43. package/dist/scripts/show-linear-summary.js.map +7 -0
  44. package/dist/scripts/simple-swarm-demo.js +90 -0
  45. package/dist/scripts/simple-swarm-demo.js.map +7 -0
  46. package/dist/scripts/status.js +155 -0
  47. package/dist/scripts/status.js.map +7 -0
  48. package/dist/scripts/test-chromadb-sync.js +192 -0
  49. package/dist/scripts/test-chromadb-sync.js.map +7 -0
  50. package/dist/scripts/test-ralph-iteration-fix.js +86 -0
  51. package/dist/scripts/test-ralph-iteration-fix.js.map +7 -0
  52. package/dist/scripts/test-ralph-iterations.js +121 -0
  53. package/dist/scripts/test-ralph-iterations.js.map +7 -0
  54. package/dist/scripts/test-redis-storage.js +389 -0
  55. package/dist/scripts/test-redis-storage.js.map +7 -0
  56. package/dist/scripts/test-simple-ralph-state-sync.js +115 -0
  57. package/dist/scripts/test-simple-ralph-state-sync.js.map +7 -0
  58. package/dist/scripts/test-swarm-fixes.js +125 -0
  59. package/dist/scripts/test-swarm-fixes.js.map +7 -0
  60. package/dist/scripts/test-swarm-tui.js +23 -0
  61. package/dist/scripts/test-swarm-tui.js.map +7 -0
  62. package/dist/scripts/test-tui-shortcuts.js +52 -0
  63. package/dist/scripts/test-tui-shortcuts.js.map +7 -0
  64. package/dist/scripts/validate-tui-shortcuts.js +60 -0
  65. package/dist/scripts/validate-tui-shortcuts.js.map +7 -0
  66. package/dist/src/agents/core/agent-task-manager.js +527 -0
  67. package/dist/src/agents/core/agent-task-manager.js.map +7 -0
  68. package/dist/src/agents/verifiers/base-verifier.js +133 -0
  69. package/dist/src/agents/verifiers/base-verifier.js.map +7 -0
  70. package/dist/src/agents/verifiers/formatter-verifier.js +130 -0
  71. package/dist/src/agents/verifiers/formatter-verifier.js.map +7 -0
  72. package/dist/src/agents/verifiers/llm-judge.js +252 -0
  73. package/dist/src/agents/verifiers/llm-judge.js.map +7 -0
  74. package/dist/src/cli/auto-detect.js +321 -0
  75. package/dist/src/cli/auto-detect.js.map +7 -0
  76. package/dist/src/cli/claude-sm-danger.js +21 -0
  77. package/dist/src/cli/claude-sm-danger.js.map +7 -0
  78. package/dist/src/cli/claude-sm.js +1156 -0
  79. package/dist/src/cli/claude-sm.js.map +7 -0
  80. package/dist/src/cli/codex-sm-danger.js +21 -0
  81. package/dist/src/cli/codex-sm-danger.js.map +7 -0
  82. package/dist/src/cli/codex-sm.js +349 -0
  83. package/dist/src/cli/codex-sm.js.map +7 -0
  84. package/dist/src/cli/commands/api.js +232 -0
  85. package/dist/src/cli/commands/api.js.map +7 -0
  86. package/dist/src/cli/commands/auto-background.js +180 -0
  87. package/dist/src/cli/commands/auto-background.js.map +7 -0
  88. package/dist/src/cli/commands/cleanup-processes.js +68 -0
  89. package/dist/src/cli/commands/cleanup-processes.js.map +7 -0
  90. package/dist/src/cli/commands/clear.js +202 -0
  91. package/dist/src/cli/commands/clear.js.map +7 -0
  92. package/dist/src/cli/commands/config.js +445 -0
  93. package/dist/src/cli/commands/config.js.map +7 -0
  94. package/dist/src/cli/commands/context-rehydrate.js +751 -0
  95. package/dist/src/cli/commands/context-rehydrate.js.map +7 -0
  96. package/dist/src/cli/commands/context.js +343 -0
  97. package/dist/src/cli/commands/context.js.map +7 -0
  98. package/dist/src/cli/commands/daemon.js +392 -0
  99. package/dist/src/cli/commands/daemon.js.map +7 -0
  100. package/dist/src/cli/commands/dashboard.js +210 -0
  101. package/dist/src/cli/commands/dashboard.js.map +7 -0
  102. package/dist/src/cli/commands/db.js +147 -0
  103. package/dist/src/cli/commands/db.js.map +7 -0
  104. package/dist/src/cli/commands/decision.js +266 -0
  105. package/dist/src/cli/commands/decision.js.map +7 -0
  106. package/dist/src/cli/commands/discovery.js +279 -0
  107. package/dist/src/cli/commands/discovery.js.map +7 -0
  108. package/dist/src/cli/commands/handoff.js +624 -0
  109. package/dist/src/cli/commands/handoff.js.map +7 -0
  110. package/dist/src/cli/commands/hooks.js +298 -0
  111. package/dist/src/cli/commands/hooks.js.map +7 -0
  112. package/dist/src/cli/commands/linear.js +529 -0
  113. package/dist/src/cli/commands/linear.js.map +7 -0
  114. package/dist/src/cli/commands/log.js +169 -0
  115. package/dist/src/cli/commands/log.js.map +7 -0
  116. package/dist/src/cli/commands/login.js +172 -0
  117. package/dist/src/cli/commands/login.js.map +7 -0
  118. package/dist/src/cli/commands/migrate.js +240 -0
  119. package/dist/src/cli/commands/migrate.js.map +7 -0
  120. package/dist/src/cli/commands/model.js +533 -0
  121. package/dist/src/cli/commands/model.js.map +7 -0
  122. package/dist/src/cli/commands/onboard.js +536 -0
  123. package/dist/src/cli/commands/onboard.js.map +7 -0
  124. package/dist/src/cli/commands/projects.js +199 -0
  125. package/dist/src/cli/commands/projects.js.map +7 -0
  126. package/dist/src/cli/commands/ralph.js +909 -0
  127. package/dist/src/cli/commands/ralph.js.map +7 -0
  128. package/dist/src/cli/commands/retrieval.js +248 -0
  129. package/dist/src/cli/commands/retrieval.js.map +7 -0
  130. package/dist/src/cli/commands/search.js +173 -0
  131. package/dist/src/cli/commands/search.js.map +7 -0
  132. package/dist/src/cli/commands/service.js +749 -0
  133. package/dist/src/cli/commands/service.js.map +7 -0
  134. package/dist/src/cli/commands/session.js +200 -0
  135. package/dist/src/cli/commands/session.js.map +7 -0
  136. package/dist/src/cli/commands/settings.js +306 -0
  137. package/dist/src/cli/commands/settings.js.map +7 -0
  138. package/dist/src/cli/commands/setup.js +701 -0
  139. package/dist/src/cli/commands/setup.js.map +7 -0
  140. package/dist/src/cli/commands/shell.js +249 -0
  141. package/dist/src/cli/commands/shell.js.map +7 -0
  142. package/dist/src/cli/commands/signup.js +50 -0
  143. package/dist/src/cli/commands/signup.js.map +7 -0
  144. package/dist/src/cli/commands/skills.js +470 -0
  145. package/dist/src/cli/commands/skills.js.map +7 -0
  146. package/dist/src/cli/commands/sms-notify.js +795 -0
  147. package/dist/src/cli/commands/sms-notify.js.map +7 -0
  148. package/dist/src/cli/commands/storage-tier.js +183 -0
  149. package/dist/src/cli/commands/storage-tier.js.map +7 -0
  150. package/dist/src/cli/commands/sweep.js +249 -0
  151. package/dist/src/cli/commands/sweep.js.map +7 -0
  152. package/dist/src/cli/commands/tasks.js +213 -0
  153. package/dist/src/cli/commands/tasks.js.map +7 -0
  154. package/dist/src/cli/commands/worktree.js +319 -0
  155. package/dist/src/cli/commands/worktree.js.map +7 -0
  156. package/dist/src/cli/index.js +594 -0
  157. package/dist/src/cli/index.js.map +7 -0
  158. package/dist/src/cli/opencode-sm.js +448 -0
  159. package/dist/src/cli/opencode-sm.js.map +7 -0
  160. package/dist/src/cli/utils/viewer.js +96 -0
  161. package/dist/src/cli/utils/viewer.js.map +7 -0
  162. package/dist/src/core/config/config-manager.js +398 -0
  163. package/dist/src/core/config/config-manager.js.map +7 -0
  164. package/dist/src/core/config/feature-flags.js +76 -0
  165. package/dist/src/core/config/feature-flags.js.map +7 -0
  166. package/dist/src/core/config/storage-config.js +115 -0
  167. package/dist/src/core/config/storage-config.js.map +7 -0
  168. package/dist/src/core/config/types.js +144 -0
  169. package/dist/src/core/config/types.js.map +7 -0
  170. package/dist/src/core/context/auto-context.js +80 -0
  171. package/dist/src/core/context/auto-context.js.map +7 -0
  172. package/dist/src/core/context/dual-stack-manager.js +870 -0
  173. package/dist/src/core/context/dual-stack-manager.js.map +7 -0
  174. package/dist/src/core/context/enhanced-rehydration.js +994 -0
  175. package/dist/src/core/context/enhanced-rehydration.js.map +7 -0
  176. package/dist/src/core/context/frame-database.js +479 -0
  177. package/dist/src/core/context/frame-database.js.map +7 -0
  178. package/dist/src/core/context/frame-digest.js +250 -0
  179. package/dist/src/core/context/frame-digest.js.map +7 -0
  180. package/dist/src/core/context/frame-handoff-manager.js +778 -0
  181. package/dist/src/core/context/frame-handoff-manager.js.map +7 -0
  182. package/dist/src/core/context/frame-lifecycle-hooks.js +119 -0
  183. package/dist/src/core/context/frame-lifecycle-hooks.js.map +7 -0
  184. package/dist/src/core/context/frame-recovery.js +302 -0
  185. package/dist/src/core/context/frame-recovery.js.map +7 -0
  186. package/dist/src/core/context/frame-stack.js +314 -0
  187. package/dist/src/core/context/frame-stack.js.map +7 -0
  188. package/dist/src/core/context/frame-types.js +5 -0
  189. package/dist/src/core/context/frame-types.js.map +7 -0
  190. package/dist/src/core/context/index.js +25 -0
  191. package/dist/src/core/context/index.js.map +7 -0
  192. package/dist/src/core/context/permission-manager.js +185 -0
  193. package/dist/src/core/context/permission-manager.js.map +7 -0
  194. package/dist/src/core/context/recursive-context-manager.js +592 -0
  195. package/dist/src/core/context/recursive-context-manager.js.map +7 -0
  196. package/dist/src/core/context/refactored-frame-manager.js +754 -0
  197. package/dist/src/core/context/refactored-frame-manager.js.map +7 -0
  198. package/dist/src/core/context/shared-context-layer.js +621 -0
  199. package/dist/src/core/context/shared-context-layer.js.map +7 -0
  200. package/dist/src/core/context/stack-merge-resolver.js +749 -0
  201. package/dist/src/core/context/stack-merge-resolver.js.map +7 -0
  202. package/dist/src/core/context/validation.js +130 -0
  203. package/dist/src/core/context/validation.js.map +7 -0
  204. package/dist/src/core/database/batch-operations.js +384 -0
  205. package/dist/src/core/database/batch-operations.js.map +7 -0
  206. package/dist/src/core/database/connection-pool.js +330 -0
  207. package/dist/src/core/database/connection-pool.js.map +7 -0
  208. package/dist/src/core/database/database-adapter.js +60 -0
  209. package/dist/src/core/database/database-adapter.js.map +7 -0
  210. package/dist/src/core/database/migration-manager.js +614 -0
  211. package/dist/src/core/database/migration-manager.js.map +7 -0
  212. package/dist/src/core/database/query-cache.js +298 -0
  213. package/dist/src/core/database/query-cache.js.map +7 -0
  214. package/dist/src/core/database/query-router.js +430 -0
  215. package/dist/src/core/database/query-router.js.map +7 -0
  216. package/dist/src/core/database/sqlite-adapter.js +738 -0
  217. package/dist/src/core/database/sqlite-adapter.js.map +7 -0
  218. package/dist/src/core/digest/enhanced-hybrid-digest.js +277 -0
  219. package/dist/src/core/digest/enhanced-hybrid-digest.js.map +7 -0
  220. package/dist/src/core/digest/frame-digest-integration.js +176 -0
  221. package/dist/src/core/digest/frame-digest-integration.js.map +7 -0
  222. package/dist/src/core/digest/hybrid-digest-generator.js +553 -0
  223. package/dist/src/core/digest/hybrid-digest-generator.js.map +7 -0
  224. package/dist/src/core/digest/index.js +9 -0
  225. package/dist/src/core/digest/index.js.map +7 -0
  226. package/dist/src/core/digest/types.js +25 -0
  227. package/dist/src/core/digest/types.js.map +7 -0
  228. package/dist/src/core/errors/error-utils.js +208 -0
  229. package/dist/src/core/errors/error-utils.js.map +7 -0
  230. package/dist/src/core/errors/index.js +521 -0
  231. package/dist/src/core/errors/index.js.map +7 -0
  232. package/dist/src/core/errors/recovery.js +269 -0
  233. package/dist/src/core/errors/recovery.js.map +7 -0
  234. package/dist/src/core/execution/parallel-executor.js +258 -0
  235. package/dist/src/core/execution/parallel-executor.js.map +7 -0
  236. package/dist/src/core/frame/workflow-templates.js +319 -0
  237. package/dist/src/core/frame/workflow-templates.js.map +7 -0
  238. package/dist/src/core/merge/conflict-detector.js +431 -0
  239. package/dist/src/core/merge/conflict-detector.js.map +7 -0
  240. package/dist/src/core/merge/index.js +9 -0
  241. package/dist/src/core/merge/index.js.map +7 -0
  242. package/dist/src/core/merge/resolution-engine.js +558 -0
  243. package/dist/src/core/merge/resolution-engine.js.map +7 -0
  244. package/dist/src/core/merge/stack-diff.js +532 -0
  245. package/dist/src/core/merge/stack-diff.js.map +7 -0
  246. package/dist/src/core/merge/types.js +5 -0
  247. package/dist/src/core/merge/types.js.map +7 -0
  248. package/dist/src/core/merge/unified-merge-resolver.js +303 -0
  249. package/dist/src/core/merge/unified-merge-resolver.js.map +7 -0
  250. package/dist/src/core/models/fallback-monitor.js +232 -0
  251. package/dist/src/core/models/fallback-monitor.js.map +7 -0
  252. package/dist/src/core/models/model-router.js +340 -0
  253. package/dist/src/core/models/model-router.js.map +7 -0
  254. package/dist/src/core/monitoring/error-handler.js +49 -0
  255. package/dist/src/core/monitoring/error-handler.js.map +7 -0
  256. package/dist/src/core/monitoring/logger.js +202 -0
  257. package/dist/src/core/monitoring/logger.js.map +7 -0
  258. package/dist/src/core/monitoring/metrics.js +172 -0
  259. package/dist/src/core/monitoring/metrics.js.map +7 -0
  260. package/dist/src/core/monitoring/progress-tracker.js +189 -0
  261. package/dist/src/core/monitoring/progress-tracker.js.map +7 -0
  262. package/dist/src/core/monitoring/session-monitor.js +300 -0
  263. package/dist/src/core/monitoring/session-monitor.js.map +7 -0
  264. package/dist/src/core/performance/context-cache.js +273 -0
  265. package/dist/src/core/performance/context-cache.js.map +7 -0
  266. package/dist/src/core/performance/index.js +11 -0
  267. package/dist/src/core/performance/index.js.map +7 -0
  268. package/dist/src/core/performance/lazy-context-loader.js +327 -0
  269. package/dist/src/core/performance/lazy-context-loader.js.map +7 -0
  270. package/dist/src/core/performance/monitor.js +221 -0
  271. package/dist/src/core/performance/monitor.js.map +7 -0
  272. package/dist/src/core/performance/optimized-frame-context.js +345 -0
  273. package/dist/src/core/performance/optimized-frame-context.js.map +7 -0
  274. package/dist/src/core/performance/performance-benchmark.js +277 -0
  275. package/dist/src/core/performance/performance-benchmark.js.map +7 -0
  276. package/dist/src/core/performance/performance-profiler.js +370 -0
  277. package/dist/src/core/performance/performance-profiler.js.map +7 -0
  278. package/dist/src/core/performance/streaming-jsonl-parser.js +195 -0
  279. package/dist/src/core/performance/streaming-jsonl-parser.js.map +7 -0
  280. package/dist/src/core/persistence/postgres-adapter.js +349 -0
  281. package/dist/src/core/persistence/postgres-adapter.js.map +7 -0
  282. package/dist/src/core/projects/project-isolation.js +201 -0
  283. package/dist/src/core/projects/project-isolation.js.map +7 -0
  284. package/dist/src/core/projects/project-manager.js +697 -0
  285. package/dist/src/core/projects/project-manager.js.map +7 -0
  286. package/dist/src/core/query/query-parser.js +370 -0
  287. package/dist/src/core/query/query-parser.js.map +7 -0
  288. package/dist/src/core/query/query-templates.js +321 -0
  289. package/dist/src/core/query/query-templates.js.map +7 -0
  290. package/dist/src/core/retrieval/context-retriever.js +479 -0
  291. package/dist/src/core/retrieval/context-retriever.js.map +7 -0
  292. package/dist/src/core/retrieval/index.js +8 -0
  293. package/dist/src/core/retrieval/index.js.map +7 -0
  294. package/dist/src/core/retrieval/llm-context-retrieval.js +613 -0
  295. package/dist/src/core/retrieval/llm-context-retrieval.js.map +7 -0
  296. package/dist/src/core/retrieval/llm-provider.js +151 -0
  297. package/dist/src/core/retrieval/llm-provider.js.map +7 -0
  298. package/dist/src/core/retrieval/retrieval-audit.js +236 -0
  299. package/dist/src/core/retrieval/retrieval-audit.js.map +7 -0
  300. package/dist/src/core/retrieval/summary-generator.js +589 -0
  301. package/dist/src/core/retrieval/summary-generator.js.map +7 -0
  302. package/dist/src/core/retrieval/types.js +21 -0
  303. package/dist/src/core/retrieval/types.js.map +7 -0
  304. package/dist/src/core/security/index.js +35 -0
  305. package/dist/src/core/security/index.js.map +7 -0
  306. package/dist/src/core/security/input-sanitizer.js +321 -0
  307. package/dist/src/core/security/input-sanitizer.js.map +7 -0
  308. package/dist/src/core/session/clear-survival.js +465 -0
  309. package/dist/src/core/session/clear-survival.js.map +7 -0
  310. package/dist/src/core/session/enhanced-handoff.js +792 -0
  311. package/dist/src/core/session/enhanced-handoff.js.map +7 -0
  312. package/dist/src/core/session/handoff-generator.js +343 -0
  313. package/dist/src/core/session/handoff-generator.js.map +7 -0
  314. package/dist/src/core/session/index.js +15 -0
  315. package/dist/src/core/session/index.js.map +7 -0
  316. package/dist/src/core/session/session-manager.js +347 -0
  317. package/dist/src/core/session/session-manager.js.map +7 -0
  318. package/dist/src/core/skills/index.js +7 -0
  319. package/dist/src/core/skills/index.js.map +7 -0
  320. package/dist/src/core/skills/skill-storage.js +764 -0
  321. package/dist/src/core/skills/skill-storage.js.map +7 -0
  322. package/dist/src/core/skills/types.js +193 -0
  323. package/dist/src/core/skills/types.js.map +7 -0
  324. package/dist/src/core/storage/chromadb-adapter.js +354 -0
  325. package/dist/src/core/storage/chromadb-adapter.js.map +7 -0
  326. package/dist/src/core/storage/infinite-storage.js +510 -0
  327. package/dist/src/core/storage/infinite-storage.js.map +7 -0
  328. package/dist/src/core/storage/remote-storage.js +489 -0
  329. package/dist/src/core/storage/remote-storage.js.map +7 -0
  330. package/dist/src/core/storage/two-tier-storage.js +766 -0
  331. package/dist/src/core/storage/two-tier-storage.js.map +7 -0
  332. package/dist/src/core/trace/cli-trace-wrapper.js +132 -0
  333. package/dist/src/core/trace/cli-trace-wrapper.js.map +7 -0
  334. package/dist/src/core/trace/db-trace-wrapper.js +247 -0
  335. package/dist/src/core/trace/db-trace-wrapper.js.map +7 -0
  336. package/dist/src/core/trace/debug-trace.js +417 -0
  337. package/dist/src/core/trace/debug-trace.js.map +7 -0
  338. package/dist/src/core/trace/index.js +109 -0
  339. package/dist/src/core/trace/index.js.map +7 -0
  340. package/dist/src/core/trace/linear-api-wrapper.js +178 -0
  341. package/dist/src/core/trace/linear-api-wrapper.js.map +7 -0
  342. package/dist/src/core/trace/trace-detector.js +528 -0
  343. package/dist/src/core/trace/trace-detector.js.map +7 -0
  344. package/dist/src/core/trace/trace-store.js +345 -0
  345. package/dist/src/core/trace/trace-store.js.map +7 -0
  346. package/dist/src/core/trace/types.js +77 -0
  347. package/dist/src/core/trace/types.js.map +7 -0
  348. package/dist/src/core/types.js +5 -0
  349. package/dist/src/core/types.js.map +7 -0
  350. package/dist/src/core/utils/async-mutex.js +114 -0
  351. package/dist/src/core/utils/async-mutex.js.map +7 -0
  352. package/dist/src/core/utils/compression.js +83 -0
  353. package/dist/src/core/utils/compression.js.map +7 -0
  354. package/dist/src/core/utils/update-checker.js +218 -0
  355. package/dist/src/core/utils/update-checker.js.map +7 -0
  356. package/dist/src/core/worktree/worktree-manager.js +465 -0
  357. package/dist/src/core/worktree/worktree-manager.js.map +7 -0
  358. package/dist/src/daemon/daemon-config.js +149 -0
  359. package/dist/src/daemon/daemon-config.js.map +7 -0
  360. package/dist/src/daemon/services/context-service.js +122 -0
  361. package/dist/src/daemon/services/context-service.js.map +7 -0
  362. package/dist/src/daemon/services/linear-service.js +136 -0
  363. package/dist/src/daemon/services/linear-service.js.map +7 -0
  364. package/dist/src/daemon/session-daemon.js +312 -0
  365. package/dist/src/daemon/session-daemon.js.map +7 -0
  366. package/dist/src/daemon/unified-daemon.js +276 -0
  367. package/dist/src/daemon/unified-daemon.js.map +7 -0
  368. package/dist/src/features/analytics/api/analytics-api.js +287 -0
  369. package/dist/src/features/analytics/api/analytics-api.js.map +7 -0
  370. package/dist/src/features/analytics/core/analytics-service.js +282 -0
  371. package/dist/src/features/analytics/core/analytics-service.js.map +7 -0
  372. package/dist/src/features/analytics/index.js +18 -0
  373. package/dist/src/features/analytics/index.js.map +7 -0
  374. package/dist/src/features/analytics/queries/metrics-queries.js +277 -0
  375. package/dist/src/features/analytics/queries/metrics-queries.js.map +7 -0
  376. package/dist/src/features/analytics/types/metrics.js +5 -0
  377. package/dist/src/features/analytics/types/metrics.js.map +7 -0
  378. package/dist/src/features/browser/browser-mcp.js +492 -0
  379. package/dist/src/features/browser/browser-mcp.js.map +7 -0
  380. package/dist/src/features/sweep/index.js +20 -0
  381. package/dist/src/features/sweep/index.js.map +7 -0
  382. package/dist/src/features/sweep/prediction-client.js +155 -0
  383. package/dist/src/features/sweep/prediction-client.js.map +7 -0
  384. package/dist/src/features/sweep/prompt-builder.js +85 -0
  385. package/dist/src/features/sweep/prompt-builder.js.map +7 -0
  386. package/dist/src/features/sweep/pty-wrapper.js +171 -0
  387. package/dist/src/features/sweep/pty-wrapper.js.map +7 -0
  388. package/dist/src/features/sweep/state-watcher.js +87 -0
  389. package/dist/src/features/sweep/state-watcher.js.map +7 -0
  390. package/dist/src/features/sweep/status-bar.js +88 -0
  391. package/dist/src/features/sweep/status-bar.js.map +7 -0
  392. package/dist/src/features/sweep/sweep-server-manager.js +226 -0
  393. package/dist/src/features/sweep/sweep-server-manager.js.map +7 -0
  394. package/dist/src/features/sweep/tab-interceptor.js +38 -0
  395. package/dist/src/features/sweep/tab-interceptor.js.map +7 -0
  396. package/dist/src/features/sweep/types.js +18 -0
  397. package/dist/src/features/sweep/types.js.map +7 -0
  398. package/dist/src/features/tasks/linear-task-manager.js +487 -0
  399. package/dist/src/features/tasks/linear-task-manager.js.map +7 -0
  400. package/dist/src/features/tasks/task-aware-context.js +410 -0
  401. package/dist/src/features/tasks/task-aware-context.js.map +7 -0
  402. package/dist/src/features/tui/simple-monitor.js +116 -0
  403. package/dist/src/features/tui/simple-monitor.js.map +7 -0
  404. package/dist/src/features/tui/swarm-monitor.js +648 -0
  405. package/dist/src/features/tui/swarm-monitor.js.map +7 -0
  406. package/dist/src/features/web/client/stores/task-store.js +26 -0
  407. package/dist/src/features/web/client/stores/task-store.js.map +7 -0
  408. package/dist/src/features/web/server/index.js +194 -0
  409. package/dist/src/features/web/server/index.js.map +7 -0
  410. package/dist/src/hooks/auto-background.js +151 -0
  411. package/dist/src/hooks/auto-background.js.map +7 -0
  412. package/dist/src/hooks/claude-code-whatsapp-hook.js +197 -0
  413. package/dist/src/hooks/claude-code-whatsapp-hook.js.map +7 -0
  414. package/dist/src/hooks/config.js +150 -0
  415. package/dist/src/hooks/config.js.map +7 -0
  416. package/dist/src/hooks/daemon.js +364 -0
  417. package/dist/src/hooks/daemon.js.map +7 -0
  418. package/dist/src/hooks/events.js +58 -0
  419. package/dist/src/hooks/events.js.map +7 -0
  420. package/dist/src/hooks/index.js +12 -0
  421. package/dist/src/hooks/index.js.map +7 -0
  422. package/dist/src/hooks/linear-task-picker.js +186 -0
  423. package/dist/src/hooks/linear-task-picker.js.map +7 -0
  424. package/dist/src/hooks/schemas.js +197 -0
  425. package/dist/src/hooks/schemas.js.map +7 -0
  426. package/dist/src/hooks/secure-fs.js +49 -0
  427. package/dist/src/hooks/secure-fs.js.map +7 -0
  428. package/dist/src/hooks/security-logger.js +155 -0
  429. package/dist/src/hooks/security-logger.js.map +7 -0
  430. package/dist/src/hooks/session-summary.js +222 -0
  431. package/dist/src/hooks/session-summary.js.map +7 -0
  432. package/dist/src/hooks/sms-action-runner.js +371 -0
  433. package/dist/src/hooks/sms-action-runner.js.map +7 -0
  434. package/dist/src/hooks/sms-notify.js +506 -0
  435. package/dist/src/hooks/sms-notify.js.map +7 -0
  436. package/dist/src/hooks/sms-watcher.js +93 -0
  437. package/dist/src/hooks/sms-watcher.js.map +7 -0
  438. package/dist/src/hooks/sms-webhook.js +555 -0
  439. package/dist/src/hooks/sms-webhook.js.map +7 -0
  440. package/dist/src/hooks/whatsapp-commands.js +479 -0
  441. package/dist/src/hooks/whatsapp-commands.js.map +7 -0
  442. package/dist/src/hooks/whatsapp-scheduler.js +317 -0
  443. package/dist/src/hooks/whatsapp-scheduler.js.map +7 -0
  444. package/dist/src/hooks/whatsapp-sync.js +409 -0
  445. package/dist/src/hooks/whatsapp-sync.js.map +7 -0
  446. package/dist/src/index.js +25 -0
  447. package/dist/src/index.js.map +7 -0
  448. package/dist/src/integrations/anthropic/client.js +263 -0
  449. package/dist/src/integrations/anthropic/client.js.map +7 -0
  450. package/dist/src/integrations/claude-code/agent-bridge.js +768 -0
  451. package/dist/src/integrations/claude-code/agent-bridge.js.map +7 -0
  452. package/dist/src/integrations/claude-code/enhanced-pre-clear-hooks.js +459 -0
  453. package/dist/src/integrations/claude-code/enhanced-pre-clear-hooks.js.map +7 -0
  454. package/dist/src/integrations/claude-code/lifecycle-hooks.js +254 -0
  455. package/dist/src/integrations/claude-code/lifecycle-hooks.js.map +7 -0
  456. package/dist/src/integrations/claude-code/post-task-hooks.js +545 -0
  457. package/dist/src/integrations/claude-code/post-task-hooks.js.map +7 -0
  458. package/dist/src/integrations/claude-code/subagent-client-stub.js +20 -0
  459. package/dist/src/integrations/claude-code/subagent-client-stub.js.map +7 -0
  460. package/dist/src/integrations/claude-code/subagent-client.js +511 -0
  461. package/dist/src/integrations/claude-code/subagent-client.js.map +7 -0
  462. package/dist/src/integrations/claude-code/task-coordinator.js +360 -0
  463. package/dist/src/integrations/claude-code/task-coordinator.js.map +7 -0
  464. package/dist/src/integrations/linear/auth.js +337 -0
  465. package/dist/src/integrations/linear/auth.js.map +7 -0
  466. package/dist/src/integrations/linear/auto-sync.js +258 -0
  467. package/dist/src/integrations/linear/auto-sync.js.map +7 -0
  468. package/dist/src/integrations/linear/client.js +634 -0
  469. package/dist/src/integrations/linear/client.js.map +7 -0
  470. package/dist/src/integrations/linear/config.js +130 -0
  471. package/dist/src/integrations/linear/config.js.map +7 -0
  472. package/dist/src/integrations/linear/migration.js +361 -0
  473. package/dist/src/integrations/linear/migration.js.map +7 -0
  474. package/dist/src/integrations/linear/oauth-server.js +454 -0
  475. package/dist/src/integrations/linear/oauth-server.js.map +7 -0
  476. package/dist/src/integrations/linear/rest-client.js +213 -0
  477. package/dist/src/integrations/linear/rest-client.js.map +7 -0
  478. package/dist/src/integrations/linear/sync-manager.js +236 -0
  479. package/dist/src/integrations/linear/sync-manager.js.map +7 -0
  480. package/dist/src/integrations/linear/sync-service.js +231 -0
  481. package/dist/src/integrations/linear/sync-service.js.map +7 -0
  482. package/dist/src/integrations/linear/sync.js +782 -0
  483. package/dist/src/integrations/linear/sync.js.map +7 -0
  484. package/dist/src/integrations/linear/types.js +5 -0
  485. package/dist/src/integrations/linear/types.js.map +7 -0
  486. package/dist/src/integrations/linear/unified-sync.js +589 -0
  487. package/dist/src/integrations/linear/unified-sync.js.map +7 -0
  488. package/dist/src/integrations/linear/webhook-handler.js +219 -0
  489. package/dist/src/integrations/linear/webhook-handler.js.map +7 -0
  490. package/dist/src/integrations/linear/webhook-server.js +218 -0
  491. package/dist/src/integrations/linear/webhook-server.js.map +7 -0
  492. package/dist/src/integrations/linear/webhook.js +291 -0
  493. package/dist/src/integrations/linear/webhook.js.map +7 -0
  494. package/dist/src/integrations/mcp/handlers/code-execution-handlers.js +266 -0
  495. package/dist/src/integrations/mcp/handlers/code-execution-handlers.js.map +7 -0
  496. package/dist/src/integrations/mcp/handlers/context-handlers.js +257 -0
  497. package/dist/src/integrations/mcp/handlers/context-handlers.js.map +7 -0
  498. package/dist/src/integrations/mcp/handlers/discovery-handlers.js +497 -0
  499. package/dist/src/integrations/mcp/handlers/discovery-handlers.js.map +7 -0
  500. package/dist/src/integrations/mcp/handlers/index.js +166 -0
  501. package/dist/src/integrations/mcp/handlers/index.js.map +7 -0
  502. package/dist/src/integrations/mcp/handlers/linear-handlers.js +247 -0
  503. package/dist/src/integrations/mcp/handlers/linear-handlers.js.map +7 -0
  504. package/dist/src/integrations/mcp/handlers/skill-handlers.js +529 -0
  505. package/dist/src/integrations/mcp/handlers/skill-handlers.js.map +7 -0
  506. package/dist/src/integrations/mcp/handlers/task-handlers.js +239 -0
  507. package/dist/src/integrations/mcp/handlers/task-handlers.js.map +7 -0
  508. package/dist/src/integrations/mcp/handlers/trace-handlers.js +308 -0
  509. package/dist/src/integrations/mcp/handlers/trace-handlers.js.map +7 -0
  510. package/dist/src/integrations/mcp/index.js +23 -0
  511. package/dist/src/integrations/mcp/index.js.map +7 -0
  512. package/dist/src/integrations/mcp/middleware/tool-scoring.js +356 -0
  513. package/dist/src/integrations/mcp/middleware/tool-scoring.js.map +7 -0
  514. package/dist/src/integrations/mcp/refactored-server.js +374 -0
  515. package/dist/src/integrations/mcp/refactored-server.js.map +7 -0
  516. package/dist/src/integrations/mcp/remote-server.js +682 -0
  517. package/dist/src/integrations/mcp/remote-server.js.map +7 -0
  518. package/dist/src/integrations/mcp/schemas.js +147 -0
  519. package/dist/src/integrations/mcp/schemas.js.map +7 -0
  520. package/dist/src/integrations/mcp/server.js +1975 -0
  521. package/dist/src/integrations/mcp/server.js.map +7 -0
  522. package/dist/src/integrations/mcp/tool-definitions-code.js +125 -0
  523. package/dist/src/integrations/mcp/tool-definitions-code.js.map +7 -0
  524. package/dist/src/integrations/mcp/tool-definitions.js +702 -0
  525. package/dist/src/integrations/mcp/tool-definitions.js.map +7 -0
  526. package/dist/src/integrations/ralph/bridge/ralph-stackmemory-bridge.js +860 -0
  527. package/dist/src/integrations/ralph/bridge/ralph-stackmemory-bridge.js.map +7 -0
  528. package/dist/src/integrations/ralph/context/context-budget-manager.js +301 -0
  529. package/dist/src/integrations/ralph/context/context-budget-manager.js.map +7 -0
  530. package/dist/src/integrations/ralph/context/stackmemory-context-loader.js +360 -0
  531. package/dist/src/integrations/ralph/context/stackmemory-context-loader.js.map +7 -0
  532. package/dist/src/integrations/ralph/coordination/enhanced-coordination.js +410 -0
  533. package/dist/src/integrations/ralph/coordination/enhanced-coordination.js.map +7 -0
  534. package/dist/src/integrations/ralph/index.js +18 -0
  535. package/dist/src/integrations/ralph/index.js.map +7 -0
  536. package/dist/src/integrations/ralph/learning/pattern-learner.js +401 -0
  537. package/dist/src/integrations/ralph/learning/pattern-learner.js.map +7 -0
  538. package/dist/src/integrations/ralph/lifecycle/iteration-lifecycle.js +448 -0
  539. package/dist/src/integrations/ralph/lifecycle/iteration-lifecycle.js.map +7 -0
  540. package/dist/src/integrations/ralph/monitoring/swarm-dashboard.js +294 -0
  541. package/dist/src/integrations/ralph/monitoring/swarm-dashboard.js.map +7 -0
  542. package/dist/src/integrations/ralph/monitoring/swarm-registry.js +108 -0
  543. package/dist/src/integrations/ralph/monitoring/swarm-registry.js.map +7 -0
  544. package/dist/src/integrations/ralph/orchestration/multi-loop-orchestrator.js +463 -0
  545. package/dist/src/integrations/ralph/orchestration/multi-loop-orchestrator.js.map +7 -0
  546. package/dist/src/integrations/ralph/patterns/compounding-engineering-pattern.js +400 -0
  547. package/dist/src/integrations/ralph/patterns/compounding-engineering-pattern.js.map +7 -0
  548. package/dist/src/integrations/ralph/patterns/extended-coherence-sessions.js +473 -0
  549. package/dist/src/integrations/ralph/patterns/extended-coherence-sessions.js.map +7 -0
  550. package/dist/src/integrations/ralph/patterns/oracle-worker-pattern.js +388 -0
  551. package/dist/src/integrations/ralph/patterns/oracle-worker-pattern.js.map +7 -0
  552. package/dist/src/integrations/ralph/performance/performance-optimizer.js +358 -0
  553. package/dist/src/integrations/ralph/performance/performance-optimizer.js.map +7 -0
  554. package/dist/src/integrations/ralph/recovery/crash-recovery.js +462 -0
  555. package/dist/src/integrations/ralph/recovery/crash-recovery.js.map +7 -0
  556. package/dist/src/integrations/ralph/state/state-reconciler.js +404 -0
  557. package/dist/src/integrations/ralph/state/state-reconciler.js.map +7 -0
  558. package/dist/src/integrations/ralph/swarm/git-workflow-manager.js +428 -0
  559. package/dist/src/integrations/ralph/swarm/git-workflow-manager.js.map +7 -0
  560. package/dist/src/integrations/ralph/swarm/swarm-coordinator.js +996 -0
  561. package/dist/src/integrations/ralph/swarm/swarm-coordinator.js.map +7 -0
  562. package/dist/src/integrations/ralph/types.js +5 -0
  563. package/dist/src/integrations/ralph/types.js.map +7 -0
  564. package/dist/src/integrations/ralph/visualization/ralph-debugger.js +585 -0
  565. package/dist/src/integrations/ralph/visualization/ralph-debugger.js.map +7 -0
  566. package/dist/src/mcp/stackmemory-mcp-server.js +554 -0
  567. package/dist/src/mcp/stackmemory-mcp-server.js.map +7 -0
  568. package/dist/src/middleware/exponential-rate-limiter.js +289 -0
  569. package/dist/src/middleware/exponential-rate-limiter.js.map +7 -0
  570. package/dist/src/models/user.model.js +358 -0
  571. package/dist/src/models/user.model.js.map +7 -0
  572. package/dist/src/servers/production/auth-middleware.js +528 -0
  573. package/dist/src/servers/production/auth-middleware.js.map +7 -0
  574. package/dist/src/services/config-service.js +65 -0
  575. package/dist/src/services/config-service.js.map +7 -0
  576. package/dist/src/services/context-service.js +194 -0
  577. package/dist/src/services/context-service.js.map +7 -0
  578. package/dist/src/skills/api-discovery.js +354 -0
  579. package/dist/src/skills/api-discovery.js.map +7 -0
  580. package/dist/src/skills/api-skill.js +475 -0
  581. package/dist/src/skills/api-skill.js.map +7 -0
  582. package/dist/src/skills/claude-skills.js +1061 -0
  583. package/dist/src/skills/claude-skills.js.map +7 -0
  584. package/dist/src/skills/dashboard-launcher.js +216 -0
  585. package/dist/src/skills/dashboard-launcher.js.map +7 -0
  586. package/dist/src/skills/recursive-agent-orchestrator.js +575 -0
  587. package/dist/src/skills/recursive-agent-orchestrator.js.map +7 -0
  588. package/dist/src/skills/repo-ingestion-skill.js +609 -0
  589. package/dist/src/skills/repo-ingestion-skill.js.map +7 -0
  590. package/dist/src/skills/unified-rlm-orchestrator.js +404 -0
  591. package/dist/src/skills/unified-rlm-orchestrator.js.map +7 -0
  592. package/dist/src/types/task.js +5 -0
  593. package/dist/src/types/task.js.map +7 -0
  594. package/dist/src/utils/env.js +50 -0
  595. package/dist/src/utils/env.js.map +7 -0
  596. package/dist/src/utils/formatting.js +62 -0
  597. package/dist/src/utils/formatting.js.map +7 -0
  598. package/dist/src/utils/process-cleanup.js +136 -0
  599. package/dist/src/utils/process-cleanup.js.map +7 -0
  600. package/package.json +4 -3
  601. package/scripts/create-cleanup-issues.js +302 -0
  602. package/scripts/demos/browser-test.ts +39 -0
  603. package/scripts/demos/ralph-integration-demo.ts +244 -0
  604. package/scripts/demos/trace-demo.ts +214 -0
  605. package/scripts/demos/trace-detector.demo.ts +171 -0
  606. package/scripts/demos/trace-test.ts +67 -0
  607. package/scripts/initialize.ts +16 -7
  608. package/scripts/install.sh +14 -62
  609. package/scripts/status.ts +111 -46
  610. package/scripts/test-claude-config.sh +123 -0
  611. package/scripts/validate-claude-config.sh +155 -0
@@ -0,0 +1,996 @@
1
+ import { fileURLToPath as __fileURLToPath } from 'url';
2
+ import { dirname as __pathDirname } from 'path';
3
+ const __filename = __fileURLToPath(import.meta.url);
4
+ const __dirname = __pathDirname(__filename);
5
+ import { v4 as uuidv4 } from "uuid";
6
+ import * as fs from "fs/promises";
7
+ import * as path from "path";
8
+ import { logger } from "../../../core/monitoring/logger.js";
9
+ import { FrameManager } from "../../../core/context/index.js";
10
+ import { sessionManager } from "../../../core/session/index.js";
11
+ import { sharedContextLayer } from "../../../core/context/shared-context-layer.js";
12
+ import { RalphStackMemoryBridge } from "../bridge/ralph-stackmemory-bridge.js";
13
+ import { GitWorkflowManager } from "./git-workflow-manager.js";
14
+ import { SwarmRegistry } from "../monitoring/swarm-registry.js";
15
+ class SwarmCoordinationError extends Error {
16
+ constructor(message, context) {
17
+ super(message);
18
+ this.context = context;
19
+ this.name = "SwarmCoordinationError";
20
+ }
21
+ }
22
+ class AgentExecutionError extends Error {
23
+ constructor(message, agentId, taskId, context) {
24
+ super(message);
25
+ this.agentId = agentId;
26
+ this.taskId = taskId;
27
+ this.context = context;
28
+ this.name = "AgentExecutionError";
29
+ }
30
+ }
31
+ class TaskAllocationError extends Error {
32
+ constructor(message, taskId, context) {
33
+ super(message);
34
+ this.taskId = taskId;
35
+ this.context = context;
36
+ this.name = "TaskAllocationError";
37
+ }
38
+ }
39
+ class SwarmCoordinator {
40
+ frameManager;
41
+ activeAgents = /* @__PURE__ */ new Map();
42
+ swarmState;
43
+ config;
44
+ coordinationTimer;
45
+ plannerWakeupQueue = /* @__PURE__ */ new Map();
46
+ gitWorkflowManager;
47
+ registeredSwarmId;
48
+ get swarmId() {
49
+ return this.registeredSwarmId;
50
+ }
51
+ get agents() {
52
+ return Array.from(this.activeAgents.values());
53
+ }
54
+ constructor(config) {
55
+ this.config = {
56
+ maxAgents: 10,
57
+ coordinationInterval: 3e4,
58
+ // 30 seconds
59
+ driftDetectionThreshold: 5,
60
+ // 5 failed iterations before considering drift
61
+ freshStartInterval: 36e5,
62
+ // 1 hour
63
+ conflictResolutionStrategy: "expertise",
64
+ enableDynamicPlanning: true,
65
+ pathologicalBehaviorDetection: true,
66
+ ...config
67
+ };
68
+ this.swarmState = {
69
+ id: uuidv4(),
70
+ status: "idle",
71
+ startTime: Date.now(),
72
+ activeTaskCount: 0,
73
+ completedTaskCount: 0,
74
+ coordination: {
75
+ events: [],
76
+ conflicts: [],
77
+ resolutions: []
78
+ },
79
+ performance: {
80
+ throughput: 0,
81
+ efficiency: 0,
82
+ coordination_overhead: 0
83
+ }
84
+ };
85
+ this.gitWorkflowManager = new GitWorkflowManager({
86
+ enableGitWorkflow: true,
87
+ branchStrategy: "agent",
88
+ autoCommit: true,
89
+ commitFrequency: 5,
90
+ mergStrategy: "squash"
91
+ });
92
+ logger.info("Swarm coordinator initialized", this.config);
93
+ }
94
+ async initialize() {
95
+ try {
96
+ await sessionManager.initialize();
97
+ await sharedContextLayer.initialize();
98
+ const session = await sessionManager.getOrCreateSession({});
99
+ if (session.database) {
100
+ this.frameManager = new FrameManager(
101
+ session.database,
102
+ session.projectId
103
+ );
104
+ }
105
+ this.startCoordinationLoop();
106
+ const registry = SwarmRegistry.getInstance();
107
+ this.registeredSwarmId = registry.registerSwarm(
108
+ this,
109
+ `Swarm ${this.swarmState.id.substring(0, 8)}`
110
+ );
111
+ logger.info("Swarm coordinator initialized successfully");
112
+ } catch (error) {
113
+ logger.error("Failed to initialize swarm coordinator", error);
114
+ throw error;
115
+ }
116
+ }
117
+ /**
118
+ * Launch a swarm of agents to work on a complex project
119
+ */
120
+ async launchSwarm(projectDescription, agents, coordination) {
121
+ logger.info("Launching swarm", {
122
+ project: projectDescription.substring(0, 100),
123
+ agentCount: agents.length
124
+ });
125
+ const swarmId = uuidv4();
126
+ try {
127
+ if (agents.length > this.config.maxAgents) {
128
+ throw new Error(
129
+ `Too many agents requested: ${agents.length} > ${this.config.maxAgents}`
130
+ );
131
+ }
132
+ const swarmTasks = await this.decomposeProjectIntoSwarmTasks(projectDescription);
133
+ const initializedAgents = await this.initializeSpecializedAgents(
134
+ agents,
135
+ swarmTasks
136
+ );
137
+ const allocation = await this.allocateTasksToAgents(
138
+ swarmTasks,
139
+ initializedAgents
140
+ );
141
+ this.swarmState = {
142
+ ...this.swarmState,
143
+ id: swarmId,
144
+ status: "active",
145
+ activeTaskCount: swarmTasks.length,
146
+ project: projectDescription,
147
+ agents: initializedAgents,
148
+ tasks: swarmTasks,
149
+ allocation
150
+ };
151
+ await this.executeSwarmTasks(allocation);
152
+ logger.info("Swarm launched successfully", {
153
+ swarmId,
154
+ agentCount: initializedAgents.length
155
+ });
156
+ return swarmId;
157
+ } catch (error) {
158
+ logger.error("Failed to launch swarm", error);
159
+ throw error;
160
+ }
161
+ }
162
+ /**
163
+ * Decompose project into tasks suitable for swarm execution
164
+ */
165
+ async decomposeProjectIntoSwarmTasks(projectDescription) {
166
+ const tasks = [];
167
+ const complexity = this.analyzeProjectComplexity(projectDescription);
168
+ if (complexity.needsArchitecture) {
169
+ tasks.push({
170
+ id: uuidv4(),
171
+ type: "architecture",
172
+ title: "System Architecture Design",
173
+ description: "Design overall system architecture and component relationships",
174
+ priority: 1,
175
+ estimatedEffort: "high",
176
+ requiredRoles: ["architect", "system_designer"],
177
+ dependencies: [],
178
+ acceptanceCriteria: [
179
+ "Architecture diagram created",
180
+ "Component interfaces defined",
181
+ "Data flow documented"
182
+ ]
183
+ });
184
+ }
185
+ const coreFeatures = this.extractCoreFeatures(projectDescription);
186
+ for (const feature of coreFeatures) {
187
+ tasks.push({
188
+ id: uuidv4(),
189
+ type: "implementation",
190
+ title: `Implement ${feature.name}`,
191
+ description: feature.description,
192
+ priority: 2,
193
+ estimatedEffort: feature.complexity,
194
+ requiredRoles: ["developer", feature.specialization || "fullstack"],
195
+ dependencies: complexity.needsArchitecture ? [tasks[0].id] : [],
196
+ acceptanceCriteria: feature.criteria
197
+ });
198
+ }
199
+ if (complexity.needsTesting) {
200
+ tasks.push({
201
+ id: uuidv4(),
202
+ type: "testing",
203
+ title: "Comprehensive Testing Suite",
204
+ description: "Create unit, integration, and end-to-end tests",
205
+ priority: 3,
206
+ estimatedEffort: "medium",
207
+ requiredRoles: ["qa_engineer", "test_automation"],
208
+ dependencies: tasks.filter((t) => t.type === "implementation").map((t) => t.id),
209
+ acceptanceCriteria: [
210
+ "Unit tests achieve >90% coverage",
211
+ "Integration tests pass",
212
+ "Performance benchmarks met"
213
+ ]
214
+ });
215
+ }
216
+ if (complexity.needsDocumentation) {
217
+ tasks.push({
218
+ id: uuidv4(),
219
+ type: "documentation",
220
+ title: "Documentation and Examples",
221
+ description: "Create user documentation, API docs, and usage examples",
222
+ priority: 4,
223
+ estimatedEffort: "low",
224
+ requiredRoles: ["technical_writer", "developer"],
225
+ dependencies: [],
226
+ // Can run in parallel
227
+ acceptanceCriteria: [
228
+ "README with setup instructions",
229
+ "API documentation complete",
230
+ "Usage examples provided"
231
+ ]
232
+ });
233
+ }
234
+ return tasks;
235
+ }
236
+ /**
237
+ * Initialize specialized agents with role-specific configurations
238
+ */
239
+ async initializeSpecializedAgents(specifications, tasks) {
240
+ const agents = [];
241
+ for (const spec of specifications) {
242
+ const agent = {
243
+ id: uuidv4(),
244
+ role: spec.role,
245
+ specialization: spec,
246
+ status: "initializing",
247
+ capabilities: this.defineCapabilities(spec.role),
248
+ workingDirectory: `.swarm/${spec.role}-${Date.now()}`,
249
+ currentTask: null,
250
+ performance: {
251
+ tasksCompleted: 0,
252
+ successRate: 1,
253
+ averageTaskTime: 0,
254
+ driftDetected: false,
255
+ lastFreshStart: Date.now()
256
+ },
257
+ coordination: {
258
+ communicationStyle: this.defineCommuncationStyle(spec.role),
259
+ conflictResolution: spec.conflictResolution || "defer_to_expertise",
260
+ collaborationPreferences: spec.collaborationPreferences || []
261
+ }
262
+ };
263
+ await this.setupAgentEnvironment(agent);
264
+ await this.configureAgentPrompts(agent);
265
+ agents.push(agent);
266
+ this.activeAgents.set(agent.id, agent);
267
+ }
268
+ logger.info(`Initialized ${agents.length} specialized agents`);
269
+ return agents;
270
+ }
271
+ /**
272
+ * Allocate tasks to agents based on specialization and workload
273
+ */
274
+ async allocateTasksToAgents(tasks, agents) {
275
+ const allocation = {
276
+ assignments: /* @__PURE__ */ new Map(),
277
+ loadBalancing: "capability_based",
278
+ conflictResolution: this.config.conflictResolutionStrategy
279
+ };
280
+ const sortedTasks = this.topologicalSort(tasks);
281
+ for (const task of sortedTasks) {
282
+ const suitableAgents = agents.filter(
283
+ (agent) => task.requiredRoles.some((role) => this.agentCanHandle(agent, role))
284
+ );
285
+ if (suitableAgents.length === 0) {
286
+ logger.warn(`No suitable agents found for task: ${task.title}`);
287
+ continue;
288
+ }
289
+ const selectedAgent = this.selectOptimalAgent(suitableAgents, task);
290
+ allocation.assignments.set(task.id, {
291
+ agentId: selectedAgent.id,
292
+ taskId: task.id,
293
+ assignedAt: Date.now(),
294
+ estimatedCompletion: Date.now() + this.estimateTaskDuration(task),
295
+ coordination: {
296
+ collaborators: this.findCollaborators(selectedAgent, task, agents),
297
+ reviewers: this.findReviewers(selectedAgent, task, agents)
298
+ }
299
+ });
300
+ selectedAgent.currentTask = task.id;
301
+ }
302
+ return allocation;
303
+ }
304
+ /**
305
+ * Execute swarm tasks with coordination
306
+ */
307
+ async executeSwarmTasks(allocation) {
308
+ const executionPromises = [];
309
+ for (const [taskId, assignment] of allocation.assignments) {
310
+ const agent = this.activeAgents.get(assignment.agentId);
311
+ const task = this.swarmState.tasks?.find((t) => t.id === taskId);
312
+ if (!agent || !task) continue;
313
+ const executionPromise = this.executeAgentTask(agent, task, assignment);
314
+ executionPromises.push(executionPromise);
315
+ }
316
+ await Promise.allSettled(executionPromises);
317
+ }
318
+ /**
319
+ * Execute a single agent task with coordination
320
+ */
321
+ async executeAgentTask(agent, task, assignment) {
322
+ logger.info(`Agent ${agent.role} starting task: ${task.title}`);
323
+ try {
324
+ agent.status = "active";
325
+ await this.gitWorkflowManager.initializeAgentWorkflow(agent, task);
326
+ const ralph = new RalphStackMemoryBridge({
327
+ baseDir: path.join(agent.workingDirectory, task.id),
328
+ maxIterations: this.calculateMaxIterations(task),
329
+ useStackMemory: true
330
+ });
331
+ const contextualPrompt = await this.synthesizeContextualPrompt(
332
+ agent,
333
+ task
334
+ );
335
+ await ralph.initialize({
336
+ task: contextualPrompt,
337
+ criteria: task.acceptanceCriteria.join("\n")
338
+ });
339
+ this.setupAgentCoordination(agent, ralph, assignment);
340
+ let iteration = 1;
341
+ const maxIterations = this.calculateMaxIterations(task);
342
+ while (iteration <= maxIterations) {
343
+ try {
344
+ const result = await ralph.runWorkerIteration();
345
+ if (result.isComplete) {
346
+ logger.info(`Task completed in ${iteration} iterations`);
347
+ break;
348
+ }
349
+ iteration++;
350
+ } catch (error) {
351
+ logger.error(`Iteration ${iteration} failed:`, error);
352
+ if (iteration >= maxIterations) {
353
+ throw error;
354
+ }
355
+ iteration++;
356
+ }
357
+ }
358
+ await this.gitWorkflowManager.commitAgentWork(agent, task);
359
+ this.updateAgentPerformance(agent, true);
360
+ await this.gitWorkflowManager.mergeAgentWork(agent, task);
361
+ await this.notifyTaskCompletion(agent, task, true);
362
+ agent.status = "idle";
363
+ logger.info(`Agent ${agent.role} completed task: ${task.title}`);
364
+ } catch (error) {
365
+ logger.error(
366
+ `Agent ${agent.role} failed task: ${task.title}`,
367
+ error
368
+ );
369
+ this.updateAgentPerformance(agent, false);
370
+ await this.handleTaskFailure(agent, task, error);
371
+ agent.status = "error";
372
+ }
373
+ }
374
+ /**
375
+ * Synthesize contextual prompt incorporating swarm knowledge
376
+ */
377
+ async synthesizeContextualPrompt(agent, task) {
378
+ const basePrompt = task.description;
379
+ const roleSpecificInstructions = this.getRoleSpecificInstructions(
380
+ agent.role
381
+ );
382
+ const swarmContext = await this.getSwarmContext(task);
383
+ const coordinationInstructions = this.getCoordinationInstructions(agent);
384
+ return `
385
+ ${roleSpecificInstructions}
386
+
387
+ TASK: ${basePrompt}
388
+
389
+ SWARM CONTEXT:
390
+ ${swarmContext}
391
+
392
+ COORDINATION GUIDELINES:
393
+ ${coordinationInstructions}
394
+
395
+ Remember:
396
+ - You are part of a swarm working on: ${this.swarmState.project}
397
+ - Other agents are working on related tasks
398
+ - Communicate findings through StackMemory shared context
399
+ - Focus on your specialization while being aware of the bigger picture
400
+ - Detect and avoid pathological behaviors (infinite loops, tunnel vision)
401
+ - Request fresh starts if you detect drift in your approach
402
+
403
+ ACCEPTANCE CRITERIA:
404
+ ${task.acceptanceCriteria.map((c) => `- ${c}`).join("\n")}
405
+ `;
406
+ }
407
+ /**
408
+ * Start coordination monitoring loop
409
+ */
410
+ startCoordinationLoop() {
411
+ this.coordinationTimer = setInterval(() => {
412
+ this.performCoordinationCycle().catch((error) => {
413
+ logger.error("Coordination cycle failed", error);
414
+ });
415
+ }, this.config.coordinationInterval);
416
+ }
417
+ /**
418
+ * Perform coordination cycle
419
+ */
420
+ async performCoordinationCycle() {
421
+ if (this.swarmState.status !== "active") return;
422
+ logger.debug("Performing coordination cycle");
423
+ if (this.config.pathologicalBehaviorDetection) {
424
+ await this.detectPathologicalBehaviors();
425
+ }
426
+ if (this.config.enableDynamicPlanning) {
427
+ await this.wakeUpPlanners();
428
+ }
429
+ await this.resolveActiveConflicts();
430
+ await this.rebalanceWorkload();
431
+ await this.triggerFreshStartsIfNeeded();
432
+ this.updateSwarmMetrics();
433
+ }
434
+ /**
435
+ * Detect pathological behaviors in agents
436
+ */
437
+ async detectPathologicalBehaviors() {
438
+ for (const agent of this.activeAgents.values()) {
439
+ if (agent.status !== "active") continue;
440
+ if (agent.performance.driftDetected) {
441
+ logger.warn(
442
+ `Drift detected in agent ${agent.role}, triggering fresh start`
443
+ );
444
+ await this.triggerFreshStart(agent);
445
+ continue;
446
+ }
447
+ if (await this.detectTunnelVision(agent)) {
448
+ logger.warn(
449
+ `Tunnel vision detected in agent ${agent.role}, providing alternative approach`
450
+ );
451
+ await this.provideAlternativeApproach(agent);
452
+ }
453
+ if (await this.detectExcessiveRuntime(agent)) {
454
+ logger.warn(
455
+ `Excessive runtime detected in agent ${agent.role}, requesting checkpoint`
456
+ );
457
+ await this.requestCheckpoint(agent);
458
+ }
459
+ }
460
+ }
461
+ /**
462
+ * Wake up planners when their tasks complete
463
+ */
464
+ async wakeUpPlanners() {
465
+ for (const [agentId, wakeupCallback] of this.plannerWakeupQueue) {
466
+ const agent = this.activeAgents.get(agentId);
467
+ if (!agent || agent.status !== "idle") continue;
468
+ logger.info(`Waking up planner agent: ${agent.role}`);
469
+ wakeupCallback();
470
+ this.plannerWakeupQueue.delete(agentId);
471
+ }
472
+ }
473
+ /**
474
+ * Get status of a specific swarm
475
+ */
476
+ getSwarmStatus(swarmId) {
477
+ const registry = SwarmRegistry.getInstance();
478
+ const swarm = registry.getSwarm(swarmId);
479
+ if (!swarm) {
480
+ return null;
481
+ }
482
+ return {
483
+ id: swarmId,
484
+ state: swarm.status || "running",
485
+ activeAgents: swarm.agents?.length || 0,
486
+ startTime: swarm.startTime || Date.now(),
487
+ agents: swarm.agents?.map((agent) => ({
488
+ role: agent.role,
489
+ status: agent.status || "active",
490
+ task: agent.task || "Working"
491
+ }))
492
+ };
493
+ }
494
+ /**
495
+ * Get all active swarms
496
+ */
497
+ getAllActiveSwarms() {
498
+ const registry = SwarmRegistry.getInstance();
499
+ const activeSwarms = registry.listActiveSwarms();
500
+ return activeSwarms.map((swarm) => ({
501
+ id: swarm.id,
502
+ description: swarm.description,
503
+ agentCount: swarm.agents?.length || 0,
504
+ status: swarm.status || "running",
505
+ startTime: swarm.startTime || Date.now()
506
+ }));
507
+ }
508
+ /**
509
+ * Stop a specific swarm gracefully
510
+ */
511
+ async stopSwarm(swarmId) {
512
+ const targetId = swarmId || this.swarmId;
513
+ if (!targetId) {
514
+ throw new Error("No swarm ID provided");
515
+ }
516
+ logger.info("Stopping swarm", { swarmId: targetId });
517
+ for (const agent of this.agents) {
518
+ try {
519
+ await this.stopAgent(agent);
520
+ } catch (error) {
521
+ logger.error("Failed to stop agent", {
522
+ agent: agent.id,
523
+ error: error.message
524
+ });
525
+ }
526
+ }
527
+ if (this.gitWorkflowManager) {
528
+ try {
529
+ await this.gitWorkflowManager.cleanup();
530
+ } catch (error) {
531
+ logger.error("Git cleanup failed", { error: error.message });
532
+ }
533
+ }
534
+ const registry = SwarmRegistry.getInstance();
535
+ registry.unregisterSwarm(targetId);
536
+ logger.info("Swarm stopped", { swarmId: targetId });
537
+ }
538
+ /**
539
+ * Force stop a swarm without saving state
540
+ */
541
+ async forceStopSwarm(swarmId) {
542
+ logger.info("Force stopping swarm", { swarmId });
543
+ const registry = SwarmRegistry.getInstance();
544
+ registry.unregisterSwarm(swarmId);
545
+ this.activeAgents.clear();
546
+ logger.info("Swarm force stopped", { swarmId });
547
+ }
548
+ /**
549
+ * Cleanup all resources
550
+ */
551
+ async cleanup() {
552
+ logger.info("Cleaning up SwarmCoordinator resources");
553
+ const activeSwarms = this.getAllActiveSwarms();
554
+ for (const swarm of activeSwarms) {
555
+ try {
556
+ await this.stopSwarm(swarm.id);
557
+ } catch (error) {
558
+ logger.error("Failed to stop swarm during cleanup", {
559
+ swarmId: swarm.id,
560
+ error: error.message
561
+ });
562
+ }
563
+ }
564
+ const registry = SwarmRegistry.getInstance();
565
+ registry.cleanup();
566
+ this.activeAgents.clear();
567
+ logger.info("SwarmCoordinator cleanup completed");
568
+ }
569
+ /**
570
+ * Stop an individual agent
571
+ */
572
+ async stopAgent(agent) {
573
+ logger.debug("Stopping agent", { agentId: agent.id, role: agent.role });
574
+ agent.status = "stopped";
575
+ if (agent.ralphBridge) {
576
+ try {
577
+ await agent.ralphBridge.cleanup();
578
+ } catch (error) {
579
+ logger.error("Failed to cleanup agent bridge", {
580
+ error: error.message
581
+ });
582
+ }
583
+ }
584
+ }
585
+ // Helper methods for role specialization and coordination
586
+ defineCapabilities(role) {
587
+ const capabilityMap = {
588
+ architect: [
589
+ "system_design",
590
+ "component_modeling",
591
+ "architecture_validation"
592
+ ],
593
+ planner: [
594
+ "task_decomposition",
595
+ "dependency_analysis",
596
+ "resource_planning"
597
+ ],
598
+ developer: ["code_implementation", "debugging", "refactoring"],
599
+ reviewer: [
600
+ "code_review",
601
+ "quality_assessment",
602
+ "best_practice_enforcement"
603
+ ],
604
+ tester: ["test_design", "automation", "validation"],
605
+ optimizer: [
606
+ "performance_analysis",
607
+ "resource_optimization",
608
+ "bottleneck_identification"
609
+ ],
610
+ documenter: [
611
+ "technical_writing",
612
+ "api_documentation",
613
+ "example_creation"
614
+ ],
615
+ coordinator: [
616
+ "task_coordination",
617
+ "conflict_resolution",
618
+ "progress_tracking"
619
+ ]
620
+ };
621
+ return capabilityMap[role] || [];
622
+ }
623
+ defineCommuncationStyle(role) {
624
+ const styleMap = {
625
+ architect: "high_level_design_focused",
626
+ planner: "structured_and_methodical",
627
+ developer: "implementation_focused",
628
+ reviewer: "quality_focused_constructive",
629
+ tester: "validation_focused",
630
+ optimizer: "performance_metrics_focused",
631
+ documenter: "clarity_focused",
632
+ coordinator: "facilitative_and_diplomatic"
633
+ };
634
+ return styleMap[role] || "collaborative";
635
+ }
636
+ getRoleSpecificInstructions(role) {
637
+ const instructionMap = {
638
+ architect: `
639
+ You are a SYSTEM ARCHITECT. Your role is to:
640
+ - Design high-level system architecture
641
+ - Define component interfaces and relationships
642
+ - Ensure architectural consistency across the project
643
+ - Think in terms of scalability, maintainability, and extensibility
644
+ - Collaborate with developers to validate feasibility`,
645
+ planner: `
646
+ You are a PROJECT PLANNER. Your role is to:
647
+ - Break down complex tasks into manageable steps
648
+ - Identify dependencies and critical path
649
+ - Coordinate with other agents on sequencing
650
+ - Wake up when tasks complete to plan next steps
651
+ - Adapt plans based on actual progress`,
652
+ developer: `
653
+ You are a SPECIALIZED DEVELOPER. Your role is to:
654
+ - Implement features according to specifications
655
+ - Write clean, maintainable code
656
+ - Follow established patterns and conventions
657
+ - Integrate with other components
658
+ - Communicate implementation details clearly`,
659
+ reviewer: `
660
+ You are a CODE REVIEWER. Your role is to:
661
+ - Review code for quality, correctness, and best practices
662
+ - Provide constructive feedback
663
+ - Ensure consistency with project standards
664
+ - Identify potential issues before they become problems
665
+ - Approve or request changes`,
666
+ tester: `
667
+ You are a QA ENGINEER. Your role is to:
668
+ - Design comprehensive test strategies
669
+ - Implement automated tests
670
+ - Validate functionality and performance
671
+ - Report bugs clearly and reproducibly
672
+ - Ensure quality gates are met`,
673
+ optimizer: `
674
+ You are a PERFORMANCE OPTIMIZER. Your role is to:
675
+ - Analyze system performance and identify bottlenecks
676
+ - Implement optimizations
677
+ - Monitor resource usage
678
+ - Establish performance benchmarks
679
+ - Ensure scalability requirements are met`,
680
+ documenter: `
681
+ You are a TECHNICAL WRITER. Your role is to:
682
+ - Create clear, comprehensive documentation
683
+ - Write API documentation and usage examples
684
+ - Ensure documentation stays up-to-date
685
+ - Focus on user experience and clarity
686
+ - Collaborate with developers to understand features`,
687
+ coordinator: `
688
+ You are a PROJECT COORDINATOR. Your role is to:
689
+ - Facilitate communication between agents
690
+ - Resolve conflicts and blockers
691
+ - Track overall project progress
692
+ - Ensure no tasks fall through cracks
693
+ - Maintain project timeline and quality`
694
+ };
695
+ return instructionMap[role] || "You are a specialized agent contributing to a larger project.";
696
+ }
697
+ // Additional helper methods would be implemented here...
698
+ analyzeProjectComplexity(description) {
699
+ return {
700
+ needsArchitecture: description.length > 500 || description.includes("system") || description.includes("platform"),
701
+ needsTesting: true,
702
+ // Almost all projects need testing
703
+ needsDocumentation: description.includes("API") || description.includes("library"),
704
+ complexity: "medium"
705
+ };
706
+ }
707
+ extractCoreFeatures(description) {
708
+ return [
709
+ {
710
+ name: "Core Feature",
711
+ description: "Main functionality implementation",
712
+ complexity: "medium",
713
+ criteria: [
714
+ "Feature works correctly",
715
+ "Handles edge cases",
716
+ "Follows coding standards"
717
+ ]
718
+ }
719
+ ];
720
+ }
721
+ // Implement remaining helper methods...
722
+ async setupAgentEnvironment(agent) {
723
+ try {
724
+ await fs.mkdir(agent.workingDirectory, { recursive: true });
725
+ logger.debug(
726
+ `Created working directory for agent ${agent.id}: ${agent.workingDirectory}`
727
+ );
728
+ } catch (error) {
729
+ logger.warn(
730
+ `Could not create working directory for agent ${agent.id}`,
731
+ error
732
+ );
733
+ }
734
+ }
735
+ async configureAgentPrompts(agent) {
736
+ logger.debug(`Configured prompts for agent ${agent.role}`);
737
+ }
738
+ topologicalSort(tasks) {
739
+ const sorted = [];
740
+ const visited = /* @__PURE__ */ new Set();
741
+ const visiting = /* @__PURE__ */ new Set();
742
+ const visit = (task) => {
743
+ if (visited.has(task.id)) return;
744
+ if (visiting.has(task.id)) {
745
+ logger.warn(`Circular dependency detected for task: ${task.id}`);
746
+ return;
747
+ }
748
+ visiting.add(task.id);
749
+ for (const depId of task.dependencies) {
750
+ const depTask = tasks.find((t) => t.id === depId);
751
+ if (depTask) visit(depTask);
752
+ }
753
+ visiting.delete(task.id);
754
+ visited.add(task.id);
755
+ sorted.push(task);
756
+ };
757
+ tasks.forEach(visit);
758
+ return sorted;
759
+ }
760
+ agentCanHandle(agent, role) {
761
+ return agent.role === role || agent.capabilities.includes(role);
762
+ }
763
+ selectOptimalAgent(agents, task) {
764
+ return agents.reduce((best, current) => {
765
+ const bestLoad = best.currentTask ? 1 : 0;
766
+ const currentLoad = current.currentTask ? 1 : 0;
767
+ return currentLoad < bestLoad ? current : best;
768
+ });
769
+ }
770
+ estimateTaskDuration(task) {
771
+ const durations = {
772
+ low: 6e4,
773
+ // 1 minute
774
+ medium: 3e5,
775
+ // 5 minutes
776
+ high: 9e5
777
+ // 15 minutes
778
+ };
779
+ return durations[task.estimatedEffort] || 3e5;
780
+ }
781
+ findCollaborators(agent, task, agents) {
782
+ return agents.filter((a) => a.id !== agent.id && a.currentTask).map((a) => a.id).slice(0, 2);
783
+ }
784
+ findReviewers(agent, task, agents) {
785
+ return agents.filter((a) => a.role === "reviewer" && a.id !== agent.id).map((a) => a.id);
786
+ }
787
+ calculateMaxIterations(task) {
788
+ const iterations = {
789
+ low: 5,
790
+ medium: 10,
791
+ high: 20
792
+ };
793
+ return iterations[task.estimatedEffort] || 10;
794
+ }
795
+ async getSwarmContext(task) {
796
+ const relatedTasks = Array.from(this.activeAgents.values()).filter((a) => a.currentTask).map((a) => `- Agent ${a.role} is working on task ${a.currentTask}`).join("\n");
797
+ return relatedTasks || "No other agents currently active";
798
+ }
799
+ getCoordinationInstructions(agent) {
800
+ return `
801
+ - Save progress to shared context regularly
802
+ - Check for updates from collaborators
803
+ - Request help if blocked for more than 2 iterations
804
+ - Report completion immediately`;
805
+ }
806
+ setupAgentCoordination(agent, ralph, assignment) {
807
+ logger.debug(`Setting up coordination for agent ${agent.id}`);
808
+ }
809
+ updateAgentPerformance(agent, success) {
810
+ agent.performance.tasksCompleted++;
811
+ if (!success) {
812
+ agent.performance.successRate = agent.performance.successRate * (agent.performance.tasksCompleted - 1) / agent.performance.tasksCompleted;
813
+ }
814
+ }
815
+ async notifyTaskCompletion(agent, task, success) {
816
+ const event = {
817
+ type: "task_completion",
818
+ agentId: agent.id,
819
+ timestamp: Date.now(),
820
+ data: {
821
+ taskId: task.id,
822
+ success,
823
+ agent: agent.role
824
+ }
825
+ };
826
+ this.swarmState.coordination?.events.push(event);
827
+ logger.info(
828
+ `Task ${task.id} completed by agent ${agent.role}: ${success ? "SUCCESS" : "FAILED"}`
829
+ );
830
+ }
831
+ async handleTaskFailure(agent, task, error) {
832
+ logger.error(`Agent ${agent.role} failed task ${task.id}`, error);
833
+ if (this.swarmState.coordination) {
834
+ this.swarmState.coordination.conflicts.push({
835
+ type: "task_failure",
836
+ agents: [agent.id],
837
+ timestamp: Date.now(),
838
+ description: error.message
839
+ });
840
+ }
841
+ }
842
+ async detectTunnelVision(agent) {
843
+ return false;
844
+ }
845
+ async provideAlternativeApproach(agent) {
846
+ logger.info(`Providing alternative approach to agent ${agent.role}`);
847
+ }
848
+ async detectExcessiveRuntime(agent) {
849
+ if (!agent.performance.lastFreshStart) return false;
850
+ return Date.now() - agent.performance.lastFreshStart > 36e5;
851
+ }
852
+ async requestCheckpoint(agent) {
853
+ logger.info(`Requesting checkpoint from agent ${agent.role}`);
854
+ }
855
+ async triggerFreshStart(agent) {
856
+ logger.info(`Triggering fresh start for agent ${agent.role}`);
857
+ agent.performance.lastFreshStart = Date.now();
858
+ agent.performance.driftDetected = false;
859
+ }
860
+ async resolveActiveConflicts() {
861
+ if (this.swarmState.coordination?.conflicts.length) {
862
+ logger.debug(
863
+ `Resolving ${this.swarmState.coordination.conflicts.length} conflicts`
864
+ );
865
+ }
866
+ }
867
+ async rebalanceWorkload() {
868
+ const activeAgents = Array.from(this.activeAgents.values()).filter(
869
+ (a) => a.status === "active"
870
+ );
871
+ if (activeAgents.length > 0) {
872
+ logger.debug(
873
+ `Rebalancing workload among ${activeAgents.length} active agents`
874
+ );
875
+ }
876
+ }
877
+ async triggerFreshStartsIfNeeded() {
878
+ for (const agent of this.activeAgents.values()) {
879
+ if (agent.performance.driftDetected) {
880
+ await this.triggerFreshStart(agent);
881
+ }
882
+ }
883
+ }
884
+ updateSwarmMetrics() {
885
+ if (!this.swarmState.performance) return;
886
+ const activeCount = Array.from(this.activeAgents.values()).filter(
887
+ (a) => a.status === "active"
888
+ ).length;
889
+ this.swarmState.performance.throughput = this.swarmState.completedTaskCount / ((Date.now() - this.swarmState.startTime) / 1e3);
890
+ this.swarmState.performance.efficiency = activeCount > 0 ? this.swarmState.completedTaskCount / activeCount : 0;
891
+ }
892
+ /**
893
+ * Cleanup completed swarms and their resources
894
+ */
895
+ async cleanupCompletedSwarms() {
896
+ if (this.swarmState.status !== "completed") {
897
+ return;
898
+ }
899
+ try {
900
+ logger.info("Cleaning up completed swarm resources");
901
+ if (this.coordinationTimer) {
902
+ clearInterval(this.coordinationTimer);
903
+ this.coordinationTimer = void 0;
904
+ }
905
+ for (const agent of this.activeAgents.values()) {
906
+ try {
907
+ await fs.rmdir(agent.workingDirectory, { recursive: true });
908
+ logger.debug(`Cleaned up working directory for agent ${agent.id}`);
909
+ } catch (error) {
910
+ logger.warn(`Could not clean up directory for agent ${agent.id}`, error);
911
+ }
912
+ }
913
+ await this.gitWorkflowManager.coordinateMerges(Array.from(this.activeAgents.values()));
914
+ this.activeAgents.clear();
915
+ this.swarmState = {
916
+ id: uuidv4(),
917
+ status: "idle",
918
+ startTime: Date.now(),
919
+ activeTaskCount: 0,
920
+ completedTaskCount: 0,
921
+ coordination: {
922
+ events: [],
923
+ conflicts: [],
924
+ resolutions: []
925
+ },
926
+ performance: {
927
+ throughput: 0,
928
+ efficiency: 0,
929
+ coordination_overhead: 0
930
+ }
931
+ };
932
+ logger.info("Swarm cleanup completed successfully");
933
+ } catch (error) {
934
+ logger.error("Failed to cleanup completed swarm", error);
935
+ throw new SwarmCoordinationError("Cleanup failed", { swarmId: this.swarmState.id, error });
936
+ }
937
+ }
938
+ /**
939
+ * Force cleanup of a swarm (for emergency situations)
940
+ */
941
+ async forceCleanup() {
942
+ logger.warn("Force cleanup initiated");
943
+ try {
944
+ if (this.coordinationTimer) {
945
+ clearInterval(this.coordinationTimer);
946
+ this.coordinationTimer = void 0;
947
+ }
948
+ for (const agent of this.activeAgents.values()) {
949
+ agent.status = "stopped";
950
+ }
951
+ this.swarmState.status = "stopped";
952
+ await this.cleanupCompletedSwarms();
953
+ } catch (error) {
954
+ logger.error("Force cleanup failed", error);
955
+ }
956
+ }
957
+ /**
958
+ * Get swarm resource usage and cleanup recommendations
959
+ */
960
+ getResourceUsage() {
961
+ const workingDirs = Array.from(this.activeAgents.values()).map((a) => a.workingDirectory);
962
+ const memoryEstimate = this.activeAgents.size * 50;
963
+ const isStale = Date.now() - this.swarmState.startTime > 36e5;
964
+ const hasCompletedTasks = this.swarmState.completedTaskCount > 0 && this.swarmState.activeTaskCount === 0;
965
+ const recommendations = [];
966
+ let cleanupRecommended = false;
967
+ if (isStale) {
968
+ recommendations.push("Swarm has been running for over 1 hour - consider cleanup");
969
+ cleanupRecommended = true;
970
+ }
971
+ if (hasCompletedTasks) {
972
+ recommendations.push("All tasks completed - cleanup is recommended");
973
+ cleanupRecommended = true;
974
+ }
975
+ if (this.activeAgents.size > 5) {
976
+ recommendations.push("High agent count - monitor resource usage");
977
+ }
978
+ return {
979
+ activeAgents: this.activeAgents.size,
980
+ workingDirectories: workingDirs,
981
+ memoryEstimate,
982
+ cleanupRecommended,
983
+ recommendations
984
+ };
985
+ }
986
+ [Symbol.toStringTag] = "SwarmCoordinator";
987
+ }
988
+ const swarmCoordinator = new SwarmCoordinator();
989
+ export {
990
+ AgentExecutionError,
991
+ SwarmCoordinationError,
992
+ SwarmCoordinator,
993
+ TaskAllocationError,
994
+ swarmCoordinator
995
+ };
996
+ //# sourceMappingURL=swarm-coordinator.js.map