claude-flow-novice 2.6.0 → 2.9.0

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 (659) hide show
  1. package/.claude/agents/cfn-dev-team/coordinators/README.md +42 -0
  2. package/.claude/agents/cfn-dev-team/coordinators/cfn-v3-coordinator.md +440 -0
  3. package/.claude/agents/{product-owner-team → cfn-dev-team/coordinators}/cto-agent.md +154 -187
  4. package/.claude/agents/cfn-dev-team/coordinators/multi-sprint-coordinator.md +50 -0
  5. package/.claude/agents/{product-owner-team → cfn-dev-team/coordinators}/product-owner-agent.md +7 -40
  6. package/.claude/agents/{cfn-loop → cfn-dev-team/coordinators}/product-owner.md +73 -18
  7. package/.claude/agents/cfn-dev-team/developers/README.md +69 -0
  8. package/.claude/agents/cfn-dev-team/developers/backend-dev.md +77 -0
  9. package/.claude/agents/{core-agents → cfn-dev-team/developers}/coder.md +132 -27
  10. package/.claude/agents/cfn-dev-team/developers/react-frontend-engineer.md +121 -0
  11. package/.claude/agents/{frontend → cfn-dev-team/developers}/state-architect.md +1 -0
  12. package/.claude/agents/{frontend → cfn-dev-team/developers}/ui-designer.md +1 -0
  13. package/.claude/agents/cfn-dev-team/reviewers/README.md +58 -0
  14. package/.claude/agents/{analysis → cfn-dev-team/reviewers}/code-quality-validator.md +9 -18
  15. package/.claude/agents/{core-agents → cfn-dev-team/reviewers}/reviewer.md +62 -23
  16. package/.claude/agents/cfn-dev-team/testers/README.md +94 -0
  17. package/.claude/agents/{testing → cfn-dev-team/testers}/e2e/playwright-agent.md +2 -21
  18. package/.claude/agents/{testing → cfn-dev-team/testers}/interaction-tester.md +2 -21
  19. package/.claude/agents/{testing → cfn-dev-team/testers}/playwright-tester.md +1 -1
  20. package/.claude/agents/cfn-dev-team/testers/tester.md +139 -0
  21. package/.claude/agents/cfn-dev-team/testers/unit/tdd-london-swarm.md +49 -0
  22. package/.claude/agents/cfn-dev-team/testers/validation/production-validator.md +33 -0
  23. package/.claude/cfn-data/cfn-loop.db +0 -0
  24. package/.claude/cfn-data/cfn_loop_logs.db +0 -0
  25. package/.claude/commands/{CFN_COORDINATOR_PARAMETERS.md → cfn/CFN_COORDINATOR_PARAMETERS.md} +22 -22
  26. package/.claude/commands/{cfn-loop-epic.md → cfn/cfn-loop-epic.md} +6 -6
  27. package/.claude/commands/{cfn-loop-single.md → cfn/cfn-loop-single.md} +9 -9
  28. package/.claude/commands/{cfn-loop-sprints.md → cfn/cfn-loop-sprints.md} +1 -1
  29. package/.claude/commands/{cfn-loop.md → cfn/cfn-loop.md} +9 -9
  30. package/.claude/commands/cfn/cfn-mode.md +20 -0
  31. package/.claude/commands/{cfn-optimize-agents.md → cfn/cfn-optimize-agents.md} +1 -1
  32. package/.claude/commands/{context-curate.md → cfn/context-curate.md} +2 -2
  33. package/.claude/commands/{context-inject.md → cfn/context-inject.md} +3 -3
  34. package/.claude/commands/{context-reflect.md → cfn/context-reflect.md} +1 -1
  35. package/.claude/commands/{context-stats.md → cfn/context-stats.md} +1 -1
  36. package/.claude/commands/{list-agents-rebuild.md → cfn/list-agents-rebuild.md} +12 -12
  37. package/.claude/commands/cfn/write-plan.md +104 -0
  38. package/.claude/hooks/cfn-BACKUP_USAGE.md +243 -0
  39. package/.claude/hooks/cfn-post-edit-cfn-retrospective.sh +79 -0
  40. package/.claude/hooks/cfn-post-edit.sh +21 -0
  41. package/.claude/hooks/cfn-pre-edit-backup.sh +71 -0
  42. package/.claude/hooks/cfn-restore-from-backup.sh +37 -0
  43. package/.claude/skills/cfn-loop-orchestration/README.md +41 -0
  44. package/.claude/skills/cfn-redis-coordination/README.md +65 -0
  45. package/.claude/skills/cfn-webapp-testing/README.md +142 -0
  46. package/CFN-CLAUDE.md +776 -0
  47. package/README.md +598 -251
  48. package/dist/agents/agent-loader.js +146 -165
  49. package/dist/agents/agent-loader.js.map +1 -1
  50. package/dist/cli/agent-command.js +2 -0
  51. package/dist/cli/agent-command.js.map +1 -1
  52. package/dist/cli/agent-definition-parser.js +7 -0
  53. package/dist/cli/agent-definition-parser.js.map +1 -1
  54. package/dist/cli/agent-executor.js +145 -11
  55. package/dist/cli/agent-executor.js.map +1 -1
  56. package/dist/cli/agent-prompt-builder.js +81 -1
  57. package/dist/cli/agent-prompt-builder.js.map +1 -1
  58. package/dist/cli/agent-spawn.js +10 -1
  59. package/dist/cli/agent-spawn.js.map +1 -1
  60. package/dist/cli/anthropic-client.js +192 -13
  61. package/dist/cli/anthropic-client.js.map +1 -1
  62. package/dist/cli/cfn-context.js +150 -0
  63. package/dist/cli/cfn-context.js.map +1 -1
  64. package/dist/cli/cfn-fork.js +159 -0
  65. package/dist/cli/cfn-fork.js.map +1 -0
  66. package/dist/cli/cli-agent-context.js +8 -3
  67. package/dist/cli/cli-agent-context.js.map +1 -1
  68. package/dist/cli/conversation-fork.js +201 -0
  69. package/dist/cli/conversation-fork.js.map +1 -0
  70. package/dist/cli/index.js +4 -0
  71. package/dist/cli/index.js.map +1 -1
  72. package/dist/cli/init-command.js +20 -0
  73. package/dist/cli/init-command.js.map +1 -0
  74. package/dist/cli/tool-definitions.js +263 -0
  75. package/dist/cli/tool-definitions.js.map +1 -0
  76. package/dist/cli/tool-executor.js +247 -0
  77. package/dist/cli/tool-executor.js.map +1 -0
  78. package/dist/hello.js +8 -0
  79. package/dist/hello.js.map +1 -0
  80. package/package.json +26 -12
  81. package/scripts/README.md +68 -0
  82. package/scripts/cfn-intervention-example.sh +21 -0
  83. package/scripts/init-project.js +148 -0
  84. package/scripts/migrate-test-infrastructure.sh +40 -0
  85. package/scripts/restructure-cfn-namespace.sh +161 -0
  86. package/scripts/validate-test-migration.sh +49 -0
  87. package/scripts/verify-no-secrets.sh +55 -0
  88. package/.claude/SLASH-COMMANDS-READY.md +0 -53
  89. package/.claude/WORKING-SETUP.md +0 -67
  90. package/.claude/ace-system-overview.md +0 -524
  91. package/.claude/agent-principles/agent-template.md +0 -96
  92. package/.claude/agents/CLAUDE.md +0 -995
  93. package/.claude/agents/README-VALIDATION.md +0 -243
  94. package/.claude/agents/agent-principles/README.md +0 -226
  95. package/.claude/agents/agent-principles/agent-type-guidelines.md +0 -465
  96. package/.claude/agents/agent-principles/format-selection.md +0 -224
  97. package/.claude/agents/agent-principles/phase4-template-optimization.md +0 -494
  98. package/.claude/agents/agent-principles/prompt-engineering.md +0 -501
  99. package/.claude/agents/agent-principles/quality-metrics.md +0 -375
  100. package/.claude/agents/analysis/code-analyzer.md +0 -192
  101. package/.claude/agents/analysis/code-review/analyze-code-quality.md +0 -133
  102. package/.claude/agents/analysis/perf-analyzer.md +0 -230
  103. package/.claude/agents/architecture/system-architect.md +0 -161
  104. package/.claude/agents/architecture/system-architect.md.backup +0 -603
  105. package/.claude/agents/code-booster.md +0 -131
  106. package/.claude/agents/consensus/consensus-builder.md +0 -159
  107. package/.claude/agents/consensus/crdt-synchronizer.md +0 -192
  108. package/.claude/agents/consensus/performance-benchmarker.md +0 -101
  109. package/.claude/agents/consensus/quorum-manager.md +0 -168
  110. package/.claude/agents/consensus/raft-manager.md +0 -106
  111. package/.claude/agents/consensus/security-manager.md +0 -107
  112. package/.claude/agents/context/context-curator.md +0 -84
  113. package/.claude/agents/context/context-reflector.md +0 -81
  114. package/.claude/agents/context-curator.md +0 -167
  115. package/.claude/agents/context-reflector.md +0 -65
  116. package/.claude/agents/core-agents/analyst.md +0 -170
  117. package/.claude/agents/core-agents/architect.md +0 -200
  118. package/.claude/agents/core-agents/base-template-generator.md +0 -188
  119. package/.claude/agents/core-agents/cfn-loop-coordinator.md +0 -134
  120. package/.claude/agents/core-agents/code-quality-validator.md +0 -149
  121. package/.claude/agents/core-agents/context-curator.md +0 -452
  122. package/.claude/agents/core-agents/context-reflector.md +0 -273
  123. package/.claude/agents/core-agents/coordinator.md +0 -182
  124. package/.claude/agents/core-agents/cost-savings-cfn-loop-coordinator.md +0 -235
  125. package/.claude/agents/core-agents/cost-savings-coordinator.md +0 -167
  126. package/.claude/agents/core-agents/performance-benchmarker.md +0 -148
  127. package/.claude/agents/core-agents/planner.md +0 -174
  128. package/.claude/agents/core-agents/security-manager.md +0 -111
  129. package/.claude/agents/core-agents/tester.md +0 -170
  130. package/.claude/agents/custom/agent-builder.md +0 -637
  131. package/.claude/agents/development/backend/dev-backend-api.md +0 -139
  132. package/.claude/agents/development/backend-dev.md +0 -165
  133. package/.claude/agents/development/npm-package-specialist.md +0 -347
  134. package/.claude/agents/devops/devops-engineer.md +0 -148
  135. package/.claude/agents/documentation/api-docs/docs-api-openapi.md +0 -98
  136. package/.claude/agents/documentation/api-docs.md +0 -103
  137. package/.claude/agents/frontend/README.md +0 -640
  138. package/.claude/agents/frontend/interaction-tester.md +0 -139
  139. package/.claude/agents/frontend/react-frontend-engineer.md +0 -9
  140. package/.claude/agents/github/github-commit-agent.md +0 -118
  141. package/.claude/agents/goal/goal-planner.md +0 -183
  142. package/.claude/agents/personas/accessibility-advocate-persona.md +0 -107
  143. package/.claude/agents/planning-team/api-designer-persona.md +0 -147
  144. package/.claude/agents/planning-team/security-architect-persona.md +0 -190
  145. package/.claude/agents/planning-team/system-architect-persona.md +0 -190
  146. package/.claude/agents/product-owner-team/accessibility-advocate-persona.md +0 -161
  147. package/.claude/agents/product-owner-team/power-user-persona.md +0 -182
  148. package/.claude/agents/security/security-specialist-existing.md +0 -154
  149. package/.claude/agents/security/security-specialist.md +0 -185
  150. package/.claude/agents/sparc/architecture.md +0 -149
  151. package/.claude/agents/sparc/pseudocode.md +0 -159
  152. package/.claude/agents/sparc/refinement.md +0 -106
  153. package/.claude/agents/sparc/specification.md +0 -157
  154. package/.claude/agents/specialized/cli-agent-optimizer.md +0 -122
  155. package/.claude/agents/specialized/code-booster.md +0 -143
  156. package/.claude/agents/specialized/devops-engineer.md +0 -150
  157. package/.claude/agents/specialized/mobile/mobile-dev.md +0 -210
  158. package/.claude/agents/specialized/mobile/spec-mobile-react-native.md +0 -191
  159. package/.claude/agents/specialized/rust-developer.md +0 -166
  160. package/.claude/agents/specialized/rust-enterprise-developer.md +0 -144
  161. package/.claude/agents/specialized/rust-mvp-developer.md +0 -142
  162. package/.claude/agents/testing/production-validator.md +0 -179
  163. package/.claude/agents/testing/tdd-london-swarm.md +0 -209
  164. package/.claude/agents/testing/unit/tdd-london-swarm.md +0 -43
  165. package/.claude/agents/testing/validation/production-validator.md +0 -43
  166. package/.claude/agents/validate-agent.js +0 -841
  167. package/.claude/agents-ignore/cfn-coordinator-enterprise.md +0 -1303
  168. package/.claude/agents-ignore/cfn-coordinator-mvp.md +0 -942
  169. package/.claude/agents-ignore/cfn-coordinator-standard.md +0 -1062
  170. package/.claude/agents-ignore/deprecated-coordinators/adaptive-coordinator-enhanced.md +0 -145
  171. package/.claude/agents-ignore/deprecated-coordinators/adaptive-coordinator.md +0 -161
  172. package/.claude/agents-ignore/deprecated-coordinators/blocking-coordinator-example.md +0 -732
  173. package/.claude/agents-ignore/deprecated-coordinators/byzantine-coordinator.md +0 -94
  174. package/.claude/agents-ignore/deprecated-coordinators/cfn-coordinator-enterprise.md +0 -323
  175. package/.claude/agents-ignore/deprecated-coordinators/cfn-coordinator-mvp.md +0 -157
  176. package/.claude/agents-ignore/deprecated-coordinators/cfn-coordinator-standard.md +0 -229
  177. package/.claude/agents-ignore/deprecated-coordinators/cfn-coordinator-unified.md +0 -149
  178. package/.claude/agents-ignore/deprecated-coordinators/coordinator-hybrid.md +0 -231
  179. package/.claude/agents-ignore/deprecated-coordinators/gossip-coordinator.md +0 -165
  180. package/.claude/agents-ignore/deprecated-coordinators/hierarchical-coordinator.md +0 -91
  181. package/.claude/agents-ignore/deprecated-coordinators/mesh-coordinator.md +0 -131
  182. package/.claude/agents-ignore/deprecated-coordinators/task-coordinator.md +0 -105
  183. package/.claude/agents-ignore/deprecated-coordinators/test-coordinator.md +0 -141
  184. package/.claude/api-configs/config-current-zai-config.env +0 -62
  185. package/.claude/api-configs/config-test-zai-config.env +0 -62
  186. package/.claude/api-configs/env-backups/before-anthropic-20251020-025404.env +0 -62
  187. package/.claude/api-configs/env-backups/before-restore-20251020-025431.env +0 -62
  188. package/.claude/architecture/mesh-get-polling-design.md +0 -87
  189. package/.claude/architecture/mesh-get-polling-implementation.md +0 -89
  190. package/.claude/architecture/typescript-microservices.md +0 -50
  191. package/.claude/artifacts/reflection-merge-logs/cli-agent-spawning-v2.5.2-merge-report.md +0 -61
  192. package/.claude/cfn-loop-rules.md +0 -73
  193. package/.claude/cfn-mode-patterns.md +0 -571
  194. package/.claude/claude-md-backup-pre-skills.md +0 -15
  195. package/.claude/commands/agents/README.md +0 -10
  196. package/.claude/commands/agents/agent-capabilities.md +0 -21
  197. package/.claude/commands/agents/agent-coordination.md +0 -28
  198. package/.claude/commands/agents/agent-spawning.md +0 -28
  199. package/.claude/commands/agents/agent-types.md +0 -26
  200. package/.claude/commands/analysis/COMMAND_COMPLIANCE_REPORT.md +0 -54
  201. package/.claude/commands/analysis/README.md +0 -9
  202. package/.claude/commands/analysis/bottleneck-detect.md +0 -162
  203. package/.claude/commands/analysis/performance-bottlenecks.md +0 -59
  204. package/.claude/commands/analysis/performance-report.md +0 -25
  205. package/.claude/commands/analysis/token-efficiency.md +0 -45
  206. package/.claude/commands/analysis/token-usage.md +0 -25
  207. package/.claude/commands/automation/README.md +0 -9
  208. package/.claude/commands/automation/auto-agent.md +0 -122
  209. package/.claude/commands/automation/self-healing.md +0 -106
  210. package/.claude/commands/automation/session-memory.md +0 -90
  211. package/.claude/commands/automation/smart-agents.md +0 -73
  212. package/.claude/commands/automation/smart-spawn.md +0 -25
  213. package/.claude/commands/automation/workflow-select.md +0 -25
  214. package/.claude/commands/claude-md.js +0 -237
  215. package/.claude/commands/claude-soul.js +0 -28
  216. package/.claude/commands/cli-integration.js +0 -216
  217. package/.claude/commands/coordination/README.md +0 -9
  218. package/.claude/commands/coordination/agent-spawn.md +0 -25
  219. package/.claude/commands/coordination/coordination-system.md +0 -88
  220. package/.claude/commands/coordination/init.md +0 -44
  221. package/.claude/commands/coordination/orchestrate.md +0 -43
  222. package/.claude/commands/coordination/spawn.md +0 -45
  223. package/.claude/commands/coordination/swarm-init.md +0 -85
  224. package/.claude/commands/coordination/task-orchestrate.md +0 -25
  225. package/.claude/commands/github/README.md +0 -11
  226. package/.claude/commands/github/code-review-swarm.md +0 -514
  227. package/.claude/commands/github/code-review.md +0 -25
  228. package/.claude/commands/github/github-modes.md +0 -147
  229. package/.claude/commands/github/github-swarm.md +0 -121
  230. package/.claude/commands/github/issue-tracker.md +0 -292
  231. package/.claude/commands/github/issue-triage.md +0 -25
  232. package/.claude/commands/github/multi-repo-swarm.md +0 -519
  233. package/.claude/commands/github/pr-enhance.md +0 -26
  234. package/.claude/commands/github/pr-manager.md +0 -170
  235. package/.claude/commands/github/project-board-sync.md +0 -471
  236. package/.claude/commands/github/release-manager.md +0 -338
  237. package/.claude/commands/github/release-swarm.md +0 -544
  238. package/.claude/commands/github/repo-analyze.md +0 -25
  239. package/.claude/commands/github/repo-architect.md +0 -367
  240. package/.claude/commands/github/swarm-issue.md +0 -482
  241. package/.claude/commands/github/swarm-pr.md +0 -285
  242. package/.claude/commands/github/sync-coordinator.md +0 -301
  243. package/.claude/commands/github/workflow-automation.md +0 -442
  244. package/.claude/commands/github.js +0 -638
  245. package/.claude/commands/hive-mind/README.md +0 -17
  246. package/.claude/commands/hive-mind/hive-mind-consensus.md +0 -8
  247. package/.claude/commands/hive-mind/hive-mind-init.md +0 -18
  248. package/.claude/commands/hive-mind/hive-mind-memory.md +0 -8
  249. package/.claude/commands/hive-mind/hive-mind-metrics.md +0 -8
  250. package/.claude/commands/hive-mind/hive-mind-resume.md +0 -8
  251. package/.claude/commands/hive-mind/hive-mind-sessions.md +0 -8
  252. package/.claude/commands/hive-mind/hive-mind-spawn.md +0 -21
  253. package/.claude/commands/hive-mind/hive-mind-status.md +0 -8
  254. package/.claude/commands/hive-mind/hive-mind-stop.md +0 -8
  255. package/.claude/commands/hive-mind/hive-mind-wizard.md +0 -8
  256. package/.claude/commands/hive-mind/hive-mind.md +0 -27
  257. package/.claude/commands/hooks/README.md +0 -11
  258. package/.claude/commands/hooks/overview.md +0 -58
  259. package/.claude/commands/hooks/post-edit.md +0 -117
  260. package/.claude/commands/hooks/post-task.md +0 -112
  261. package/.claude/commands/hooks/pre-edit.md +0 -113
  262. package/.claude/commands/hooks/pre-task.md +0 -111
  263. package/.claude/commands/hooks/session-end.md +0 -118
  264. package/.claude/commands/hooks/session-start.md +0 -9
  265. package/.claude/commands/hooks/setup.md +0 -103
  266. package/.claude/commands/hooks.js +0 -651
  267. package/.claude/commands/index.js +0 -119
  268. package/.claude/commands/memory/README.md +0 -9
  269. package/.claude/commands/memory/memory-bank.md +0 -58
  270. package/.claude/commands/memory/memory-persist.md +0 -25
  271. package/.claude/commands/memory/memory-search.md +0 -25
  272. package/.claude/commands/memory/memory-usage.md +0 -25
  273. package/.claude/commands/memory/neural.md +0 -47
  274. package/.claude/commands/memory/usage.md +0 -46
  275. package/.claude/commands/monitoring/README.md +0 -9
  276. package/.claude/commands/monitoring/agent-metrics.md +0 -25
  277. package/.claude/commands/monitoring/agents.md +0 -44
  278. package/.claude/commands/monitoring/real-time-view.md +0 -25
  279. package/.claude/commands/monitoring/status.md +0 -46
  280. package/.claude/commands/monitoring/swarm-monitor.md +0 -25
  281. package/.claude/commands/neural.js +0 -572
  282. package/.claude/commands/optimization/README.md +0 -9
  283. package/.claude/commands/optimization/auto-topology.md +0 -62
  284. package/.claude/commands/optimization/cache-manage.md +0 -25
  285. package/.claude/commands/optimization/parallel-execute.md +0 -25
  286. package/.claude/commands/optimization/parallel-execution.md +0 -50
  287. package/.claude/commands/optimization/topology-optimize.md +0 -25
  288. package/.claude/commands/pair/README.md +0 -261
  289. package/.claude/commands/pair/commands.md +0 -546
  290. package/.claude/commands/pair/config.md +0 -510
  291. package/.claude/commands/pair/examples.md +0 -512
  292. package/.claude/commands/pair/modes.md +0 -348
  293. package/.claude/commands/pair/session.md +0 -407
  294. package/.claude/commands/pair/start.md +0 -209
  295. package/.claude/commands/parse-epic.js +0 -180
  296. package/.claude/commands/performance.js +0 -582
  297. package/.claude/commands/register-all-commands.js +0 -320
  298. package/.claude/commands/register-claude-md.js +0 -82
  299. package/.claude/commands/register-claude-soul.js +0 -80
  300. package/.claude/commands/sparc/analyzer.md +0 -52
  301. package/.claude/commands/sparc/architect.md +0 -53
  302. package/.claude/commands/sparc/batch-executor.md +0 -54
  303. package/.claude/commands/sparc/coder.md +0 -54
  304. package/.claude/commands/sparc/debugger.md +0 -54
  305. package/.claude/commands/sparc/designer.md +0 -53
  306. package/.claude/commands/sparc/documenter.md +0 -54
  307. package/.claude/commands/sparc/innovator.md +0 -54
  308. package/.claude/commands/sparc/memory-manager.md +0 -54
  309. package/.claude/commands/sparc/optimizer.md +0 -54
  310. package/.claude/commands/sparc/orchestrator.md +0 -132
  311. package/.claude/commands/sparc/researcher.md +0 -54
  312. package/.claude/commands/sparc/reviewer.md +0 -54
  313. package/.claude/commands/sparc/sparc-modes.md +0 -174
  314. package/.claude/commands/sparc/swarm-coordinator.md +0 -54
  315. package/.claude/commands/sparc/tdd.md +0 -54
  316. package/.claude/commands/sparc/tester.md +0 -54
  317. package/.claude/commands/sparc/workflow-manager.md +0 -54
  318. package/.claude/commands/sparc.js +0 -110
  319. package/.claude/commands/stream-chain/pipeline.md +0 -121
  320. package/.claude/commands/stream-chain/run.md +0 -70
  321. package/.claude/commands/swarm/README.md +0 -15
  322. package/.claude/commands/swarm/analysis.md +0 -95
  323. package/.claude/commands/swarm/development.md +0 -96
  324. package/.claude/commands/swarm/examples.md +0 -168
  325. package/.claude/commands/swarm/maintenance.md +0 -102
  326. package/.claude/commands/swarm/optimization.md +0 -117
  327. package/.claude/commands/swarm/research.md +0 -136
  328. package/.claude/commands/swarm/swarm-analysis.md +0 -8
  329. package/.claude/commands/swarm/swarm-background.md +0 -8
  330. package/.claude/commands/swarm/swarm-init.md +0 -19
  331. package/.claude/commands/swarm/swarm-modes.md +0 -8
  332. package/.claude/commands/swarm/swarm-monitor.md +0 -8
  333. package/.claude/commands/swarm/swarm-spawn.md +0 -19
  334. package/.claude/commands/swarm/swarm-status.md +0 -8
  335. package/.claude/commands/swarm/swarm-strategies.md +0 -8
  336. package/.claude/commands/swarm/swarm.md +0 -27
  337. package/.claude/commands/swarm/testing.md +0 -131
  338. package/.claude/commands/swarm.js +0 -423
  339. package/.claude/commands/testing/playwright-e2e.md +0 -288
  340. package/.claude/commands/training/README.md +0 -9
  341. package/.claude/commands/training/model-update.md +0 -25
  342. package/.claude/commands/training/neural-patterns.md +0 -74
  343. package/.claude/commands/training/neural-train.md +0 -25
  344. package/.claude/commands/training/pattern-learn.md +0 -25
  345. package/.claude/commands/training/specialization.md +0 -63
  346. package/.claude/commands/truth/start.md +0 -143
  347. package/.claude/commands/validate-commands.js +0 -223
  348. package/.claude/commands/verify/check.md +0 -50
  349. package/.claude/commands/verify/start.md +0 -128
  350. package/.claude/commands/workflow.js +0 -606
  351. package/.claude/commands/workflows/README.md +0 -9
  352. package/.claude/commands/workflows/development.md +0 -78
  353. package/.claude/commands/workflows/research.md +0 -63
  354. package/.claude/commands/workflows/workflow-create.md +0 -25
  355. package/.claude/commands/workflows/workflow-execute.md +0 -25
  356. package/.claude/commands/workflows/workflow-export.md +0 -25
  357. package/.claude/coordinator-feedback-pattern.md +0 -326
  358. package/.claude/coordinator-patterns.md +0 -126
  359. package/.claude/core/agent-manager.js +0 -80
  360. package/.claude/core/agent-manager.js.map +0 -1
  361. package/.claude/core/config.js +0 -1221
  362. package/.claude/core/config.js.map +0 -1
  363. package/.claude/core/event-bus.js +0 -136
  364. package/.claude/core/event-bus.js.map +0 -1
  365. package/.claude/core/index.js +0 -6
  366. package/.claude/core/index.js.map +0 -1
  367. package/.claude/core/json-persistence.js +0 -112
  368. package/.claude/core/json-persistence.js.map +0 -1
  369. package/.claude/core/logger.js +0 -245
  370. package/.claude/core/logger.js.map +0 -1
  371. package/.claude/core/orchestrator-fixed.js +0 -236
  372. package/.claude/core/orchestrator-fixed.js.map +0 -1
  373. package/.claude/core/orchestrator.js +0 -1136
  374. package/.claude/core/orchestrator.js.map +0 -1
  375. package/.claude/core/persistence.js +0 -185
  376. package/.claude/core/persistence.js.map +0 -1
  377. package/.claude/core/project-manager.js +0 -80
  378. package/.claude/core/project-manager.js.map +0 -1
  379. package/.claude/core/slash-command.js +0 -24
  380. package/.claude/core/version.js +0 -35
  381. package/.claude/core/version.js.map +0 -1
  382. package/.claude/helpers/checkpoint-manager.sh +0 -251
  383. package/.claude/helpers/github-safe.js +0 -106
  384. package/.claude/helpers/github-setup.sh +0 -28
  385. package/.claude/helpers/quick-start.sh +0 -19
  386. package/.claude/helpers/setup-mcp.sh +0 -18
  387. package/.claude/helpers/standard-checkpoint-hooks.sh +0 -179
  388. package/.claude/hooks.json +0 -21
  389. package/.claude/logs/sprint1-hybrid-routing-v2-decision.json +0 -18
  390. package/.claude/redis-agent-dependencies.md +0 -494
  391. package/.claude/root-claude-distribute/CLAUDE.md +0 -428
  392. package/.claude/settings.json +0 -129
  393. package/.claude/settings.local.json +0 -33
  394. package/.claude/skills/CFN-LOOP-VALIDATION.md +0 -202
  395. package/.claude/skills/REDIS-COORDINATION.md +0 -187
  396. package/.claude/skills/SKILL.md +0 -229
  397. package/.claude/skills/ace-system/SKILL.md +0 -364
  398. package/.claude/skills/ace-system/add-bullet.sh +0 -145
  399. package/.claude/skills/ace-system/invoke-context-curate.sh +0 -192
  400. package/.claude/skills/ace-system/invoke-context-inject.sh +0 -166
  401. package/.claude/skills/ace-system/invoke-context-query.sh +0 -127
  402. package/.claude/skills/ace-system/invoke-context-reflect.sh +0 -98
  403. package/.claude/skills/ace-system/invoke-context-stats.sh +0 -188
  404. package/.claude/skills/ace-system/log-merge.sh +0 -67
  405. package/.claude/skills/ace-system/query-reflections.sh +0 -35
  406. package/.claude/skills/ace-system/store-reflection.sh +0 -149
  407. package/.claude/skills/ace-system/test-ace-skill.sh +0 -312
  408. package/.claude/skills/ace-system/update-reflection.sh +0 -41
  409. package/.claude/skills/agent-execution/execute-agent.sh +0 -126
  410. package/.claude/skills/agent-spawning/SKILL.md +0 -135
  411. package/.claude/skills/agent-spawning/agent-selection-guide.md +0 -814
  412. package/.claude/skills/agent-spawning/check-dependencies.sh +0 -30
  413. package/.claude/skills/agent-spawning/spawn-agent.sh +0 -263
  414. package/.claude/skills/agent-spawning/spawn-templates.sh +0 -613
  415. package/.claude/skills/analytics/description-refinement-guide.md +0 -164
  416. package/.claude/skills/analytics/log-skill-invocation.js +0 -122
  417. package/.claude/skills/analytics/run-production-criteria-tests.sh +0 -126
  418. package/.claude/skills/analytics/skill-analytics-dashboard.js +0 -113
  419. package/.claude/skills/analytics/skill-invocation-hook.sh +0 -28
  420. package/.claude/skills/analytics/skill-invocations.sql +0 -58
  421. package/.claude/skills/analytics/test-corpus.json +0 -32
  422. package/.claude/skills/analytics/test-data-generator.js +0 -115
  423. package/.claude/skills/analytics/test-manual-override-rate.js +0 -285
  424. package/.claude/skills/analytics/validate-skill-selection.js +0 -188
  425. package/.claude/skills/cfn-loop-validation/SKILL.md +0 -263
  426. package/.claude/skills/cfn-loop-validation/check-dependencies.sh +0 -31
  427. package/.claude/skills/cfn-loop-validation/config.json +0 -161
  428. package/.claude/skills/cfn-loop-validation/consensus-calculator.js +0 -477
  429. package/.claude/skills/cfn-loop-validation/evidence-chain.sql +0 -163
  430. package/.claude/skills/cfn-loop-validation/examples/README.md +0 -453
  431. package/.claude/skills/cfn-loop-validation/examples/coordinator-full-cfn-loop.sh +0 -234
  432. package/.claude/skills/cfn-loop-validation/examples/coordinator-loop2-consensus.sh +0 -132
  433. package/.claude/skills/cfn-loop-validation/examples/coordinator-loop3-gate.sh +0 -115
  434. package/.claude/skills/cfn-loop-validation/examples/coordinator-redis-integration.sh +0 -186
  435. package/.claude/skills/cfn-loop-validation/orchestrate-cfn-loop.sh +0 -252
  436. package/.claude/skills/cfn-loop-validation/validate-iteration.sh +0 -134
  437. package/.claude/skills/cfn-loop-validation.sh +0 -70
  438. package/.claude/skills/config-management/SKILL.md +0 -34
  439. package/.claude/skills/config-management/check-dependencies.sh +0 -56
  440. package/.claude/skills/config-management/config.json +0 -32
  441. package/.claude/skills/config-management/manage-config.sh +0 -113
  442. package/.claude/skills/consensus-calculator.js +0 -45
  443. package/.claude/skills/event-bus/SKILL.md +0 -412
  444. package/.claude/skills/event-bus/config.json +0 -111
  445. package/.claude/skills/event-bus/eventbus-wrapper.cjs +0 -69
  446. package/.claude/skills/event-bus/invoke-event-publish.sh +0 -147
  447. package/.claude/skills/event-bus/invoke-event-subscribe.sh +0 -171
  448. package/.claude/skills/event-bus/invoke-lifecycle-track.sh +0 -201
  449. package/.claude/skills/event-bus/test-event-bus.sh +0 -280
  450. package/.claude/skills/evidence-chain.sql +0 -66
  451. package/.claude/skills/fleet-manager/SKILL.md +0 -412
  452. package/.claude/skills/fleet-manager/config.json +0 -60
  453. package/.claude/skills/fleet-manager/invoke-fleet-allocate.sh +0 -182
  454. package/.claude/skills/fleet-manager/invoke-fleet-balance.sh +0 -239
  455. package/.claude/skills/fleet-manager/invoke-fleet-metrics.sh +0 -193
  456. package/.claude/skills/fleet-manager/invoke-fleet-register.sh +0 -124
  457. package/.claude/skills/fleet-manager/test-fleet-manager.sh +0 -345
  458. package/.claude/skills/hook-pipeline/SKILL.md +0 -148
  459. package/.claude/skills/hook-pipeline/auto-resolve.sh +0 -66
  460. package/.claude/skills/hook-pipeline/check-dependencies.sh +0 -40
  461. package/.claude/skills/hook-pipeline/feedback-resolver.sh +0 -452
  462. package/.claude/skills/hook-pipeline/post-edit-handler.sh +0 -154
  463. package/.claude/skills/hook-pipeline/security-scan.json +0 -60
  464. package/.claude/skills/hook-pipeline/security-scanner.sh +0 -121
  465. package/.claude/skills/hook-pipeline/test-root-warning-resolution.sh +0 -148
  466. package/.claude/skills/hybrid-routing/SKILL.md +0 -46
  467. package/.claude/skills/hybrid-routing/check-dependencies.sh +0 -52
  468. package/.claude/skills/hybrid-routing/config.json +0 -26
  469. package/.claude/skills/hybrid-routing/spawn-worker.sh +0 -44
  470. package/.claude/skills/process-lifecycle/SKILL.md +0 -39
  471. package/.claude/skills/process-lifecycle/check-dependencies.sh +0 -58
  472. package/.claude/skills/process-lifecycle/config.json +0 -39
  473. package/.claude/skills/process-lifecycle/process-manager.sh +0 -144
  474. package/.claude/skills/redis-coordination/AGENT_LOGGING.md +0 -280
  475. package/.claude/skills/redis-coordination/BZPOPMIN_FIX_SUMMARY.md +0 -209
  476. package/.claude/skills/redis-coordination/HEARTBEAT.md +0 -57
  477. package/.claude/skills/redis-coordination/HEARTBEAT_MONITORING.md +0 -267
  478. package/.claude/skills/redis-coordination/README.md +0 -64
  479. package/.claude/skills/redis-coordination/SECURITY_REVIEW.md +0 -25
  480. package/.claude/skills/redis-coordination/SHUTDOWN_HANDLING.md +0 -164
  481. package/.claude/skills/redis-coordination/SKILL.md +0 -118
  482. package/.claude/skills/redis-coordination/agent-log.sh +0 -124
  483. package/.claude/skills/redis-coordination/agent-recovery.sh +0 -75
  484. package/.claude/skills/redis-coordination/cancel-swarm.sh +0 -221
  485. package/.claude/skills/redis-coordination/cfn-loop-relaunch.sh +0 -29
  486. package/.claude/skills/redis-coordination/check-dependencies.sh +0 -32
  487. package/.claude/skills/redis-coordination/complete-swarm.sh +0 -75
  488. package/.claude/skills/redis-coordination/config.json +0 -61
  489. package/.claude/skills/redis-coordination/examples/README.md +0 -73
  490. package/.claude/skills/redis-coordination/examples/grafana-dashboard.json +0 -352
  491. package/.claude/skills/redis-coordination/examples/hierarchical-pattern.sh +0 -127
  492. package/.claude/skills/redis-coordination/examples/mesh-pattern.sh +0 -171
  493. package/.claude/skills/redis-coordination/examples/timeout-handling.sh +0 -227
  494. package/.claude/skills/redis-coordination/examples/waiting-mode-pattern.sh +0 -239
  495. package/.claude/skills/redis-coordination/get-agent-timeout.sh +0 -177
  496. package/.claude/skills/redis-coordination/heartbeat-functions.sh +0 -137
  497. package/.claude/skills/redis-coordination/heartbeat-protocol.md +0 -106
  498. package/.claude/skills/redis-coordination/heartbeat.sh +0 -126
  499. package/.claude/skills/redis-coordination/init-swarm.sh +0 -148
  500. package/.claude/skills/redis-coordination/invoke-redis-pattern.sh +0 -220
  501. package/.claude/skills/redis-coordination/invoke-waiting-mode.sh +0 -417
  502. package/.claude/skills/redis-coordination/list-active-swarms.sh +0 -147
  503. package/.claude/skills/redis-coordination/metrics-export.sh +0 -674
  504. package/.claude/skills/redis-coordination/metrics-schema.json +0 -66
  505. package/.claude/skills/redis-coordination/metrics-storage.md +0 -31
  506. package/.claude/skills/redis-coordination/monitor-heartbeats.sh +0 -101
  507. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh +0 -993
  508. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-1760949407 +0 -933
  509. package/.claude/skills/redis-coordination/phase4-wake-queue-test-report.md +0 -82
  510. package/.claude/skills/redis-coordination/priority-wake-mechanism.md +0 -75
  511. package/.claude/skills/redis-coordination/priority_wake.py +0 -134
  512. package/.claude/skills/redis-coordination/query-dlq.sh +0 -162
  513. package/.claude/skills/redis-coordination/redis-pattern.sh +0 -619
  514. package/.claude/skills/redis-coordination/send-heartbeat.sh +0 -73
  515. package/.claude/skills/redis-coordination/store-epic-context.sh +0 -123
  516. package/.claude/skills/redis-coordination/test-bzpopmin-fix.sh +0 -274
  517. package/.claude/skills/redis-coordination/test-cancel-swarm.sh +0 -276
  518. package/.claude/skills/redis-coordination/test-dlq.sh +0 -129
  519. package/.claude/skills/redis-coordination/test-iteration-feedback.sh +0 -320
  520. package/.claude/skills/redis-coordination/test-orchestrator.sh +0 -224
  521. package/.claude/skills/redis-coordination/test-priority-wake-phase4-unix.sh +0 -148
  522. package/.claude/skills/redis-coordination/test-priority-wake-phase4.sh +0 -163
  523. package/.claude/skills/redis-coordination/test-priority-wake.sh +0 -138
  524. package/.claude/skills/redis-coordination/test-quick-fix.sh +0 -81
  525. package/.claude/skills/redis-coordination/test-quorum-absolute.sh +0 -45
  526. package/.claude/skills/redis-coordination/test-quorum-fallback.sh +0 -68
  527. package/.claude/skills/redis-coordination/test-quorum-percentage.sh +0 -56
  528. package/.claude/skills/redis-coordination/test-quorum-with-retry.sh +0 -81
  529. package/.claude/skills/redis-coordination/test-quorum.sh +0 -57
  530. package/.claude/skills/redis-coordination/test-shutdown-handling.sh +0 -187
  531. package/.claude/skills/redis-coordination/test-shutdown.sh +0 -160
  532. package/.claude/skills/redis-coordination/test-utils-unix.sh +0 -97
  533. package/.claude/skills/redis-coordination/test-utils.sh +0 -97
  534. package/.claude/skills/redis-coordination/test-waiting-mode.sh +0 -59
  535. package/.claude/skills/redis-coordination/tests/dlq-functionality-test.sh +0 -102
  536. package/.claude/skills/redis-coordination/tests/edge-cases-test.sh +0 -99
  537. package/.claude/skills/redis-coordination/tests/integration-test.sh +0 -170
  538. package/.claude/skills/redis-coordination/tests/retry-mechanism-test.sh +0 -82
  539. package/.claude/skills/redis-coordination/tests/run-test-suite.sh +0 -92
  540. package/.claude/skills/redis-coordination/tests/test-heartbeat-monitoring.sh +0 -418
  541. package/.claude/skills/redis-coordination/tests/test-heartbeat-simple.sh +0 -124
  542. package/.claude/skills/redis-coordination/tests/test-utils.sh +0 -122
  543. package/.claude/skills/skill-builder/SKILL.md +0 -910
  544. package/.claude/skills/sqlite-memory/IMPLEMENTATION_REPORT.md +0 -393
  545. package/.claude/skills/sqlite-memory/QUICK_REFERENCE.md +0 -204
  546. package/.claude/skills/sqlite-memory/SKILL.md +0 -415
  547. package/.claude/skills/sqlite-memory/acl-queries.sql +0 -452
  548. package/.claude/skills/sqlite-memory/check-dependencies.sh +0 -36
  549. package/.claude/skills/sqlite-memory/config.json +0 -45
  550. package/.claude/skills/sqlite-memory/memory-cli.sh +0 -88
  551. package/.claude/skills/sqlite-memory/test-state-persistence.js +0 -187
  552. package/.claude/skills/sqlite-memory/ttl-cleanup.sh +0 -274
  553. package/.claude/skills/test-execution/SKILL.md +0 -128
  554. package/.claude/skills/test-execution/check-dependencies.sh +0 -36
  555. package/.claude/skills/test-execution/test-cache-reader.sh +0 -134
  556. package/.claude/skills/test-execution/test-concurrent-conflicts.sh +0 -115
  557. package/.claude/skills/test-execution/test-coordinator-pattern.sh +0 -109
  558. package/.claude/skills/test-execution-coordinator-pattern.md +0 -228
  559. package/.claude/skills/transparency-middleware/Cargo.toml +0 -18
  560. package/.claude/skills/transparency-middleware/SECURITY.md +0 -41
  561. package/.claude/skills/transparency-middleware/SKILL.md +0 -91
  562. package/.claude/skills/transparency-middleware/TEST_RESULTS.md +0 -174
  563. package/.claude/skills/transparency-middleware/config.json +0 -31
  564. package/.claude/skills/transparency-middleware/examples/basic-usage.ts +0 -39
  565. package/.claude/skills/transparency-middleware/examples/batch-processing.ts +0 -52
  566. package/.claude/skills/transparency-middleware/examples/custom-filtering.ts +0 -61
  567. package/.claude/skills/transparency-middleware/invoke-transparency-filter.sh +0 -98
  568. package/.claude/skills/transparency-middleware/invoke-transparency-init.sh +0 -224
  569. package/.claude/skills/transparency-middleware/invoke-transparency-level.sh +0 -333
  570. package/.claude/skills/transparency-middleware/invoke-transparency-metrics.sh +0 -345
  571. package/.claude/skills/transparency-middleware/invoke-transparency-observe.sh +0 -140
  572. package/.claude/skills/transparency-middleware/invoke-transparency-stop.sh +0 -235
  573. package/.claude/skills/transparency-middleware/memory_query.rs +0 -85
  574. package/.claude/skills/transparency-middleware/memory_repository.rs +0 -140
  575. package/.claude/skills/transparency-middleware/memory_schema.rs +0 -64
  576. package/.claude/skills/transparency-middleware/middleware-config.sh +0 -29
  577. package/.claude/skills/transparency-middleware/performance-benchmark.sh +0 -79
  578. package/.claude/skills/transparency-middleware/test-e2e.sh +0 -406
  579. package/.claude/skills/transparency-middleware/test-integration.sh +0 -162
  580. package/.claude/skills/transparency-middleware/test-transparency-skill.sh +0 -368
  581. package/.claude/skills/transparency-middleware/test-transparency-skill.sh.unix +0 -126
  582. package/.claude/skills/transparency-middleware/tests/input-validation.sh +0 -93
  583. package/.claude/skills/transparency-middleware/wrap-agent.sh +0 -132
  584. package/.claude/skills/web-portal/DESIGN.md +0 -117
  585. package/.claude/skills/web-portal/SKILL.md +0 -679
  586. package/.claude/skills/web-portal/invoke-portal-agents.sh +0 -129
  587. package/.claude/skills/web-portal/invoke-portal-dashboard.sh +0 -85
  588. package/.claude/skills/web-portal/invoke-portal-events.sh +0 -125
  589. package/.claude/skills/web-portal/invoke-portal-metrics.sh +0 -112
  590. package/.claude/skills/web-portal/invoke-portal-start.sh +0 -135
  591. package/.claude/skills/web-portal/invoke-portal-stop.sh +0 -121
  592. package/.claude/skills/web-portal/test-web-portal-skill.sh +0 -51
  593. package/.claude/skills/web-portal/validate-deployment.sh +0 -85
  594. package/.claude/slash-commands.json +0 -92
  595. package/.claude/spawn-pattern-examples.md +0 -500
  596. package/.claude/sprint-configs/cfn-naming-standardization.json +0 -729
  597. package/.claude/sprint-reports/sprint-1.4-self-correction-monitoring.json +0 -64
  598. package/.claude/swarm-memory.db +0 -0
  599. package/.claude/templates/agent-optimization-plan.md +0 -439
  600. package/.claude/templates/bulk-optimization-strategy.md +0 -367
  601. package/.claude/templates/cfn-loop-mechanics.md +0 -80
  602. package/.claude/templates/coordinator-patterns.md +0 -75
  603. package/.claude/templates/memory-operations.md +0 -200
  604. package/.claude/templates/post-edit-validation.md +0 -109
  605. package/.claude/templates/redis-coordination.md +0 -140
  606. package/.claude/templates/remaining-agent-analysis.md +0 -121
  607. package/.claude/templates/swarm-coordination.md +0 -103
  608. package/.claude/templates/team-dynamics.md +0 -82
  609. package/CLAUDE.md +0 -502
  610. package/dist/cli/cli-agent-context.test.js +0 -451
  611. package/dist/cli/cli-agent-context.test.js.map +0 -1
  612. package/dist/coordination/fleet-manager.test.js +0 -141
  613. package/dist/coordination/fleet-manager.test.js.map +0 -1
  614. package/dist/middleware/transparency-middleware.test.js +0 -184
  615. package/dist/middleware/transparency-middleware.test.js.map +0 -1
  616. package/readme/CLAUDE.md +0 -429
  617. /package/.claude/agents/{core-agents → cfn-dev-team/developers}/researcher.md +0 -0
  618. /package/.claude/commands/{README.md → cfn/README.md} +0 -0
  619. /package/.claude/commands/{auto-compact.md → cfn/auto-compact.md} +0 -0
  620. /package/.claude/commands/{cfn-claude-sync.md → cfn/cfn-claude-sync.md} +0 -0
  621. /package/.claude/commands/{cfn-loop-document.md → cfn/cfn-loop-document.md} +0 -0
  622. /package/.claude/commands/{claude-md.md → cfn/claude-md.md} +0 -0
  623. /package/.claude/commands/{claude-soul.md → cfn/claude-soul.md} +0 -0
  624. /package/.claude/commands/{context-query.md → cfn/context-query.md} +0 -0
  625. /package/.claude/commands/{cost-savings-off.md → cfn/cost-savings-off.md} +0 -0
  626. /package/.claude/commands/{cost-savings-on.md → cfn/cost-savings-on.md} +0 -0
  627. /package/.claude/commands/{cost-savings-status.md → cfn/cost-savings-status.md} +0 -0
  628. /package/.claude/commands/{custom-routing-activate.md → cfn/custom-routing-activate.md} +0 -0
  629. /package/.claude/commands/{custom-routing-deactivate.md → cfn/custom-routing-deactivate.md} +0 -0
  630. /package/.claude/commands/{dependency-recommendations.md → cfn/dependency-recommendations.md} +0 -0
  631. /package/.claude/commands/{fullstack.md → cfn/fullstack.md} +0 -0
  632. /package/.claude/commands/{github-commit.md → cfn/github-commit.md} +0 -0
  633. /package/.claude/commands/{github.md → cfn/github.md} +0 -0
  634. /package/.claude/commands/{hello-world-tests.md → cfn/hello-world-tests.md} +0 -0
  635. /package/.claude/commands/{hooks.md → cfn/hooks.md} +0 -0
  636. /package/.claude/commands/{launch-web-dashboard.md → cfn/launch-web-dashboard.md} +0 -0
  637. /package/.claude/commands/{metrics-summary.md → cfn/metrics-summary.md} +0 -0
  638. /package/.claude/commands/{neural.md → cfn/neural.md} +0 -0
  639. /package/.claude/commands/{parse-epic.md → cfn/parse-epic.md} +0 -0
  640. /package/.claude/commands/{performance.md → cfn/performance.md} +0 -0
  641. /package/.claude/commands/{sparc.md → cfn/sparc.md} +0 -0
  642. /package/.claude/commands/{suggest-improvements.md → cfn/suggest-improvements.md} +0 -0
  643. /package/.claude/commands/{suggest-templates.md → cfn/suggest-templates.md} +0 -0
  644. /package/.claude/commands/{swarm.md → cfn/swarm.md} +0 -0
  645. /package/.claude/commands/{switch-api.md → cfn/switch-api.md} +0 -0
  646. /package/.claude/commands/{workflow.md → cfn/workflow.md} +0 -0
  647. /package/.claude/hooks/{invoke-post-edit.sh → cfn-invoke-post-edit.sh} +0 -0
  648. /package/.claude/hooks/{post-edit.config.json → cfn-post-edit.config.json} +0 -0
  649. /package/.claude/skills/{agent-spawning → cfn-agent-spawning}/README.md +0 -0
  650. /package/.claude/skills/{analytics → cfn-analytics}/README.md +0 -0
  651. /package/.claude/skills/{config-management → cfn-config-management}/README.md +0 -0
  652. /package/.claude/skills/{event-bus → cfn-event-bus}/README.md +0 -0
  653. /package/.claude/skills/{fleet-manager → cfn-fleet-manager}/README.md +0 -0
  654. /package/.claude/skills/{hook-pipeline → cfn-hook-pipeline}/README.md +0 -0
  655. /package/.claude/skills/{hybrid-routing → cfn-hybrid-routing}/README.md +0 -0
  656. /package/.claude/skills/{process-lifecycle → cfn-process-lifecycle}/README.md +0 -0
  657. /package/.claude/skills/{sqlite-memory → cfn-sqlite-memory}/README.md +0 -0
  658. /package/.claude/skills/{test-execution → cfn-test-execution}/README.md +0 -0
  659. /package/.claude/skills/{transparency-middleware → cfn-transparency-middleware}/README.md +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/agent-spawn.ts"],"sourcesContent":["#!/usr/bin/env node\r\n/**\r\n * Agent Spawning CLI - Direct agent process spawning\r\n *\r\n * Usage:\r\n * npx cfn-spawn agent <type> [options]\r\n * npx cfn-spawn <type> [options] (agent is implied)\r\n *\r\n * Examples:\r\n * npx cfn-spawn agent researcher --task-id task-123 --iteration 1\r\n * npx cfn-spawn researcher --task-id task-123 --iteration 1\r\n */\r\n\r\nimport { spawn } from 'child_process';\r\nimport { resolve } from 'path';\r\n\r\ninterface AgentSpawnOptions {\r\n agentType: string;\r\n taskId?: string;\r\n iteration?: number;\r\n context?: string;\r\n mode?: string;\r\n priority?: number;\r\n parentTaskId?: string;\r\n}\r\n\r\n/**\r\n * Parse command line arguments for agent spawning\r\n */\r\nfunction parseAgentArgs(args: string[]): AgentSpawnOptions | null {\r\n // Handle both \"agent <type>\" and \"<type>\" patterns\r\n let agentType: string;\r\n let optionArgs: string[];\r\n\r\n if (args[0] === 'agent') {\r\n agentType = args[1];\r\n optionArgs = args.slice(2);\r\n } else {\r\n agentType = args[0];\r\n optionArgs = args.slice(1);\r\n }\r\n\r\n if (!agentType) {\r\n console.error('Error: Agent type is required');\r\n console.error('Usage: cfn-spawn agent <type> [options]');\r\n return null;\r\n }\r\n\r\n const options: AgentSpawnOptions = { agentType };\r\n\r\n // Parse optional parameters\r\n for (let i = 0; i < optionArgs.length; i += 2) {\r\n const key = optionArgs[i];\r\n const value = optionArgs[i + 1];\r\n\r\n switch (key) {\r\n case '--task-id':\r\n options.taskId = value;\r\n break;\r\n case '--iteration':\r\n options.iteration = parseInt(value, 10);\r\n break;\r\n case '--context':\r\n options.context = value;\r\n break;\r\n case '--mode':\r\n options.mode = value;\r\n break;\r\n case '--priority':\r\n options.priority = parseInt(value, 10);\r\n break;\r\n case '--parent-task':\r\n case '--parent-task-id':\r\n options.parentTaskId = value;\r\n break;\r\n default:\r\n console.warn(`Unknown option: ${key}`);\r\n }\r\n }\r\n\r\n return options;\r\n}\r\n\r\n/**\r\n * Spawn an agent process using npx claude-flow-novice agent\r\n *\r\n * This is a wrapper/alias for the existing claude-flow-novice agent spawning mechanism\r\n * Provides the cfn-spawn naming pattern while delegating to the working implementation\r\n */\r\nasync function spawnAgent(options: AgentSpawnOptions): Promise<void> {\r\n const { agentType, taskId, iteration, context, mode, priority, parentTaskId } = options;\r\n\r\n console.log(`[cfn-spawn] Spawning agent: ${agentType}`);\r\n if (taskId) console.log(`[cfn-spawn] Task ID: ${taskId}`);\r\n if (iteration) console.log(`[cfn-spawn] Iteration: ${iteration}`);\r\n if (context) console.log(`[cfn-spawn] Context: ${context}`);\r\n if (mode) console.log(`[cfn-spawn] Mode: ${mode}`);\r\n\r\n // Build command arguments for npx claude-flow-novice agent\r\n const claudeArgs = ['claude-flow-novice', 'agent', agentType];\r\n\r\n // Add optional parameters\r\n if (taskId) {\r\n claudeArgs.push('--task-id', taskId);\r\n }\r\n if (iteration) {\r\n claudeArgs.push('--iteration', iteration.toString());\r\n }\r\n if (context) {\r\n claudeArgs.push('--context', context);\r\n }\r\n if (mode) {\r\n claudeArgs.push('--mode', mode);\r\n }\r\n if (priority) {\r\n claudeArgs.push('--priority', priority.toString());\r\n }\r\n if (parentTaskId) {\r\n claudeArgs.push('--parent-task-id', parentTaskId);\r\n }\r\n\r\n // Fetch epic context from Redis if available\r\n let epicContext = '';\r\n let phaseContext = '';\r\n let successCriteria = '';\r\n\r\n if (taskId) {\r\n try {\r\n const { execSync } = await import('child_process');\r\n\r\n // Try to read epic-level context from Redis\r\n try {\r\n epicContext = execSync(`redis-cli get \"swarm:${taskId}:epic-context\"`, { encoding: 'utf8' }).trim();\r\n if (epicContext === '(nil)') epicContext = '';\r\n } catch (e) {\r\n // Redis not available or key doesn't exist\r\n }\r\n\r\n // Try to read phase-specific context\r\n try {\r\n phaseContext = execSync(`redis-cli get \"swarm:${taskId}:phase-context\"`, { encoding: 'utf8' }).trim();\r\n if (phaseContext === '(nil)') phaseContext = '';\r\n } catch (e) {\r\n // Redis not available or key doesn't exist\r\n }\r\n\r\n // Try to read success criteria\r\n try {\r\n successCriteria = execSync(`redis-cli get \"swarm:${taskId}:success-criteria\"`, { encoding: 'utf8' }).trim();\r\n if (successCriteria === '(nil)') successCriteria = '';\r\n } catch (e) {\r\n // Redis not available or key doesn't exist\r\n }\r\n\r\n if (epicContext) {\r\n console.log(`[cfn-spawn] Epic context loaded from Redis`);\r\n }\r\n } catch (err) {\r\n console.warn(`[cfn-spawn] Could not load epic context from Redis:`, err);\r\n }\r\n }\r\n\r\n // Add environment variables for agent context\r\n const env = {\r\n ...process.env,\r\n AGENT_TYPE: agentType,\r\n TASK_ID: taskId || '',\r\n ITERATION: iteration?.toString() || '1',\r\n CONTEXT: context || '',\r\n MODE: mode || 'cli',\r\n PRIORITY: priority?.toString() || '5',\r\n PARENT_TASK_ID: parentTaskId || '',\r\n // Epic-level context from Redis\r\n EPIC_CONTEXT: epicContext,\r\n PHASE_CONTEXT: phaseContext,\r\n SUCCESS_CRITERIA: successCriteria\r\n };\r\n\r\n console.log(`[cfn-spawn] Executing: npx ${claudeArgs.join(' ')}`);\r\n\r\n // Spawn the claude-flow-novice agent process\r\n const agentProcess = spawn('npx', claudeArgs, {\r\n stdio: 'inherit',\r\n env,\r\n cwd: process.cwd()\r\n });\r\n\r\n // Handle process exit\r\n agentProcess.on('exit', (code, signal) => {\r\n if (code === 0) {\r\n console.log(`[cfn-spawn] Agent ${agentType} completed successfully`);\r\n } else {\r\n console.error(`[cfn-spawn] Agent ${agentType} exited with code ${code}, signal ${signal}`);\r\n }\r\n process.exit(code || 0);\r\n });\r\n\r\n // Handle process errors\r\n agentProcess.on('error', (err) => {\r\n console.error(`[cfn-spawn] Failed to spawn agent ${agentType}:`, err.message);\r\n process.exit(1);\r\n });\r\n\r\n // Cleanup on parent exit\r\n process.on('SIGINT', () => {\r\n console.log('\\n[cfn-spawn] Received SIGINT, terminating agent...');\r\n agentProcess.kill('SIGINT');\r\n });\r\n\r\n process.on('SIGTERM', () => {\r\n console.log('\\n[cfn-spawn] Received SIGTERM, terminating agent...');\r\n agentProcess.kill('SIGTERM');\r\n });\r\n}\r\n\r\n/**\r\n * Build task description for the agent\r\n */\r\nfunction buildTaskDescription(\r\n agentType: string,\r\n taskId?: string,\r\n iteration?: number,\r\n context?: string\r\n): string {\r\n let desc = `Execute task as ${agentType} agent`;\r\n\r\n if (taskId) desc += ` for task ${taskId}`;\r\n if (iteration) desc += ` (iteration ${iteration})`;\r\n if (context) desc += `: ${context}`;\r\n\r\n return desc;\r\n}\r\n\r\n/**\r\n * Main CLI entry point\r\n */\r\nexport async function main(args: string[] = process.argv.slice(2)): Promise<void> {\r\n // Show help if requested\r\n if (args.includes('--help') || args.includes('-h')) {\r\n console.log(`\r\ncfn-spawn - Claude Flow Novice Agent Spawner\r\n\r\nUsage:\r\n cfn-spawn agent <type> [options]\r\n cfn-spawn <type> [options] (agent is implied)\r\n\r\nOptions:\r\n --task-id <id> Task identifier\r\n --iteration <n> Iteration number\r\n --context <text> Context description\r\n --mode <mode> Execution mode (cli, api, hybrid)\r\n --priority <1-10> Task priority\r\n --parent-task-id <id> Parent task identifier\r\n\r\nExamples:\r\n cfn-spawn agent researcher --task-id task-123 --iteration 1\r\n cfn-spawn coder --task-id auth-impl --context \"Implement JWT auth\"\r\n cfn-spawn reviewer --task-id auth-impl --iteration 2 --mode cli\r\n `);\r\n return;\r\n }\r\n\r\n // Parse arguments\r\n const options = parseAgentArgs(args);\r\n if (!options) {\r\n process.exit(1);\r\n }\r\n\r\n // Spawn the agent\r\n await spawnAgent(options);\r\n}\r\n\r\n// Run if called directly\r\n// ES module check - compare import.meta.url with the executed file\r\nconst isMainModule = import.meta.url.endsWith(process.argv[1]?.replace(/\\\\/g, '/') || '');\r\nif (isMainModule) {\r\n main().catch((err) => {\r\n console.error('[cfn-spawn] Fatal error:', err);\r\n process.exit(1);\r\n });\r\n}\r\n"],"names":["spawn","parseAgentArgs","args","agentType","optionArgs","slice","console","error","options","i","length","key","value","taskId","iteration","parseInt","context","mode","priority","parentTaskId","warn","spawnAgent","log","claudeArgs","push","toString","epicContext","phaseContext","successCriteria","execSync","encoding","trim","e","err","env","process","AGENT_TYPE","TASK_ID","ITERATION","CONTEXT","MODE","PRIORITY","PARENT_TASK_ID","EPIC_CONTEXT","PHASE_CONTEXT","SUCCESS_CRITERIA","join","agentProcess","stdio","cwd","on","code","signal","exit","message","kill","buildTaskDescription","desc","main","argv","includes","isMainModule","url","endsWith","replace","catch"],"mappings":";AACA;;;;;;;;;;CAUC,GAED,SAASA,KAAK,QAAQ,gBAA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CAAC5B,QAAQwB,IAAI,CAAC,EAAE,EAAEK,QAAQ,OAAO,QAAQ;AACtF,IAAIH,cAAc;IAChBH,OAAOO,KAAK,CAAC,CAAChC;QACZ3B,QAAQC,KAAK,CAAC,4BAA4B0B;QAC1CE,QAAQkB,IAAI,CAAC;IACf;AACF"}
1
+ {"version":3,"sources":["../../src/cli/agent-spawn.ts"],"sourcesContent":["#!/usr/bin/env node\r\n/**\r\n * Agent Spawning CLI - Direct agent process spawning\r\n *\r\n * Usage:\r\n * npx cfn-spawn agent <type> [options]\r\n * npx cfn-spawn <type> [options] (agent is implied)\r\n *\r\n * Examples:\r\n * npx cfn-spawn agent researcher --task-id task-123 --iteration 1\r\n * npx cfn-spawn researcher --task-id task-123 --iteration 1\r\n */\r\n\r\nimport { spawn } from 'child_process';\r\nimport { resolve } from 'path';\r\n\r\ninterface AgentSpawnOptions {\r\n agentType: string;\r\n agentId?: string;\r\n taskId?: string;\r\n iteration?: number;\r\n context?: string;\r\n mode?: string;\r\n priority?: number;\r\n parentTaskId?: string;\r\n}\r\n\r\n/**\r\n * Parse command line arguments for agent spawning\r\n */\r\nfunction parseAgentArgs(args: string[]): AgentSpawnOptions | null {\r\n // Handle both \"agent <type>\" and \"<type>\" patterns\r\n let agentType: string;\r\n let optionArgs: string[];\r\n\r\n if (args[0] === 'agent') {\r\n agentType = args[1];\r\n optionArgs = args.slice(2);\r\n } else {\r\n agentType = args[0];\r\n optionArgs = args.slice(1);\r\n }\r\n\r\n if (!agentType) {\r\n console.error('Error: Agent type is required');\r\n console.error('Usage: cfn-spawn agent <type> [options]');\r\n return null;\r\n }\r\n\r\n const options: AgentSpawnOptions = { agentType };\r\n\r\n // Parse optional parameters\r\n for (let i = 0; i < optionArgs.length; i += 2) {\r\n const key = optionArgs[i];\r\n const value = optionArgs[i + 1];\r\n\r\n switch (key) {\r\n case '--agent-id':\r\n options.agentId = value;\r\n break;\r\n case '--task-id':\r\n options.taskId = value;\r\n break;\r\n case '--iteration':\r\n options.iteration = parseInt(value, 10);\r\n break;\r\n case '--context':\r\n options.context = value;\r\n break;\r\n case '--mode':\r\n options.mode = value;\r\n break;\r\n case '--priority':\r\n options.priority = parseInt(value, 10);\r\n break;\r\n case '--parent-task':\r\n case '--parent-task-id':\r\n options.parentTaskId = value;\r\n break;\r\n default:\r\n console.warn(`Unknown option: ${key}`);\r\n }\r\n }\r\n\r\n return options;\r\n}\r\n\r\n/**\r\n * Spawn an agent process using npx claude-flow-novice agent\r\n *\r\n * This is a wrapper/alias for the existing claude-flow-novice agent spawning mechanism\r\n * Provides the cfn-spawn naming pattern while delegating to the working implementation\r\n */\r\nasync function spawnAgent(options: AgentSpawnOptions): Promise<void> {\r\n const { agentType, agentId, taskId, iteration, context, mode, priority, parentTaskId } = options;\r\n\r\n console.log(`[cfn-spawn] Spawning agent: ${agentType}`);\r\n if (agentId) console.log(`[cfn-spawn] Agent ID: ${agentId}`);\r\n if (taskId) console.log(`[cfn-spawn] Task ID: ${taskId}`);\r\n if (iteration) console.log(`[cfn-spawn] Iteration: ${iteration}`);\r\n if (context) console.log(`[cfn-spawn] Context: ${context}`);\r\n if (mode) console.log(`[cfn-spawn] Mode: ${mode}`);\r\n\r\n // Build command arguments for npx claude-flow-novice agent\r\n const claudeArgs = ['claude-flow-novice', 'agent', agentType];\r\n\r\n // Add optional parameters\r\n if (agentId) {\r\n claudeArgs.push('--agent-id', agentId);\r\n }\r\n if (taskId) {\r\n claudeArgs.push('--task-id', taskId);\r\n }\r\n if (iteration) {\r\n claudeArgs.push('--iteration', iteration.toString());\r\n }\r\n if (context) {\r\n claudeArgs.push('--context', context);\r\n }\r\n if (mode) {\r\n claudeArgs.push('--mode', mode);\r\n }\r\n if (priority) {\r\n claudeArgs.push('--priority', priority.toString());\r\n }\r\n if (parentTaskId) {\r\n claudeArgs.push('--parent-task-id', parentTaskId);\r\n }\r\n\r\n // Fetch epic context from Redis if available\r\n let epicContext = '';\r\n let phaseContext = '';\r\n let successCriteria = '';\r\n\r\n if (taskId) {\r\n try {\r\n const { execSync } = await import('child_process');\r\n\r\n // Try to read epic-level context from Redis\r\n try {\r\n epicContext = execSync(`redis-cli get \"swarm:${taskId}:epic-context\"`, { encoding: 'utf8' }).trim();\r\n if (epicContext === '(nil)') epicContext = '';\r\n } catch (e) {\r\n // Redis not available or key doesn't exist\r\n }\r\n\r\n // Try to read phase-specific context\r\n try {\r\n phaseContext = execSync(`redis-cli get \"swarm:${taskId}:phase-context\"`, { encoding: 'utf8' }).trim();\r\n if (phaseContext === '(nil)') phaseContext = '';\r\n } catch (e) {\r\n // Redis not available or key doesn't exist\r\n }\r\n\r\n // Try to read success criteria\r\n try {\r\n successCriteria = execSync(`redis-cli get \"swarm:${taskId}:success-criteria\"`, { encoding: 'utf8' }).trim();\r\n if (successCriteria === '(nil)') successCriteria = '';\r\n } catch (e) {\r\n // Redis not available or key doesn't exist\r\n }\r\n\r\n if (epicContext) {\r\n console.log(`[cfn-spawn] Epic context loaded from Redis`);\r\n }\r\n } catch (err) {\r\n console.warn(`[cfn-spawn] Could not load epic context from Redis:`, err);\r\n }\r\n }\r\n\r\n // Add environment variables for agent context\r\n const env = {\r\n ...process.env,\r\n AGENT_TYPE: agentType,\r\n TASK_ID: taskId || '',\r\n ITERATION: iteration?.toString() || '1',\r\n CONTEXT: context || '',\r\n MODE: mode || 'cli',\r\n PRIORITY: priority?.toString() || '5',\r\n PARENT_TASK_ID: parentTaskId || '',\r\n // Epic-level context from Redis\r\n EPIC_CONTEXT: epicContext,\r\n PHASE_CONTEXT: phaseContext,\r\n SUCCESS_CRITERIA: successCriteria\r\n };\r\n\r\n console.log(`[cfn-spawn] Executing: npx ${claudeArgs.join(' ')}`);\r\n\r\n // Spawn the claude-flow-novice agent process\r\n const agentProcess = spawn('npx', claudeArgs, {\r\n stdio: 'inherit',\r\n env,\r\n cwd: process.cwd()\r\n });\r\n\r\n // Handle process exit\r\n agentProcess.on('exit', (code, signal) => {\r\n if (code === 0) {\r\n console.log(`[cfn-spawn] Agent ${agentType} completed successfully`);\r\n } else {\r\n console.error(`[cfn-spawn] Agent ${agentType} exited with code ${code}, signal ${signal}`);\r\n }\r\n process.exit(code || 0);\r\n });\r\n\r\n // Handle process errors\r\n agentProcess.on('error', (err) => {\r\n console.error(`[cfn-spawn] Failed to spawn agent ${agentType}:`, err.message);\r\n process.exit(1);\r\n });\r\n\r\n // Cleanup on parent exit\r\n process.on('SIGINT', () => {\r\n console.log('\\n[cfn-spawn] Received SIGINT, terminating agent...');\r\n agentProcess.kill('SIGINT');\r\n });\r\n\r\n process.on('SIGTERM', () => {\r\n console.log('\\n[cfn-spawn] Received SIGTERM, terminating agent...');\r\n agentProcess.kill('SIGTERM');\r\n });\r\n}\r\n\r\n/**\r\n * Build task description for the agent\r\n */\r\nfunction buildTaskDescription(\r\n agentType: string,\r\n taskId?: string,\r\n iteration?: number,\r\n context?: string\r\n): string {\r\n let desc = `Execute task as ${agentType} agent`;\r\n\r\n if (taskId) desc += ` for task ${taskId}`;\r\n if (iteration) desc += ` (iteration ${iteration})`;\r\n if (context) desc += `: ${context}`;\r\n\r\n return desc;\r\n}\r\n\r\n/**\r\n * Main CLI entry point\r\n */\r\nexport async function main(args: string[] = process.argv.slice(2)): Promise<void> {\r\n // Show help if requested\r\n if (args.includes('--help') || args.includes('-h')) {\r\n console.log(`\r\ncfn-spawn - Claude Flow Novice Agent Spawner\r\n\r\nUsage:\r\n cfn-spawn agent <type> [options]\r\n cfn-spawn <type> [options] (agent is implied)\r\n\r\nOptions:\r\n --agent-id <id> Explicit agent identifier (overrides auto-generation)\r\n --task-id <id> Task identifier\r\n --iteration <n> Iteration number\r\n --context <text> Context description\r\n --mode <mode> Execution mode (cli, api, hybrid)\r\n --priority <1-10> Task priority\r\n --parent-task-id <id> Parent task identifier\r\n\r\nExamples:\r\n cfn-spawn agent researcher --task-id task-123 --iteration 1\r\n cfn-spawn coder --task-id auth-impl --context \"Implement JWT auth\"\r\n cfn-spawn reviewer --task-id auth-impl --iteration 2 --mode cli\r\n cfn-spawn tester --agent-id tester-1-1 --task-id test-phase --iteration 1\r\n `);\r\n return;\r\n }\r\n\r\n // Parse arguments\r\n const options = parseAgentArgs(args);\r\n if (!options) {\r\n process.exit(1);\r\n }\r\n\r\n // Spawn the agent\r\n await spawnAgent(options);\r\n}\r\n\r\n// Run if called directly\r\n// ES module check - compare import.meta.url with the executed file\r\nconst isMainModule = import.meta.url.endsWith(process.argv[1]?.replace(/\\\\/g, '/') || '');\r\nif (isMainModule) {\r\n main().catch((err) => {\r\n console.error('[cfn-spawn] Fatal error:', err);\r\n process.exit(1);\r\n });\r\n}\r\n"],"names":["spawn","parseAgentArgs","args","agentType","optionArgs","slice","console","error","options","i","length","key","value","agentId","taskId","iteration","parseInt","context","mode","priority","parentTaskId","warn","spawnAgent","log","claudeArgs","push","toString","epicContext","phaseContext","successCriteria","execSync","encoding","trim","e","err","env","process","AGENT_TYPE","TASK_ID","ITERATION","CONTEXT","MODE","PRIORITY","PARENT_TASK_ID","EPIC_CONTEXT","PHASE_CONTEXT","SUCCESS_CRITERIA","join","agentProcess","stdio","cwd","on","code","signal","exit","message","kill","buildTaskDescription","desc","main","argv","includes","isMainModule","url","endsWith","replace","catch"],"mappings":";AACA;;;;;;;;;;CAUC,GAED,SAASA,KAAK,QAAQ,gBAAgB;AActC;;CAEC,GACD,SAASC,eAAeC,IAAc;IACpC,mDAAmD;IACnD,IAAIC;IACJ,IAAIC;IAEJ,IAAIF,IAAI,CAAC,EAAE,KAAK,SAAS;QACvBC,YAAYD,IAAI,CAAC,EAAE;QACnBE,aAAaF,KAAKG,KAAK,CAAC;IAC1B,OAAO;QACLF,YAAYD,IAAI,CAAC,EAAE;QACnBE,aAAaF,KAAKG,KAAK,CAAC;IAC1B;IAEA,IAAI,CAACF,WAAW;QACdG,QAAQC,KAAK,CAAC;QACdD,QAAQC,KAAK,CAAC;QACd,OAAO;IACT;IAEA,MAAMC,UAA6B;QAAEL;IAAU;IAE/C,4BAA4B;IAC5B,IA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ropic-ai/sdk';
7
7
  import fs from 'fs/promises';
8
8
  import path from 'path';
9
+ import { exec } from 'child_process';
10
+ import { promisify } from 'util';
11
+ import { executeTool } from './tool-executor.js';
12
+ const execAsync = promisify(exec);
9
13
  /**
10
14
  * Get API configuration from environment and config files
11
15
  */ export async function getAPIConfig() {
@@ -90,7 +94,7 @@ import path from 'path';
90
94
  const config = await getAPIConfig();
91
95
  // Primary model (glm-4.6 for Z.ai, Claude for Anthropic)
92
96
  let model = mapModelName(options.model, config.provider);
93
- const maxTokens = options.maxTokens || 4096;
97
+ const maxTokens = options.maxTokens || 16000; // Sprint 6: 16K hard limit for GLM-4.6 (agents target 10K for buffer)
94
98
  const temperature = options.temperature ?? 1.0;
95
99
  // Disable streaming for Z.ai (compatibility issue)
96
100
  const enableStreaming = options.stream && config.provider !== 'zai';
@@ -99,7 +103,11 @@ import path from 'path';
99
103
  console.log(`[anthropic-client] Max tokens: ${maxTokens}`);
100
104
  console.log(`[anthropic-client] Stream: ${enableStreaming ? 'enabled' : 'disabled'}`);
101
105
  console.log('');
102
- const messages = [
106
+ // Sprint 4: Use messages array if provided (conversation forking)
107
+ const messages = options.messages ? options.messages.map((m)=>({
108
+ role: m.role,
109
+ content: m.content
110
+ })) : [
103
111
  {
104
112
  role: 'user',
105
113
  content: options.prompt
@@ -197,29 +205,188 @@ import path from 'path';
197
205
  // Should never reach here
198
206
  throw lastError || new Error('All retry attempts failed');
199
207
  }
208
+ /**
209
+ * Execute agent with tool support (agentic loop)
210
+ *
211
+ * Handles:
212
+ * 1. Send message with tools
213
+ * 2. Get response
214
+ * 3. If tool_use blocks, execute tools and send results back
215
+ * 4. Repeat until final text response
216
+ */ async function executeWithTools(options, onChunk) {
217
+ const client = await createClient();
218
+ const config = await getAPIConfig();
219
+ const model = mapModelName(options.model, config.provider);
220
+ const maxTokens = options.maxTokens || 16000;
221
+ const temperature = options.temperature ?? 1.0;
222
+ // Build initial messages array
223
+ const messages = options.messages ? options.messages.map((m)=>({
224
+ role: m.role,
225
+ content: m.content
226
+ })) : [
227
+ {
228
+ role: 'user',
229
+ content: options.prompt
230
+ }
231
+ ];
232
+ let totalInputTokens = 0;
233
+ let totalOutputTokens = 0;
234
+ let fullTextContent = '';
235
+ const MAX_ITERATIONS = 10; // Prevent infinite loops
236
+ let iteration = 0;
237
+ while(iteration < MAX_ITERATIONS){
238
+ iteration++;
239
+ console.log(`[executeWithTools] Iteration ${iteration}`);
240
+ const requestParams = {
241
+ model,
242
+ max_tokens: maxTokens,
243
+ temperature,
244
+ messages
245
+ };
246
+ if (options.systemPrompt) {
247
+ requestParams.system = options.systemPrompt;
248
+ }
249
+ if (options.tools && options.tools.length > 0) {
250
+ requestParams.tools = options.tools;
251
+ }
252
+ // Make API request (non-streaming for now to handle tool_use)
253
+ const response = await client.messages.create(requestParams);
254
+ totalInputTokens += response.usage.input_tokens;
255
+ totalOutputTokens += response.usage.output_tokens;
256
+ // Extract content blocks
257
+ const textBlocks = response.content.filter((block)=>block.type === 'text');
258
+ const toolUseBlocks = response.content.filter((block)=>block.type === 'tool_use');
259
+ // Stream text output
260
+ for (const block of textBlocks){
261
+ if (block.type === 'text') {
262
+ const text = block.text;
263
+ fullTextContent += text;
264
+ if (onChunk) {
265
+ onChunk(text);
266
+ }
267
+ }
268
+ }
269
+ // If no tool uses, we're done
270
+ if (toolUseBlocks.length === 0) {
271
+ console.log(`[executeWithTools] No tool uses, completing`);
272
+ return {
273
+ content: fullTextContent,
274
+ usage: {
275
+ inputTokens: totalInputTokens,
276
+ outputTokens: totalOutputTokens
277
+ },
278
+ stopReason: response.stop_reason || 'end_turn'
279
+ };
280
+ }
281
+ // Execute tools
282
+ console.log(`[executeWithTools] Executing ${toolUseBlocks.length} tool(s)`);
283
+ const toolResults = [];
284
+ for (const toolUseBlock of toolUseBlocks){
285
+ if (toolUseBlock.type !== 'tool_use') continue;
286
+ const toolUse = {
287
+ type: 'tool_use',
288
+ id: toolUseBlock.id,
289
+ name: toolUseBlock.name,
290
+ input: toolUseBlock.input
291
+ };
292
+ console.log(`[executeWithTools] Tool: ${toolUse.name}`);
293
+ const result = await executeTool(toolUse);
294
+ toolResults.push(result);
295
+ // Stream tool result
296
+ if (onChunk) {
297
+ onChunk(`\n[Tool: ${toolUse.name}] ${result.content.substring(0, 100)}${result.content.length > 100 ? '...' : ''}\n`);
298
+ }
299
+ }
300
+ // Add assistant message with tool_use
301
+ messages.push({
302
+ role: 'assistant',
303
+ content: response.content
304
+ });
305
+ // Add tool results as user message
306
+ messages.push({
307
+ role: 'user',
308
+ content: toolResults
309
+ });
310
+ // Continue to next iteration
311
+ }
312
+ // Reached max iterations
313
+ console.warn(`[executeWithTools] Reached max iterations (${MAX_ITERATIONS})`);
314
+ return {
315
+ content: fullTextContent,
316
+ usage: {
317
+ inputTokens: totalInputTokens,
318
+ outputTokens: totalOutputTokens
319
+ },
320
+ stopReason: 'max_tokens'
321
+ };
322
+ }
200
323
  /**
201
324
  * Execute agent via API with full lifecycle
202
- */ export async function executeAgentAPI(agentType, agentId, model, prompt, systemPrompt) {
325
+ */ export async function executeAgentAPI(agentType, agentId, model, prompt, systemPrompt, messages, maxTokens, tools// Tool definitions for agent capabilities
326
+ ) {
327
+ // Start heartbeat monitoring (declare at function scope for error handling)
328
+ let heartbeatInterval = null;
329
+ const taskId = process.env.TASK_ID;
203
330
  try {
204
331
  console.log(`[anthropic-client] Executing agent: ${agentType}`);
205
332
  console.log(`[anthropic-client] Agent ID: ${agentId}`);
333
+ if (messages && messages.length > 1) {
334
+ console.log(`[anthropic-client] Continuing conversation (${messages.length} messages)`);
335
+ }
206
336
  console.log('');
337
+ if (taskId) {
338
+ heartbeatInterval = setInterval(async ()=>{
339
+ try {
340
+ await execAsync(`redis-cli hset "swarm:${taskId}:agent:${agentId}" heartbeat "${Date.now()}" status "working"`);
341
+ } catch (err) {
342
+ console.error('[heartbeat] Error sending heartbeat:', err);
343
+ }
344
+ }, 30000); // Every 30 seconds
345
+ console.log(`[heartbeat] Monitoring started for agent ${agentId} (30s interval)`);
346
+ }
207
347
  let fullOutput = '';
208
- const response = await sendMessage({
209
- model,
210
- prompt,
211
- systemPrompt,
212
- stream: true
213
- }, (chunk)=>{
214
- // Stream output in real-time
215
- process.stdout.write(chunk);
216
- fullOutput += chunk;
217
- });
348
+ // If tools provided, use agentic loop with tool execution
349
+ // Otherwise use simple streaming
350
+ let response;
351
+ if (tools && tools.length > 0) {
352
+ console.log(`[anthropic-client] Tools enabled: ${tools.map((t)=>t.name).join(', ')}`);
353
+ response = await executeWithTools({
354
+ model,
355
+ prompt,
356
+ systemPrompt,
357
+ messages,
358
+ maxTokens,
359
+ tools
360
+ }, (chunk)=>{
361
+ process.stdout.write(chunk);
362
+ fullOutput += chunk;
363
+ });
364
+ } else {
365
+ response = await sendMessage({
366
+ model,
367
+ prompt,
368
+ systemPrompt,
369
+ stream: true,
370
+ messages,
371
+ maxTokens
372
+ }, (chunk)=>{
373
+ process.stdout.write(chunk);
374
+ fullOutput += chunk;
375
+ });
376
+ }
218
377
  console.log('\n');
219
378
  console.log('=== Agent Execution Complete ===');
220
379
  console.log(`Input tokens: ${response.usage.inputTokens}`);
221
380
  console.log(`Output tokens: ${response.usage.outputTokens}`);
222
381
  console.log(`Stop reason: ${response.stopReason}`);
382
+ // Stop heartbeat and send final status
383
+ if (heartbeatInterval) {
384
+ clearInterval(heartbeatInterval);
385
+ if (taskId) {
386
+ await execAsync(`redis-cli hset "swarm:${taskId}:agent:${agentId}" heartbeat "${Date.now()}" status "complete"`);
387
+ console.log(`[heartbeat] Monitoring stopped - agent ${agentId} complete`);
388
+ }
389
+ }
223
390
  return {
224
391
  success: true,
225
392
  output: response.content,
@@ -227,6 +394,18 @@ import path from 'path';
227
394
  };
228
395
  } catch (error) {
229
396
  console.error('[anthropic-client] Error:', error);
397
+ // Stop heartbeat and send error status
398
+ if (heartbeatInterval) {
399
+ clearInterval(heartbeatInterval);
400
+ if (taskId) {
401
+ try {
402
+ await execAsync(`redis-cli hset "swarm:${taskId}:agent:${agentId}" heartbeat "${Date.now()}" status "error"`);
403
+ console.log(`[heartbeat] Monitoring stopped - agent ${agentId} error`);
404
+ } catch (err) {
405
+ // Ignore heartbeat errors during error handling
406
+ }
407
+ }
408
+ }
230
409
  return {
231
410
  success: false,
232
411
  output: '',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/anthropic-client.ts"],"sourcesContent":["/**\r\n * Anthropic API Client\r\n *\r\n * Handles communication with Claude API (Anthropic or z.ai provider).\r\n * Supports streaming responses and tool execution.\r\n */\r\n\r\nimport Anthropic from '@anthropic-ai/sdk';\r\nimport fs from 'fs/promises';\r\nimport path from 'path';\r\n\r\nexport interface APIConfig {\r\n provider: 'anthropic' | 'zai';\r\n apiKey?: string;\r\n baseURL?: string;\r\n}\r\n\r\nexport interface MessageOptions {\r\n model: string;\r\n prompt: string;\r\n systemPrompt?: string;\r\n maxTokens?: number;\r\n temperature?: number;\r\n stream?: boolean;\r\n tools?: any[];\r\n}\r\n\r\nexport interface MessageResponse {\r\n content: string;\r\n usage: {\r\n inputTokens: number;\r\n outputTokens: number;\r\n };\r\n stopReason: string;\r\n}\r\n\r\n/**\r\n * Get API configuration from environment and config files\r\n */\r\nexport async function getAPIConfig(): Promise<APIConfig> {\r\n // Check environment variable\r\n const envProvider = process.env.CLAUDE_API_PROVIDER;\r\n if (envProvider === 'zai') {\r\n return {\r\n provider: 'zai',\r\n apiKey: process.env.ZAI_API_KEY || process.env.ANTHROPIC_API_KEY,\r\n baseURL: process.env.ZAI_BASE_URL || 'https://api.z.ai/api/anthropic',\r\n };\r\n }\r\n\r\n // Check config file\r\n try {\r\n const configPath = path.join('.claude', 'config', 'api-provider.json');\r\n const config = JSON.parse(await fs.readFile(configPath, 'utf-8'));\r\n\r\n if (config.provider === 'zai' || config.provider === 'z.ai') {\r\n return {\r\n provider: 'zai',\r\n apiKey: config.apiKey || process.env.ZAI_API_KEY || process.env.ANTHROPIC_API_KEY,\r\n baseURL: config.baseURL || process.env.ZAI_BASE_URL || 'https://api.z.ai/api/anthropic',\r\n };\r\n }\r\n } catch {\r\n // Config file doesn't exist, use defaults\r\n }\r\n\r\n // Default to Anthropic\r\n return {\r\n provider: 'anthropic',\r\n apiKey: process.env.ANTHROPIC_API_KEY,\r\n };\r\n}\r\n\r\n/**\r\n * Create Anthropic client with appropriate configuration\r\n */\r\nexport async function createClient(): Promise<Anthropic> {\r\n const config = await getAPIConfig();\r\n\r\n if (!config.apiKey) {\r\n throw new Error(\r\n `API key not found. Set ${config.provider === 'zai' ? 'ZAI_API_KEY' : 'ANTHROPIC_API_KEY'} environment variable.`\r\n );\r\n }\r\n\r\n const clientOptions: any = {\r\n apiKey: config.apiKey,\r\n timeout: 120000, // 2 minutes (120 seconds)\r\n maxRetries: 2,\r\n };\r\n\r\n if (config.provider === 'zai' && config.baseURL) {\r\n clientOptions.baseURL = config.baseURL;\r\n }\r\n\r\n return new Anthropic(clientOptions);\r\n}\r\n\r\n/**\r\n * Map agent model name to API model ID (provider-specific)\r\n */\r\nexport function mapModelName(agentModel: string, provider: 'anthropic' | 'zai' = 'anthropic'): string {\r\n // Z.ai uses GLM models - try glm-4.6 first for all models\r\n if (provider === 'zai') {\r\n const zaiModelMap: Record<string, string> = {\r\n haiku: 'glm-4.6',\r\n sonnet: 'glm-4.6',\r\n opus: 'glm-4.6',\r\n };\r\n return zaiModelMap[agentModel] || 'glm-4.6';\r\n }\r\n\r\n // Anthropic uses Claude models\r\n const modelMap: Record<string, string> = {\r\n haiku: 'claude-3-5-haiku-20241022',\r\n sonnet: 'claude-3-5-sonnet-20241022',\r\n opus: 'claude-3-opus-20240229',\r\n };\r\n\r\n return modelMap[agentModel] || modelMap.haiku;\r\n}\r\n\r\n/**\r\n * Get fallback model for Z.ai (glm-4.6 -> glm-4.5-air)\r\n */\r\nfunction getFallbackModel(model: string): string | null {\r\n if (model === 'glm-4.6') {\r\n return 'glm-4.5-air';\r\n }\r\n return null;\r\n}\r\n\r\n/**\r\n * Send message to Claude API with streaming support and automatic fallback\r\n */\r\nexport async function sendMessage(\r\n options: MessageOptions,\r\n onChunk?: (text: string) => void\r\n): Promise<MessageResponse> {\r\n const client = await createClient();\r\n const config = await getAPIConfig();\r\n\r\n // Primary model (glm-4.6 for Z.ai, Claude for Anthropic)\r\n let model = mapModelName(options.model, config.provider);\r\n const maxTokens = options.maxTokens || 4096;\r\n const temperature = options.temperature ?? 1.0;\r\n\r\n // Disable streaming for Z.ai (compatibility issue)\r\n const enableStreaming = options.stream && config.provider !== 'zai';\r\n\r\n console.log(`[anthropic-client] Provider: ${config.provider}`);\r\n console.log(`[anthropic-client] Model: ${model}`);\r\n console.log(`[anthropic-client] Max tokens: ${maxTokens}`);\r\n console.log(`[anthropic-client] Stream: ${enableStreaming ? 'enabled' : 'disabled'}`);\r\n console.log('');\r\n\r\n const messages: Anthropic.MessageParam[] = [\r\n {\r\n role: 'user',\r\n content: options.prompt,\r\n },\r\n ];\r\n\r\n // Retry logic: Try primary model (glm-4.6), fall back to glm-4.5 on error\r\n let lastError: Error | null = null;\r\n let attempts = 0;\r\n const maxAttempts = 2; // Primary + fallback\r\n\r\n while (attempts < maxAttempts) {\r\n const currentModel = attempts === 0 ? model : getFallbackModel(model);\r\n\r\n if (!currentModel) {\r\n // No fallback available, throw last error\r\n throw lastError || new Error('No model available');\r\n }\r\n\r\n attempts++;\r\n\r\n if (attempts > 1) {\r\n console.log(`[anthropic-client] Retrying with fallback model: ${currentModel}`);\r\n }\r\n\r\n const requestParams: Anthropic.MessageCreateParams = {\r\n model: currentModel,\r\n max_tokens: maxTokens,\r\n temperature,\r\n messages,\r\n };\r\n\r\n if (options.systemPrompt) {\r\n requestParams.system = options.systemPrompt;\r\n }\r\n\r\n if (options.tools && options.tools.length > 0) {\r\n requestParams.tools = options.tools;\r\n }\r\n\r\n try {\r\n // Streaming response\r\n if (enableStreaming) {\r\n let fullContent = '';\r\n let inputTokens = 0;\r\n let outputTokens = 0;\r\n let stopReason = 'end_turn';\r\n\r\n console.log('[anthropic-client] Creating streaming request...');\r\n const stream = await client.messages.create({\r\n ...requestParams,\r\n stream: true,\r\n });\r\n\r\n console.log('[anthropic-client] Stream created, processing events...');\r\n for await (const event of stream) {\r\n console.log('[anthropic-client] Event type:', event.type);\r\n if (event.type === 'message_start') {\r\n // @ts-ignore - usage exists on message_start\r\n inputTokens = event.message.usage?.input_tokens || 0;\r\n } else if (event.type === 'content_block_delta') {\r\n // @ts-ignore - text exists on delta\r\n const text = event.delta?.text || '';\r\n fullContent += text;\r\n if (onChunk) {\r\n onChunk(text);\r\n }\r\n } else if (event.type === 'message_delta') {\r\n // @ts-ignore - usage exists on message_delta\r\n outputTokens = event.usage?.output_tokens || 0;\r\n // @ts-ignore - stop_reason exists on delta\r\n stopReason = event.delta?.stop_reason || 'end_turn';\r\n }\r\n }\r\n\r\n return {\r\n content: fullContent,\r\n usage: {\r\n inputTokens,\r\n outputTokens,\r\n },\r\n stopReason,\r\n };\r\n }\r\n\r\n // Non-streaming response\r\n const response = await client.messages.create(requestParams);\r\n\r\n const content =\r\n response.content\r\n .filter((block) => block.type === 'text')\r\n .map((block) => (block as any).text)\r\n .join('\\n') || '';\r\n\r\n return {\r\n content,\r\n usage: {\r\n inputTokens: response.usage.input_tokens,\r\n outputTokens: response.usage.output_tokens,\r\n },\r\n stopReason: response.stop_reason || 'end_turn',\r\n };\r\n } catch (error) {\r\n lastError = error instanceof Error ? error : new Error(String(error));\r\n console.error(`[anthropic-client] Error with model ${currentModel}:`, lastError.message);\r\n\r\n // If this was the last attempt, throw the error\r\n if (attempts >= maxAttempts) {\r\n throw lastError;\r\n }\r\n\r\n // Continue to next attempt with fallback model\r\n console.log('[anthropic-client] Will retry with fallback model...');\r\n }\r\n }\r\n\r\n // Should never reach here\r\n throw lastError || new Error('All retry attempts failed');\r\n}\r\n\r\n/**\r\n * Execute agent via API with full lifecycle\r\n */\r\nexport async function executeAgentAPI(\r\n agentType: string,\r\n agentId: string,\r\n model: string,\r\n prompt: string,\r\n systemPrompt?: string\r\n): Promise<{ success: boolean; output: string; usage: any; error?: string }> {\r\n try {\r\n console.log(`[anthropic-client] Executing agent: ${agentType}`);\r\n console.log(`[anthropic-client] Agent ID: ${agentId}`);\r\n console.log('');\r\n\r\n let fullOutput = '';\r\n\r\n const response = await sendMessage(\r\n {\r\n model,\r\n prompt,\r\n systemPrompt,\r\n stream: true,\r\n },\r\n (chunk) => {\r\n // Stream output in real-time\r\n process.stdout.write(chunk);\r\n fullOutput += chunk;\r\n }\r\n );\r\n\r\n console.log('\\n');\r\n console.log('=== Agent Execution Complete ===');\r\n console.log(`Input tokens: ${response.usage.inputTokens}`);\r\n console.log(`Output tokens: ${response.usage.outputTokens}`);\r\n console.log(`Stop reason: ${response.stopReason}`);\r\n\r\n return {\r\n success: true,\r\n output: response.content,\r\n usage: response.usage,\r\n };\r\n } catch (error) {\r\n console.error('[anthropic-client] Error:', error);\r\n return {\r\n success: false,\r\n output: '',\r\n usage: { inputTokens: 0, outputTokens: 0 },\r\n error: error instanceof Error ? error.message : String(error),\r\n };\r\n }\r\n}\r\n"],"names":["Anthropic","fs","path","getAPIConfig","envProvider","process","env","CLAUDE_API_PROVIDER","provider","apiKey","ZAI_API_KEY","ANTHROPIC_API_KEY","baseURL","ZAI_BASE_URL","configPath","join","config","JSON","parse","readFile","createClient","Error","clientOptions","timeout","maxRetries","mapModelName","agentModel","zaiModelMap","haiku","sonnet","opus","modelMap","getFallbackModel","model","sendMessage","options","onChunk","client","maxTokens","temperature","enableStreaming","stream","console","log","messages","role","content","prompt","lastError","attempts","maxAttempts","currentModel","requestParams","max_tokens","systemPrompt","system","tools","length","fullContent","inputTokens","outputTokens","stopReason","create","event","type","message","usage","input_tokens","text","delta","output_tokens","stop_reason","response","filter","block","map","error","String","executeAgentAPI","agentType","agentId","fullOutput","chunk","stdout","write","success","output"],"mappings":"AAAA;;;;;CAKC,GAED,OAAOA,eAAe,oBAAoB;AAC1C,OAAOC,QAAQ,cAAc;AAC7B,OAAOC,UAAU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QC,GAAG,CAAC,CAAC,6BAA6B,EAAEqC,SAAS;QACrDtC,QAAQC,GAAG,CAAC;QAEZ,IAAIsC,aAAa;QAEjB,MAAMT,WAAW,MAAMtC,YACrB;YACED;YACAc;YACAO;YACAb,QAAQ;QACV,GACA,CAACyC;YACC,6BAA6B;YAC7B7E,QAAQ8E,MAAM,CAACC,KAAK,CAACF;YACrBD,cAAcC;QAChB;QAGFxC,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC,CAAC,cAAc,EAAE6B,SAASN,KAAK,CAACP,WAAW,EAAE;QACzDjB,QAAQC,GAAG,CAAC,CAAC,eAAe,EAAE6B,SAASN,KAAK,CAACN,YAAY,EAAE;QAC3DlB,QAAQC,GAAG,CAAC,CAAC,aAAa,EAAE6B,SAASX,UAAU,EAAE;QAEjD,OAAO;YACLwB,SAAS;YACTC,QAAQd,SAAS1B,OAAO;YACxBoB,OAAOM,SAASN,KAAK;QACvB;IACF,EAAE,OAAOU,OAAO;QACdlC,QAAQkC,KAAK,CAAC,6BAA6BA;QAC3C,OAAO;YACLS,SAAS;YACTC,QAAQ;YACRpB,OAAO;gBAAEP,aAAa;gBAAGC,cAAc;YAAE;YACzCgB,OAAOA,iBAAiBvD,QAAQuD,MAAMX,OAAO,GAAGY,OAAOD;QACzD;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/cli/anthropic-client.ts"],"sourcesContent":["/**\r\n * Anthropic API Client\r\n *\r\n * Handles communication with Claude API (Anthropic or z.ai provider).\r\n * Supports streaming responses and tool execution.\r\n */\r\n\r\nimport Anthropic from '@anthropic-ai/sdk';\r\nimport fs from 'fs/promises';\r\nimport path from 'path';\r\nimport { exec } from 'child_process';\r\nimport { promisify } from 'util';\r\nimport { executeTool, type ToolUse, type ToolResult } from './tool-executor.js';\r\n\r\nconst execAsync = promisify(exec);\r\n\r\nexport interface APIConfig {\r\n provider: 'anthropic' | 'zai';\r\n apiKey?: string;\r\n baseURL?: string;\r\n}\r\n\r\nexport interface MessageOptions {\r\n model: string;\r\n prompt: string;\r\n systemPrompt?: string;\r\n maxTokens?: number;\r\n temperature?: number;\r\n stream?: boolean;\r\n tools?: any[];\r\n messages?: Array<{ role: string; content: string }>; // Sprint 4: Conversation forking\r\n}\r\n\r\nexport interface MessageResponse {\r\n content: string;\r\n usage: {\r\n inputTokens: number;\r\n outputTokens: number;\r\n };\r\n stopReason: string;\r\n}\r\n\r\n/**\r\n * Get API configuration from environment and config files\r\n */\r\nexport async function getAPIConfig(): Promise<APIConfig> {\r\n // Check environment variable\r\n const envProvider = process.env.CLAUDE_API_PROVIDER;\r\n if (envProvider === 'zai') {\r\n return {\r\n provider: 'zai',\r\n apiKey: process.env.ZAI_API_KEY || process.env.ANTHROPIC_API_KEY,\r\n baseURL: process.env.ZAI_BASE_URL || 'https://api.z.ai/api/anthropic',\r\n };\r\n }\r\n\r\n // Check config file\r\n try {\r\n const configPath = path.join('.claude', 'config', 'api-provider.json');\r\n const config = JSON.parse(await fs.readFile(configPath, 'utf-8'));\r\n\r\n if (config.provider === 'zai' || config.provider === 'z.ai') {\r\n return {\r\n provider: 'zai',\r\n apiKey: config.apiKey || process.env.ZAI_API_KEY || process.env.ANTHROPIC_API_KEY,\r\n baseURL: config.baseURL || process.env.ZAI_BASE_URL || 'https://api.z.ai/api/anthropic',\r\n };\r\n }\r\n } catch {\r\n // Config file doesn't exist, use defaults\r\n }\r\n\r\n // Default to Anthropic\r\n return {\r\n provider: 'anthropic',\r\n apiKey: process.env.ANTHROPIC_API_KEY,\r\n };\r\n}\r\n\r\n/**\r\n * Create Anthropic client with appropriate configuration\r\n */\r\nexport async function createClient(): Promise<Anthropic> {\r\n const config = await getAPIConfig();\r\n\r\n if (!config.apiKey) {\r\n throw new Error(\r\n `API key not found. Set ${config.provider === 'zai' ? 'ZAI_API_KEY' : 'ANTHROPIC_API_KEY'} environment variable.`\r\n );\r\n }\r\n\r\n const clientOptions: any = {\r\n apiKey: config.apiKey,\r\n timeout: 120000, // 2 minutes (120 seconds)\r\n maxRetries: 2,\r\n };\r\n\r\n if (config.provider === 'zai' && config.baseURL) {\r\n clientOptions.baseURL = config.baseURL;\r\n }\r\n\r\n return new Anthropic(clientOptions);\r\n}\r\n\r\n/**\r\n * Map agent model name to API model ID (provider-specific)\r\n */\r\nexport function mapModelName(agentModel: string, provider: 'anthropic' | 'zai' = 'anthropic'): string {\r\n // Z.ai uses GLM models - try glm-4.6 first for all models\r\n if (provider === 'zai') {\r\n const zaiModelMap: Record<string, string> = {\r\n haiku: 'glm-4.6',\r\n sonnet: 'glm-4.6',\r\n opus: 'glm-4.6',\r\n };\r\n return zaiModelMap[agentModel] || 'glm-4.6';\r\n }\r\n\r\n // Anthropic uses Claude models\r\n const modelMap: Record<string, string> = {\r\n haiku: 'claude-3-5-haiku-20241022',\r\n sonnet: 'claude-3-5-sonnet-20241022',\r\n opus: 'claude-3-opus-20240229',\r\n };\r\n\r\n return modelMap[agentModel] || modelMap.haiku;\r\n}\r\n\r\n/**\r\n * Get fallback model for Z.ai (glm-4.6 -> glm-4.5-air)\r\n */\r\nfunction getFallbackModel(model: string): string | null {\r\n if (model === 'glm-4.6') {\r\n return 'glm-4.5-air';\r\n }\r\n return null;\r\n}\r\n\r\n/**\r\n * Send message to Claude API with streaming support and automatic fallback\r\n */\r\nexport async function sendMessage(\r\n options: MessageOptions,\r\n onChunk?: (text: string) => void\r\n): Promise<MessageResponse> {\r\n const client = await createClient();\r\n const config = await getAPIConfig();\r\n\r\n // Primary model (glm-4.6 for Z.ai, Claude for Anthropic)\r\n let model = mapModelName(options.model, config.provider);\r\n const maxTokens = options.maxTokens || 16000; // Sprint 6: 16K hard limit for GLM-4.6 (agents target 10K for buffer)\r\n const temperature = options.temperature ?? 1.0;\r\n\r\n // Disable streaming for Z.ai (compatibility issue)\r\n const enableStreaming = options.stream && config.provider !== 'zai';\r\n\r\n console.log(`[anthropic-client] Provider: ${config.provider}`);\r\n console.log(`[anthropic-client] Model: ${model}`);\r\n console.log(`[anthropic-client] Max tokens: ${maxTokens}`);\r\n console.log(`[anthropic-client] Stream: ${enableStreaming ? 'enabled' : 'disabled'}`);\r\n console.log('');\r\n\r\n // Sprint 4: Use messages array if provided (conversation forking)\r\n const messages: Anthropic.MessageParam[] = options.messages\r\n ? options.messages.map(m => ({\r\n role: m.role as 'user' | 'assistant',\r\n content: m.content,\r\n }))\r\n : [\r\n {\r\n role: 'user',\r\n content: options.prompt,\r\n },\r\n ];\r\n\r\n // Retry logic: Try primary model (glm-4.6), fall back to glm-4.5 on error\r\n let lastError: Error | null = null;\r\n let attempts = 0;\r\n const maxAttempts = 2; // Primary + fallback\r\n\r\n while (attempts < maxAttempts) {\r\n const currentModel = attempts === 0 ? model : getFallbackModel(model);\r\n\r\n if (!currentModel) {\r\n // No fallback available, throw last error\r\n throw lastError || new Error('No model available');\r\n }\r\n\r\n attempts++;\r\n\r\n if (attempts > 1) {\r\n console.log(`[anthropic-client] Retrying with fallback model: ${currentModel}`);\r\n }\r\n\r\n const requestParams: Anthropic.MessageCreateParams = {\r\n model: currentModel,\r\n max_tokens: maxTokens,\r\n temperature,\r\n messages,\r\n };\r\n\r\n if (options.systemPrompt) {\r\n requestParams.system = options.systemPrompt;\r\n }\r\n\r\n if (options.tools && options.tools.length > 0) {\r\n requestParams.tools = options.tools;\r\n }\r\n\r\n try {\r\n // Streaming response\r\n if (enableStreaming) {\r\n let fullContent = '';\r\n let inputTokens = 0;\r\n let outputTokens = 0;\r\n let stopReason = 'end_turn';\r\n\r\n console.log('[anthropic-client] Creating streaming request...');\r\n const stream = await client.messages.create({\r\n ...requestParams,\r\n stream: true,\r\n });\r\n\r\n console.log('[anthropic-client] Stream created, processing events...');\r\n for await (const event of stream) {\r\n console.log('[anthropic-client] Event type:', event.type);\r\n if (event.type === 'message_start') {\r\n // @ts-ignore - usage exists on message_start\r\n inputTokens = event.message.usage?.input_tokens || 0;\r\n } else if (event.type === 'content_block_delta') {\r\n // @ts-ignore - text exists on delta\r\n const text = event.delta?.text || '';\r\n fullContent += text;\r\n if (onChunk) {\r\n onChunk(text);\r\n }\r\n } else if (event.type === 'message_delta') {\r\n // @ts-ignore - usage exists on message_delta\r\n outputTokens = event.usage?.output_tokens || 0;\r\n // @ts-ignore - stop_reason exists on delta\r\n stopReason = event.delta?.stop_reason || 'end_turn';\r\n }\r\n }\r\n\r\n return {\r\n content: fullContent,\r\n usage: {\r\n inputTokens,\r\n outputTokens,\r\n },\r\n stopReason,\r\n };\r\n }\r\n\r\n // Non-streaming response\r\n const response = await client.messages.create(requestParams);\r\n\r\n const content =\r\n response.content\r\n .filter((block) => block.type === 'text')\r\n .map((block) => (block as any).text)\r\n .join('\\n') || '';\r\n\r\n return {\r\n content,\r\n usage: {\r\n inputTokens: response.usage.input_tokens,\r\n outputTokens: response.usage.output_tokens,\r\n },\r\n stopReason: response.stop_reason || 'end_turn',\r\n };\r\n } catch (error) {\r\n lastError = error instanceof Error ? error : new Error(String(error));\r\n console.error(`[anthropic-client] Error with model ${currentModel}:`, lastError.message);\r\n\r\n // If this was the last attempt, throw the error\r\n if (attempts >= maxAttempts) {\r\n throw lastError;\r\n }\r\n\r\n // Continue to next attempt with fallback model\r\n console.log('[anthropic-client] Will retry with fallback model...');\r\n }\r\n }\r\n\r\n // Should never reach here\r\n throw lastError || new Error('All retry attempts failed');\r\n}\r\n\r\n/**\r\n * Execute agent with tool support (agentic loop)\r\n *\r\n * Handles:\r\n * 1. Send message with tools\r\n * 2. Get response\r\n * 3. If tool_use blocks, execute tools and send results back\r\n * 4. Repeat until final text response\r\n */\r\nasync function executeWithTools(\r\n options: MessageOptions,\r\n onChunk?: (text: string) => void\r\n): Promise<MessageResponse> {\r\n const client = await createClient();\r\n const config = await getAPIConfig();\r\n\r\n const model = mapModelName(options.model, config.provider);\r\n const maxTokens = options.maxTokens || 16000;\r\n const temperature = options.temperature ?? 1.0;\r\n\r\n // Build initial messages array\r\n const messages: Anthropic.MessageParam[] = options.messages\r\n ? options.messages.map(m => ({\r\n role: m.role as 'user' | 'assistant',\r\n content: m.content,\r\n }))\r\n : [\r\n {\r\n role: 'user',\r\n content: options.prompt,\r\n },\r\n ];\r\n\r\n let totalInputTokens = 0;\r\n let totalOutputTokens = 0;\r\n let fullTextContent = '';\r\n const MAX_ITERATIONS = 10; // Prevent infinite loops\r\n let iteration = 0;\r\n\r\n while (iteration < MAX_ITERATIONS) {\r\n iteration++;\r\n console.log(`[executeWithTools] Iteration ${iteration}`);\r\n\r\n const requestParams: Anthropic.MessageCreateParams = {\r\n model,\r\n max_tokens: maxTokens,\r\n temperature,\r\n messages,\r\n };\r\n\r\n if (options.systemPrompt) {\r\n requestParams.system = options.systemPrompt;\r\n }\r\n\r\n if (options.tools && options.tools.length > 0) {\r\n requestParams.tools = options.tools;\r\n }\r\n\r\n // Make API request (non-streaming for now to handle tool_use)\r\n const response = await client.messages.create(requestParams);\r\n\r\n totalInputTokens += response.usage.input_tokens;\r\n totalOutputTokens += response.usage.output_tokens;\r\n\r\n // Extract content blocks\r\n const textBlocks = response.content.filter(block => block.type === 'text');\r\n const toolUseBlocks = response.content.filter(block => block.type === 'tool_use');\r\n\r\n // Stream text output\r\n for (const block of textBlocks) {\r\n if (block.type === 'text') {\r\n const text = (block as any).text;\r\n fullTextContent += text;\r\n if (onChunk) {\r\n onChunk(text);\r\n }\r\n }\r\n }\r\n\r\n // If no tool uses, we're done\r\n if (toolUseBlocks.length === 0) {\r\n console.log(`[executeWithTools] No tool uses, completing`);\r\n return {\r\n content: fullTextContent,\r\n usage: {\r\n inputTokens: totalInputTokens,\r\n outputTokens: totalOutputTokens,\r\n },\r\n stopReason: response.stop_reason || 'end_turn',\r\n };\r\n }\r\n\r\n // Execute tools\r\n console.log(`[executeWithTools] Executing ${toolUseBlocks.length} tool(s)`);\r\n const toolResults: ToolResult[] = [];\r\n\r\n for (const toolUseBlock of toolUseBlocks) {\r\n if (toolUseBlock.type !== 'tool_use') continue;\r\n\r\n const toolUse: ToolUse = {\r\n type: 'tool_use',\r\n id: (toolUseBlock as any).id,\r\n name: (toolUseBlock as any).name,\r\n input: (toolUseBlock as any).input,\r\n };\r\n\r\n console.log(`[executeWithTools] Tool: ${toolUse.name}`);\r\n const result = await executeTool(toolUse);\r\n toolResults.push(result);\r\n\r\n // Stream tool result\r\n if (onChunk) {\r\n onChunk(`\\n[Tool: ${toolUse.name}] ${result.content.substring(0, 100)}${result.content.length > 100 ? '...' : ''}\\n`);\r\n }\r\n }\r\n\r\n // Add assistant message with tool_use\r\n messages.push({\r\n role: 'assistant',\r\n content: response.content as any,\r\n });\r\n\r\n // Add tool results as user message\r\n messages.push({\r\n role: 'user',\r\n content: toolResults as any,\r\n });\r\n\r\n // Continue to next iteration\r\n }\r\n\r\n // Reached max iterations\r\n console.warn(`[executeWithTools] Reached max iterations (${MAX_ITERATIONS})`);\r\n return {\r\n content: fullTextContent,\r\n usage: {\r\n inputTokens: totalInputTokens,\r\n outputTokens: totalOutputTokens,\r\n },\r\n stopReason: 'max_tokens',\r\n };\r\n}\r\n\r\n/**\r\n * Execute agent via API with full lifecycle\r\n */\r\nexport async function executeAgentAPI(\r\n agentType: string,\r\n agentId: string,\r\n model: string,\r\n prompt: string,\r\n systemPrompt?: string,\r\n messages?: Array<{ role: string; content: string }>, // Sprint 4: Conversation forking\r\n maxTokens?: number, // Sprint 6: Configurable token limit\r\n tools?: any[] // Tool definitions for agent capabilities\r\n): Promise<{ success: boolean; output: string; usage: any; error?: string }> {\r\n // Start heartbeat monitoring (declare at function scope for error handling)\r\n let heartbeatInterval: NodeJS.Timeout | null = null;\r\n const taskId = process.env.TASK_ID;\r\n\r\n try {\r\n console.log(`[anthropic-client] Executing agent: ${agentType}`);\r\n console.log(`[anthropic-client] Agent ID: ${agentId}`);\r\n if (messages && messages.length > 1) {\r\n console.log(`[anthropic-client] Continuing conversation (${messages.length} messages)`);\r\n }\r\n console.log('');\r\n\r\n if (taskId) {\r\n heartbeatInterval = setInterval(async () => {\r\n try {\r\n await execAsync(`redis-cli hset \"swarm:${taskId}:agent:${agentId}\" heartbeat \"${Date.now()}\" status \"working\"`);\r\n } catch (err) {\r\n console.error('[heartbeat] Error sending heartbeat:', err);\r\n }\r\n }, 30000); // Every 30 seconds\r\n\r\n console.log(`[heartbeat] Monitoring started for agent ${agentId} (30s interval)`);\r\n }\r\n\r\n let fullOutput = '';\r\n\r\n // If tools provided, use agentic loop with tool execution\r\n // Otherwise use simple streaming\r\n let response: MessageResponse;\r\n\r\n if (tools && tools.length > 0) {\r\n console.log(`[anthropic-client] Tools enabled: ${tools.map(t => t.name).join(', ')}`);\r\n response = await executeWithTools(\r\n {\r\n model,\r\n prompt,\r\n systemPrompt,\r\n messages,\r\n maxTokens,\r\n tools\r\n },\r\n (chunk) => {\r\n process.stdout.write(chunk);\r\n fullOutput += chunk;\r\n }\r\n );\r\n } else {\r\n response = await sendMessage(\r\n {\r\n model,\r\n prompt,\r\n systemPrompt,\r\n stream: true,\r\n messages,\r\n maxTokens,\r\n },\r\n (chunk) => {\r\n process.stdout.write(chunk);\r\n fullOutput += chunk;\r\n }\r\n );\r\n }\r\n\r\n console.log('\\n');\r\n console.log('=== Agent Execution Complete ===');\r\n console.log(`Input tokens: ${response.usage.inputTokens}`);\r\n console.log(`Output tokens: ${response.usage.outputTokens}`);\r\n console.log(`Stop reason: ${response.stopReason}`);\r\n\r\n // Stop heartbeat and send final status\r\n if (heartbeatInterval) {\r\n clearInterval(heartbeatInterval);\r\n\r\n if (taskId) {\r\n await execAsync(`redis-cli hset \"swarm:${taskId}:agent:${agentId}\" heartbeat \"${Date.now()}\" status \"complete\"`);\r\n console.log(`[heartbeat] Monitoring stopped - agent ${agentId} complete`);\r\n }\r\n }\r\n\r\n return {\r\n success: true,\r\n output: response.content,\r\n usage: response.usage,\r\n };\r\n } catch (error) {\r\n console.error('[anthropic-client] Error:', error);\r\n\r\n // Stop heartbeat and send error status\r\n if (heartbeatInterval) {\r\n clearInterval(heartbeatInterval);\r\n\r\n if (taskId) {\r\n try {\r\n await execAsync(`redis-cli hset \"swarm:${taskId}:agent:${agentId}\" heartbeat \"${Date.now()}\" status \"error\"`);\r\n console.log(`[heartbeat] Monitoring stopped - agent ${agentId} error`);\r\n } catch (err) {\r\n // Ignore heartbeat errors during error handling\r\n }\r\n }\r\n }\r\n\r\n return {\r\n success: false,\r\n output: '',\r\n usage: { inputTokens: 0, outputTokens: 0 },\r\n error: error instanceof Error ? error.message : String(error),\r\n };\r\n }\r\n}\r\n"],"names":["Anthropic","fs","path","exec","promisify","executeTool","execAsync","getAPIConfig","envProvider","process","env","CLAUDE_API_PROVIDER","provider","apiKey","ZAI_API_KEY","ANTHROPIC_API_KEY","baseURL","ZAI_BASE_URL","configPath","join","config","JSON","parse","readFile","createClient","Error","clientOptions","timeout","maxRetries","mapModelName","agentModel","zaiModelMap","haiku","sonnet","opus","modelMap","getFallbackModel","model","sendMessage","options","onChunk","client","maxTokens","temperature","enableStreaming","stream","console","log","messages","map","m","role","content","prompt","lastError","attempts","maxAttempts","currentModel","requestParams","max_tokens","systemPrompt","system","tools","length","fullContent","inputTokens","outputTokens","stopReason","create","event","type","message","usage","input_tokens","text","delta","output_tokens","stop_reason","response","filter","block","error","String","executeWithTools","totalInputTokens","totalOutputTokens","fullTextContent","MAX_ITERATIONS","iteration","textBlocks","toolUseBlocks","toolResults","toolUseBlock","toolUse","id","name","input","result","push","substring","warn","executeAgentAPI","agentType","agentId","heartbeatInterval","taskId","TASK_ID","setInterval","Date","now","err","fullOutput","t","chunk","stdout","write","clearInterval","success","output"],"mappings":"AAAA;;;;;CAKC,GAED,OAAOA,eAAe,oBAAoB;AAC1C,OAAOC,QAAQ,cAAc;AAC7B,OAAOC,UAAU,OAAO;AACxB,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,WAAW,QAAuC,qBAAqB;AAEhF,MAAMC,YAAYF,UAAUD;AA4B5B;;CAEC,GACD,OAAO,eAAeI;IACpB,6BA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KAAK,CAAC,6BAA6BA;QAE3C,uCAAuC;QACvC,IAAIuB,mBAAmB;YACrBY,cAAcZ;YAEd,IAAIC,QAAQ;gBACV,IAAI;oBACF,MAAMnG,UAAU,CAAC,sBAAsB,EAAEmG,OAAO,OAAO,EAAEF,QAAQ,aAAa,EAAEK,KAAKC,GAAG,GAAG,gBAAgB,CAAC;oBAC5G/D,QAAQC,GAAG,CAAC,CAAC,uCAAuC,EAAEwD,QAAQ,MAAM,CAAC;gBACvE,EAAE,OAAOO,KAAK;gBACZ,gDAAgD;gBAClD;YACF;QACF;QAEA,OAAO;YACLO,SAAS;YACTC,QAAQ;YACR9C,OAAO;gBAAEP,aAAa;gBAAGC,cAAc;YAAE;YACzCe,OAAOA,iBAAiBxD,QAAQwD,MAAMV,OAAO,GAAGW,OAAOD;QACzD;IACF;AACF"}
@@ -1,4 +1,154 @@
1
1
  #!/usr/bin/env node
2
+ import { exec } from 'child_process';
3
+ import { promisify } from 'util';
4
+ const execAsync = promisify(exec);
5
+ // ============================================================================
6
+ // Redis Epic Context Functions
7
+ // ============================================================================
8
+ /**
9
+ * Load epic context from Redis
10
+ *
11
+ * Redis key: swarm:{taskId}:epic-context
12
+ */ export async function loadEpicContext(taskId) {
13
+ try {
14
+ const { stdout } = await execAsync(`redis-cli get "swarm:${taskId}:epic-context"`);
15
+ const result = stdout.trim();
16
+ if (result === '(nil)' || !result) {
17
+ return null;
18
+ }
19
+ return JSON.parse(result);
20
+ } catch (error) {
21
+ console.warn(`[cfn-context] Failed to load epic context for task ${taskId}:`, error);
22
+ return null;
23
+ }
24
+ }
25
+ /**
26
+ * Load phase context from Redis
27
+ *
28
+ * Redis key: swarm:{taskId}:phase-context
29
+ */ export async function loadPhaseContext(taskId) {
30
+ try {
31
+ const { stdout } = await execAsync(`redis-cli get "swarm:${taskId}:phase-context"`);
32
+ const result = stdout.trim();
33
+ if (result === '(nil)' || !result) {
34
+ return null;
35
+ }
36
+ return JSON.parse(result);
37
+ } catch (error) {
38
+ console.warn(`[cfn-context] Failed to load phase context for task ${taskId}:`, error);
39
+ return null;
40
+ }
41
+ }
42
+ /**
43
+ * Load success criteria from Redis
44
+ *
45
+ * Redis key: swarm:{taskId}:success-criteria
46
+ */ export async function loadSuccessCriteria(taskId) {
47
+ try {
48
+ const { stdout } = await execAsync(`redis-cli get "swarm:${taskId}:success-criteria"`);
49
+ const result = stdout.trim();
50
+ if (result === '(nil)' || !result) {
51
+ return null;
52
+ }
53
+ return JSON.parse(result);
54
+ } catch (error) {
55
+ console.warn(`[cfn-context] Failed to load success criteria for task ${taskId}:`, error);
56
+ return null;
57
+ }
58
+ }
59
+ /**
60
+ * Store epic context to Redis
61
+ *
62
+ * Redis key: swarm:{taskId}:epic-context
63
+ * TTL: 7 days
64
+ */ export async function storeEpicContext(taskId, context) {
65
+ try {
66
+ const contextJson = JSON.stringify(context);
67
+ await execAsync(`redis-cli setex "swarm:${taskId}:epic-context" 604800 '${contextJson.replace(/'/g, "\\'")}'`);
68
+ console.log(`[cfn-context] Stored epic context for task ${taskId}`);
69
+ return true;
70
+ } catch (error) {
71
+ console.error(`[cfn-context] Failed to store epic context for task ${taskId}:`, error);
72
+ return false;
73
+ }
74
+ }
75
+ /**
76
+ * Store phase context to Redis
77
+ *
78
+ * Redis key: swarm:{taskId}:phase-context
79
+ * TTL: 7 days
80
+ */ export async function storePhaseContext(taskId, context) {
81
+ try {
82
+ const contextJson = JSON.stringify(context);
83
+ await execAsync(`redis-cli setex "swarm:${taskId}:phase-context" 604800 '${contextJson.replace(/'/g, "\\'")}'`);
84
+ console.log(`[cfn-context] Stored phase context for task ${taskId}`);
85
+ return true;
86
+ } catch (error) {
87
+ console.error(`[cfn-context] Failed to store phase context for task ${taskId}:`, error);
88
+ return false;
89
+ }
90
+ }
91
+ /**
92
+ * Store success criteria to Redis
93
+ *
94
+ * Redis key: swarm:{taskId}:success-criteria
95
+ * TTL: 7 days
96
+ */ export async function storeSuccessCriteria(taskId, criteria) {
97
+ try {
98
+ const criteriaJson = JSON.stringify(criteria);
99
+ await execAsync(`redis-cli setex "swarm:${taskId}:success-criteria" 604800 '${criteriaJson.replace(/'/g, "\\'")}'`);
100
+ console.log(`[cfn-context] Stored success criteria for task ${taskId}`);
101
+ return true;
102
+ } catch (error) {
103
+ console.error(`[cfn-context] Failed to store success criteria for task ${taskId}:`, error);
104
+ return false;
105
+ }
106
+ }
107
+ /**
108
+ * Format epic context as markdown for system prompt
109
+ */ export function formatEpicContextForPrompt(epic) {
110
+ if (!epic.epicGoal && !epic.inScope && !epic.outOfScope) {
111
+ return '';
112
+ }
113
+ const sections = [];
114
+ sections.push('## Epic Context');
115
+ sections.push('');
116
+ if (epic.epicName) {
117
+ sections.push(`**Epic:** ${epic.epicName}`);
118
+ sections.push('');
119
+ }
120
+ if (epic.epicGoal) {
121
+ sections.push('**Goal:**');
122
+ sections.push(epic.epicGoal);
123
+ sections.push('');
124
+ }
125
+ if (epic.currentPhase) {
126
+ sections.push(`**Current Phase:** ${epic.currentPhase}`);
127
+ sections.push('');
128
+ }
129
+ if (epic.inScope && epic.inScope.length > 0) {
130
+ sections.push('**In Scope:**');
131
+ for (const item of epic.inScope){
132
+ sections.push(`- ${item}`);
133
+ }
134
+ sections.push('');
135
+ }
136
+ if (epic.outOfScope && epic.outOfScope.length > 0) {
137
+ sections.push('**Out of Scope:**');
138
+ for (const item of epic.outOfScope){
139
+ sections.push(`- ${item}`);
140
+ }
141
+ sections.push('');
142
+ }
143
+ if (epic.references && epic.references.length > 0) {
144
+ sections.push('**References:**');
145
+ for (const ref of epic.references){
146
+ sections.push(`- ${ref}`);
147
+ }
148
+ sections.push('');
149
+ }
150
+ return sections.join('\n');
151
+ }
2
152
  function parseArgs(args) {
3
153
  const subcommand = args[0] || 'stats';
4
154
  let query;