claude-flow-novice 2.6.0 → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (364) hide show
  1. package/.claude/adaptive-context/cfn-v3-reflection.json +21 -0
  2. package/.claude/agents/AGENT_LIFECYCLE.md +495 -0
  3. package/.claude/agents/CLAUDE.md +1002 -995
  4. package/.claude/agents/accessibility-advocate.md +457 -0
  5. package/.claude/agents/agent-principles/README.md +226 -226
  6. package/.claude/agents/agent-principles/agent-type-guidelines.md +10 -0
  7. package/.claude/agents/agent-principles/format-selection.md +10 -0
  8. package/.claude/agents/agent-principles/phase4-template-optimization.md +502 -494
  9. package/.claude/agents/agent-principles/prompt-engineering.md +8 -0
  10. package/.claude/agents/agent-principles/quality-metrics.md +8 -0
  11. package/.claude/agents/analysis/code-analyzer.md +7 -17
  12. package/.claude/agents/analysis/code-review/analyze-code-quality.md +2 -104
  13. package/.claude/agents/analysis/perf-analyzer.md +2 -196
  14. package/.claude/agents/context/context-curator.md +78 -84
  15. package/.claude/agents/context/context-reflector.md +27 -81
  16. package/.claude/agents/coordinators/README.md +42 -0
  17. package/.claude/agents/coordinators/cfn-v3-coordinator.md +440 -0
  18. package/.claude/agents/{product-owner-team → coordinators}/cto-agent.md +154 -187
  19. package/.claude/agents/coordinators/multi-sprint-coordinator.md +50 -0
  20. package/.claude/agents/{product-owner-team → coordinators}/product-owner-agent.md +6 -39
  21. package/.claude/agents/{cfn-loop → coordinators}/product-owner.md +72 -17
  22. package/.claude/agents/core-agents/reviewer.md +114 -135
  23. package/.claude/agents/custom/agent-builder.md +637 -637
  24. package/.claude/agents/developers/README.md +69 -0
  25. package/.claude/agents/developers/backend-dev.md +77 -0
  26. package/.claude/agents/{core-agents → developers}/coder.md +131 -26
  27. package/.claude/agents/developers/react-frontend-engineer.md +121 -0
  28. package/.claude/agents/{frontend → developers}/state-architect.md +1 -0
  29. package/.claude/agents/{frontend → developers}/ui-designer.md +1 -0
  30. package/.claude/agents/development/backend/dev-backend-api.md +0 -29
  31. package/.claude/agents/development/npm-package-specialist.md +355 -347
  32. package/.claude/agents/documentation/api-docs/docs-api-openapi.md +8 -0
  33. package/.claude/agents/documentation/api-docs.md +8 -0
  34. package/.claude/agents/github/github-commit-agent.md +125 -117
  35. package/.claude/agents/goal/goal-planner.md +8 -0
  36. package/.claude/agents/infrastructure/README.md +100 -0
  37. package/.claude/agents/{specialized → infrastructure}/devops-engineer.md +131 -150
  38. package/.claude/agents/planners/README.md +94 -0
  39. package/.claude/agents/{core-agents → planners}/analyst.md +1 -22
  40. package/.claude/agents/{planning-team → planners}/api-designer-persona.md +8 -0
  41. package/.claude/agents/{core-agents → planners}/architect.md +7 -20
  42. package/.claude/agents/{core-agents → planners}/planner.md +0 -21
  43. package/.claude/agents/{planning-team → planners}/security-architect-persona.md +8 -28
  44. package/.claude/agents/{planning-team → planners}/system-architect-persona.md +6 -38
  45. package/.claude/agents/{architecture → planners}/system-architect.md +12 -17
  46. package/.claude/agents/product-owner-team/accessibility-advocate-persona.md +132 -161
  47. package/.claude/agents/product-owner-team/power-user-persona.md +149 -182
  48. package/.claude/agents/retrospective-analyst.md +84 -0
  49. package/.claude/agents/reviewers/README.md +58 -0
  50. package/.claude/agents/{analysis → reviewers}/code-quality-validator.md +8 -17
  51. package/.claude/agents/reviewers/reviewer.md +181 -0
  52. package/.claude/agents/sparc/architecture.md +6 -25
  53. package/.claude/agents/sparc/pseudocode.md +6 -0
  54. package/.claude/agents/sparc/refinement.md +6 -0
  55. package/.claude/agents/sparc/specification.md +1 -0
  56. package/.claude/agents/specialists/README.md +60 -0
  57. package/.claude/agents/{core-agents → specialists}/base-template-generator.md +8 -21
  58. package/.claude/agents/{specialized → specialists}/cli-agent-optimizer.md +1 -1
  59. package/.claude/agents/{specialized → specialists}/code-booster.md +1 -0
  60. package/.claude/agents/{consensus → specialists}/consensus-builder.md +1 -17
  61. package/.claude/agents/{specialized/mobile → specialists}/mobile-dev.md +0 -20
  62. package/.claude/agents/{core-agents → specialists}/performance-benchmarker.md +134 -148
  63. package/.claude/agents/{specialized → specialists}/rust-developer.md +1 -20
  64. package/.claude/agents/{specialized → specialists}/rust-enterprise-developer.md +1 -20
  65. package/.claude/agents/{specialized → specialists}/rust-mvp-developer.md +1 -20
  66. package/.claude/agents/{core-agents → specialists}/security-manager.md +68 -88
  67. package/.claude/agents/{security → specialists}/security-specialist-existing.md +6 -57
  68. package/.claude/agents/{security → specialists}/security-specialist.md +6 -30
  69. package/.claude/agents/{specialized/mobile → specialists}/spec-mobile-react-native.md +2 -21
  70. package/.claude/agents/testers/README.md +94 -0
  71. package/.claude/agents/{testing → testers}/e2e/playwright-agent.md +1 -20
  72. package/.claude/agents/{testing → testers}/interaction-tester.md +1 -20
  73. package/.claude/agents/{testing → testers}/playwright-tester.md +1 -1
  74. package/.claude/agents/testers/tester.md +139 -0
  75. package/.claude/agents/testers/unit/tdd-london-swarm.md +49 -0
  76. package/.claude/agents/testers/validation/production-validator.md +33 -0
  77. package/.claude/agents-ignore/cfn-loop-coordinator.md +157 -0
  78. package/.claude/agents-ignore/cfn-loop-coordinator.md.backup +156 -0
  79. package/.claude/agents-ignore/coordinator.md.backup +182 -0
  80. package/.claude/agents-ignore/cost-savings-cfn-loop-coordinator.md +760 -0
  81. package/.claude/agents-ignore/cost-savings-coordinator.md +173 -0
  82. package/.claude/artifacts/ace-reflections/REFLECT-001-summary.json +39 -0
  83. package/.claude/artifacts/ace-reflections/sprint-7_$(date -u +/"%Y%m%d_%H%M%S/").json" +47 -0
  84. package/.claude/commands/CFN_COORDINATOR_PARAMETERS.md +10 -10
  85. package/.claude/commands/cfn-loop-epic.md +3 -3
  86. package/.claude/commands/cfn-loop-single.md +3 -3
  87. package/.claude/commands/cfn-loop-sprints.md +1 -1
  88. package/.claude/commands/cfn-loop.md +3 -3
  89. package/.claude/commands/cfn-mode.md +20 -0
  90. package/.claude/commands/write-plan.md +104 -0
  91. package/.claude/data/cfn-loop.db +0 -0
  92. package/.claude/data/cfn_loop_logs.db +0 -0
  93. package/.claude/hooks/BACKUP_USAGE.md +243 -0
  94. package/.claude/hooks/post-edit-cfn-retrospective.sh +79 -0
  95. package/.claude/hooks/post-edit.sh +21 -0
  96. package/.claude/hooks/pre-edit-backup.sh +71 -0
  97. package/.claude/hooks/restore-from-backup.sh +37 -0
  98. package/.claude/prompts/cfn-loop-context.md +115 -0
  99. package/.claude/prompts/loop-specific/loop2.md +50 -0
  100. package/.claude/prompts/loop-specific/loop3.md +43 -0
  101. package/.claude/prompts/loop-specific/loop4.md +54 -0
  102. package/.claude/root-claude-distribute/CLAUDE.md +76 -2
  103. package/.claude/skills/ace-system/sprint-7-lessons.json +46 -0
  104. package/.claude/skills/ace-system/store-reflection.sh +33 -136
  105. package/.claude/skills/agent-discovery/SKILL.md +40 -0
  106. package/.claude/skills/agent-discovery/agents-registry-clean.json +0 -0
  107. package/.claude/skills/agent-discovery/agents-registry-fixed.json +19 -0
  108. package/.claude/skills/agent-discovery/agents-registry.json +718 -0
  109. package/.claude/skills/agent-discovery/discover-agents.py +175 -0
  110. package/.claude/skills/agent-discovery/discover-agents.sh +87 -0
  111. package/.claude/skills/agent-discovery/invoke-registry.sh +11 -0
  112. package/.claude/skills/agent-discovery/temp_script.py +0 -0
  113. package/.claude/skills/agent-output-processing/SKILL.md +359 -0
  114. package/.claude/skills/agent-selector/SKILL.md +90 -0
  115. package/.claude/skills/agent-selector/select-agents.sh +96 -0
  116. package/.claude/skills/agent-spawning/agent-selection-guide.md +1 -1
  117. package/.claude/skills/agent-swap/SKILL.md +36 -0
  118. package/.claude/skills/agent-swap/recommend-swap.sh +60 -0
  119. package/.claude/skills/api-validation/test-endpoints.sh +54 -0
  120. package/.claude/skills/automatic-memory-persistence/SKILL.md +73 -0
  121. package/.claude/skills/automatic-memory-persistence/persist-agent-output.sh +49 -0
  122. package/.claude/skills/automatic-memory-persistence/query-agent-history.sh +35 -0
  123. package/.claude/skills/automatic-memory-persistence/test-memory-persistence.sh +235 -0
  124. package/.claude/skills/cfn-loop-orchestration/README.md +41 -0
  125. package/.claude/skills/cfn-loop-orchestration/SKILL.md +299 -0
  126. package/.claude/skills/cfn-loop-orchestration/helpers/auto-tune-timeouts.sh +228 -0
  127. package/.claude/skills/cfn-loop-orchestration/helpers/consensus.sh +84 -0
  128. package/.claude/skills/cfn-loop-orchestration/helpers/deliverable-verifier.sh +71 -0
  129. package/.claude/skills/cfn-loop-orchestration/helpers/gate-check.sh +90 -0
  130. package/.claude/skills/cfn-loop-orchestration/helpers/iteration-manager.sh +87 -0
  131. package/.claude/skills/cfn-loop-orchestration/helpers/timeout-calculator.sh +51 -0
  132. package/.claude/skills/cfn-loop-orchestration/inject-loop-context.sh +41 -0
  133. package/.claude/skills/cfn-loop-orchestration/monitor-execution.sh +156 -0
  134. package/.claude/skills/cfn-loop-orchestration/orchestrate.sh +840 -0
  135. package/.claude/skills/cfn-loop-orchestration/security_utils.sh +99 -0
  136. package/.claude/skills/cfn-loop-orchestration/test-cfn-orchestration.sh +281 -0
  137. package/.claude/skills/cfn-loop-orchestration/test-edge-cases.sh +188 -0
  138. package/.claude/skills/cfn-loop-validation/SKILL.md +307 -217
  139. package/.claude/skills/complexity-estimator/SKILL.md +96 -0
  140. package/.claude/skills/complexity-estimator/estimate-complexity.sh +144 -0
  141. package/.claude/skills/context-pruner/SKILL.md +75 -0
  142. package/.claude/skills/context-pruner/prune-context.sh +73 -0
  143. package/.claude/skills/defense-in-depth/SKILL.md +133 -0
  144. package/.claude/skills/dependency-extractor/SKILL.md +35 -0
  145. package/.claude/skills/dependency-extractor/extract-dependencies.sh +66 -0
  146. package/.claude/skills/epic-decomposer/SKILL.md +44 -0
  147. package/.claude/skills/epic-decomposer/decompose-epic.sh +104 -0
  148. package/.claude/skills/improvement-recommender/SKILL.md +33 -0
  149. package/.claude/skills/improvement-recommender/recommend-improvements.sh +92 -0
  150. package/.claude/skills/intervention-detector/SKILL.md +39 -0
  151. package/.claude/skills/intervention-detector/detect-intervention.sh +111 -0
  152. package/.claude/skills/intervention-orchestrator/SKILL.md +43 -0
  153. package/.claude/skills/intervention-orchestrator/execute-intervention.sh +59 -0
  154. package/.claude/skills/loop2-output-processing/SKILL.md +163 -0
  155. package/.claude/skills/loop2-output-processing/execute-and-extract.sh +77 -0
  156. package/.claude/skills/loop2-output-processing/execute-and-extract.sh.backup +36 -0
  157. package/.claude/skills/loop2-output-processing/parse-feedback.sh +147 -0
  158. package/.claude/skills/loop2-output-processing/process-validator-output.sh +275 -0
  159. package/.claude/skills/loop2-output-processing/test-bug27-fix.sh +200 -0
  160. package/.claude/skills/loop2-output-processing/test-loop2-processing.sh +113 -0
  161. package/.claude/skills/loop3-output-processing/AGENT_COMPLETION_PROTOCOL.md +206 -0
  162. package/.claude/skills/loop3-output-processing/SKILL.md +421 -0
  163. package/.claude/skills/loop3-output-processing/calculate-confidence.sh +28 -0
  164. package/.claude/skills/loop3-output-processing/execute-and-extract.sh +85 -0
  165. package/.claude/skills/loop3-output-processing/parse-confidence.sh +31 -0
  166. package/.claude/skills/loop3-output-processing/test-agent-timeout.sh +327 -0
  167. package/.claude/skills/loop3-output-processing/test-loop3-processing.sh +155 -0
  168. package/.claude/skills/loop3-output-processing/verify-deliverables.sh +42 -0
  169. package/.claude/skills/pattern-extraction/SKILL.md +30 -0
  170. package/.claude/skills/pattern-extraction/extract-patterns.sh +80 -0
  171. package/.claude/skills/playbook/SKILL.md +113 -0
  172. package/.claude/skills/playbook/init-playbook.sh +54 -0
  173. package/.claude/skills/playbook/playbook.db +0 -0
  174. package/.claude/skills/playbook/query-playbook.sh +79 -0
  175. package/.claude/skills/playbook/update-playbook.sh +69 -0
  176. package/.claude/skills/playbook-auto-update/SKILL.md +29 -0
  177. package/.claude/skills/playbook-auto-update/auto-update-playbook.sh +86 -0
  178. package/.claude/skills/product-owner-decision/SKILL.md +332 -0
  179. package/.claude/skills/product-owner-decision/execute-decision.sh +176 -0
  180. package/.claude/skills/product-owner-decision/parse-decision.sh +66 -0
  181. package/.claude/skills/product-owner-decision/validate-deliverables.sh +82 -0
  182. package/.claude/skills/redis-coordination/LOGGING.md +260 -0
  183. package/.claude/skills/redis-coordination/README.md +30 -29
  184. package/.claude/skills/redis-coordination/SKILL.md +685 -83
  185. package/.claude/skills/redis-coordination/analyze-task-complexity.sh +277 -0
  186. package/.claude/skills/redis-coordination/cfn-loop-exec.sh +468 -0
  187. package/.claude/skills/redis-coordination/collect-confidence-scores.sh +179 -0
  188. package/.claude/skills/redis-coordination/collect-results.sh +75 -0
  189. package/.claude/skills/redis-coordination/data/cfn-loop.db +0 -0
  190. package/.claude/skills/redis-coordination/{test-orchestrator.sh → demos/test-orchestrator.sh} +25 -0
  191. package/.claude/skills/redis-coordination/execute-product-owner-decision.sh +258 -0
  192. package/.claude/skills/redis-coordination/get-agent-timeout.sh +176 -176
  193. package/.claude/skills/redis-coordination/invoke-waiting-mode.sh +93 -227
  194. package/.claude/skills/redis-coordination/invoke-waiting-mode.sh.backup-p7 +423 -0
  195. package/.claude/skills/redis-coordination/log-event.sh +109 -0
  196. package/.claude/skills/redis-coordination/monitor-cfn-violations.sh +391 -0
  197. package/.claude/skills/redis-coordination/orchestrate-cfn-loop-v3.sh +141 -0
  198. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh +31 -993
  199. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup +38 -0
  200. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-1761167675 +1672 -0
  201. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-p5 +1604 -0
  202. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-phase1 +1550 -0
  203. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-phase2 +1621 -0
  204. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-phase3 +1621 -0
  205. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.bak +0 -0
  206. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.broken +1627 -0
  207. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.corrupted +80 -0
  208. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.deprecated +1864 -0
  209. package/.claude/skills/redis-coordination/query-logs.sh +103 -0
  210. package/.claude/skills/redis-coordination/retrieve-context.sh +58 -0
  211. package/.claude/skills/redis-coordination/select-specialist-agent.sh +371 -0
  212. package/.claude/skills/redis-coordination/semantic-match-tfidf.py +252 -0
  213. package/.claude/skills/redis-coordination/send-heartbeat.sh +164 -72
  214. package/.claude/skills/redis-coordination/signal.sh +38 -0
  215. package/.claude/skills/redis-coordination/store-context.sh +86 -0
  216. package/.claude/skills/redis-coordination/test-context-injection.sh +354 -0
  217. package/.claude/skills/redis-coordination/test-timeout-enforcement.sh +513 -0
  218. package/.claude/skills/redis-coordination/tests/convert-line-endings.sh +15 -0
  219. package/.claude/skills/redis-coordination/tests/dlq-functionality-test.sh +101 -101
  220. package/.claude/skills/redis-coordination/tests/edge-cases-test.sh +98 -98
  221. package/.claude/skills/redis-coordination/tests/integration-test.sh +169 -169
  222. package/.claude/skills/redis-coordination/tests/retry-mechanism-test.sh +81 -81
  223. package/.claude/skills/redis-coordination/tests/run-test-suite.sh +91 -91
  224. package/.claude/skills/redis-coordination/tests/run-tests.sh +4 -0
  225. package/.claude/skills/redis-coordination/tests/test-primitives.sh +166 -0
  226. package/.claude/skills/redis-coordination/tests/test-utils.sh +53 -121
  227. package/.claude/skills/redis-coordination/tests/test_coordination_primitives.sh.deprecated +20 -0
  228. package/.claude/skills/redis-coordination/tests/test_utils.sh +49 -0
  229. package/.claude/skills/redis-coordination/v2_modularization/core_orchestration.sh +76 -0
  230. package/.claude/skills/redis-coordination/validate-parameters.sh +492 -0
  231. package/.claude/skills/retrospective-report/SKILL.md +31 -0
  232. package/.claude/skills/retrospective-report/generate-report.sh +101 -0
  233. package/.claude/skills/run-all-skill-tests.sh +124 -0
  234. package/.claude/skills/scope-simplifier/SKILL.md +37 -0
  235. package/.claude/skills/scope-simplifier/simplify-scope.sh +68 -0
  236. package/.claude/skills/simplified-agent-lifecycle/COST_ANALYSIS.md +49 -0
  237. package/.claude/skills/simplified-agent-lifecycle/DESIGN.md +98 -0
  238. package/.claude/skills/simplified-agent-lifecycle/MIGRATION_PLAN.md +74 -0
  239. package/.claude/skills/specialist-injection/SKILL.md +41 -0
  240. package/.claude/skills/specialist-injection/recommend-specialist.sh +57 -0
  241. package/.claude/skills/sprint-execution/SKILL.md +27 -0
  242. package/.claude/skills/sprint-execution/execute-sprint-task.sh +59 -0
  243. package/.claude/skills/sprint-execution/execute-sprint.sh +65 -0
  244. package/.claude/skills/sprint-planner/SKILL.md +37 -0
  245. package/.claude/skills/sprint-planner/plan-sprint.sh +85 -0
  246. package/.claude/skills/standardized-error-handling/SKILL.md +56 -0
  247. package/.claude/skills/standardized-error-handling/capture-agent-error.sh +87 -0
  248. package/.claude/skills/standardized-error-handling/test-error-handling.sh +166 -0
  249. package/.claude/skills/task-classifier/SKILL.md +94 -0
  250. package/.claude/skills/task-classifier/classify-task.sh +115 -0
  251. package/.claude/skills/validation-templates/SKILL.md +47 -0
  252. package/.claude/skills/validation-templates/content.json +38 -0
  253. package/.claude/skills/validation-templates/data.json +38 -0
  254. package/.claude/skills/validation-templates/design.json +38 -0
  255. package/.claude/skills/validation-templates/infrastructure.json +38 -0
  256. package/.claude/skills/validation-templates/research.json +38 -0
  257. package/.claude/skills/validation-templates/software.json +38 -0
  258. package/.claude/skills/webapp-testing/README.md +142 -0
  259. package/.claude/skills/webapp-testing/SCREENSHOT_NAMING_CONVENTION.md +547 -0
  260. package/.claude/skills/webapp-testing/SKILL.md +877 -0
  261. package/.claude/skills/webapp-testing/capture-screenshot.sh +238 -0
  262. package/.claude/skills/webapp-testing/cfn-loop-integration.sh +265 -0
  263. package/.claude/skills/webapp-testing/compare-screenshots.sh +199 -0
  264. package/.claude/skills/webapp-testing/init-storage.sh +150 -0
  265. package/.claude/skills/webapp-testing/set-baseline.sh +196 -0
  266. package/.claude/skills/webapp-testing/test-webapp-testing.sh +233 -0
  267. package/.claude/spawn-pattern-examples.md +3 -3
  268. package/CLAUDE.md +319 -45
  269. package/README.md +598 -251
  270. package/dist/agents/agent-loader.js +146 -165
  271. package/dist/agents/agent-loader.js.map +1 -1
  272. package/dist/cli/agent-command.js +2 -0
  273. package/dist/cli/agent-command.js.map +1 -1
  274. package/dist/cli/agent-definition-parser.js +7 -0
  275. package/dist/cli/agent-definition-parser.js.map +1 -1
  276. package/dist/cli/agent-executor.js +145 -11
  277. package/dist/cli/agent-executor.js.map +1 -1
  278. package/dist/cli/agent-prompt-builder.js +81 -1
  279. package/dist/cli/agent-prompt-builder.js.map +1 -1
  280. package/dist/cli/agent-spawn.js +10 -1
  281. package/dist/cli/agent-spawn.js.map +1 -1
  282. package/dist/cli/anthropic-client.js +192 -13
  283. package/dist/cli/anthropic-client.js.map +1 -1
  284. package/dist/cli/cfn-context.js +150 -0
  285. package/dist/cli/cfn-context.js.map +1 -1
  286. package/dist/cli/cfn-fork.js +159 -0
  287. package/dist/cli/cfn-fork.js.map +1 -0
  288. package/dist/cli/cli-agent-context.js +8 -3
  289. package/dist/cli/cli-agent-context.js.map +1 -1
  290. package/dist/cli/config-manager.js +109 -91
  291. package/dist/cli/config-manager.js.map +1 -1
  292. package/dist/cli/conversation-fork.js +201 -0
  293. package/dist/cli/conversation-fork.js.map +1 -0
  294. package/dist/cli/index.js +4 -0
  295. package/dist/cli/index.js.map +1 -1
  296. package/dist/cli/tool-definitions.js +263 -0
  297. package/dist/cli/tool-definitions.js.map +1 -0
  298. package/dist/cli/tool-executor.js +247 -0
  299. package/dist/cli/tool-executor.js.map +1 -0
  300. package/dist/hello.js +8 -0
  301. package/dist/hello.js.map +1 -0
  302. package/package.json +14 -6
  303. package/scripts/README.md +68 -0
  304. package/scripts/cfn-intervention-example.sh +21 -0
  305. package/scripts/migrate-test-infrastructure.sh +40 -0
  306. package/scripts/validate-test-migration.sh +49 -0
  307. package/scripts/verify-no-secrets.sh +55 -0
  308. package/.claude/agents/architecture/system-architect.md.backup +0 -603
  309. package/.claude/agents/code-booster.md +0 -131
  310. package/.claude/agents/consensus/performance-benchmarker.md +0 -101
  311. package/.claude/agents/consensus/security-manager.md +0 -107
  312. package/.claude/agents/context-curator.md +0 -167
  313. package/.claude/agents/context-reflector.md +0 -65
  314. package/.claude/agents/core-agents/cfn-loop-coordinator.md +0 -134
  315. package/.claude/agents/core-agents/code-quality-validator.md +0 -149
  316. package/.claude/agents/core-agents/context-curator.md +0 -452
  317. package/.claude/agents/core-agents/context-reflector.md +0 -273
  318. package/.claude/agents/core-agents/cost-savings-cfn-loop-coordinator.md +0 -235
  319. package/.claude/agents/core-agents/tester.md +0 -170
  320. package/.claude/agents/development/backend-dev.md +0 -165
  321. package/.claude/agents/devops/devops-engineer.md +0 -148
  322. package/.claude/agents/frontend/interaction-tester.md +0 -139
  323. package/.claude/agents/frontend/react-frontend-engineer.md +0 -9
  324. package/.claude/agents/personas/accessibility-advocate-persona.md +0 -107
  325. package/.claude/agents/testing/production-validator.md +0 -179
  326. package/.claude/agents/testing/tdd-london-swarm.md +0 -209
  327. package/.claude/agents/testing/unit/tdd-london-swarm.md +0 -43
  328. package/.claude/agents/testing/validation/production-validator.md +0 -43
  329. package/.claude/api-configs/config-current-zai-config.env +0 -62
  330. package/.claude/api-configs/config-test-zai-config.env +0 -62
  331. package/.claude/api-configs/env-backups/before-anthropic-20251020-025404.env +0 -62
  332. package/.claude/api-configs/env-backups/before-restore-20251020-025431.env +0 -62
  333. package/.claude/skills/redis-coordination/orchestrate-cfn-loop.sh.backup-1760949407 +0 -933
  334. package/dist/cli/cli-agent-context.test.js +0 -451
  335. package/dist/cli/cli-agent-context.test.js.map +0 -1
  336. package/dist/coordination/fleet-manager.test.js +0 -141
  337. package/dist/coordination/fleet-manager.test.js.map +0 -1
  338. package/dist/middleware/transparency-middleware.test.js +0 -184
  339. package/dist/middleware/transparency-middleware.test.js.map +0 -1
  340. /package/.claude/agents/{core-agents → developers}/researcher.md +0 -0
  341. /package/.claude/agents/{consensus → specialists}/crdt-synchronizer.md +0 -0
  342. /package/.claude/agents/{consensus → specialists}/quorum-manager.md +0 -0
  343. /package/.claude/agents/{consensus → specialists}/raft-manager.md +0 -0
  344. /package/.claude/{agents/core-agents → agents-ignore}/coordinator.md +0 -0
  345. /package/.claude/{agents/core-agents/cost-savings-coordinator.md → agents-ignore/cost-savings-coordinator.md.backup} +0 -0
  346. /package/.claude/skills/redis-coordination/{phase4-wake-queue-test-report.md → demos/phase4-wake-queue-test-report.md} +0 -0
  347. /package/.claude/skills/redis-coordination/{test-bzpopmin-fix.sh → demos/test-bzpopmin-fix.sh} +0 -0
  348. /package/.claude/skills/redis-coordination/{test-cancel-swarm.sh → demos/test-cancel-swarm.sh} +0 -0
  349. /package/.claude/skills/redis-coordination/{test-dlq.sh → demos/test-dlq.sh} +0 -0
  350. /package/.claude/skills/redis-coordination/{test-iteration-feedback.sh → demos/test-iteration-feedback.sh} +0 -0
  351. /package/.claude/skills/redis-coordination/{test-priority-wake-phase4-unix.sh → demos/test-priority-wake-phase4-unix.sh} +0 -0
  352. /package/.claude/skills/redis-coordination/{test-priority-wake-phase4.sh → demos/test-priority-wake-phase4.sh} +0 -0
  353. /package/.claude/skills/redis-coordination/{test-priority-wake.sh → demos/test-priority-wake.sh} +0 -0
  354. /package/.claude/skills/redis-coordination/{test-quick-fix.sh → demos/test-quick-fix.sh} +0 -0
  355. /package/.claude/skills/redis-coordination/{test-quorum-absolute.sh → demos/test-quorum-absolute.sh} +0 -0
  356. /package/.claude/skills/redis-coordination/{test-quorum-fallback.sh → demos/test-quorum-fallback.sh} +0 -0
  357. /package/.claude/skills/redis-coordination/{test-quorum-percentage.sh → demos/test-quorum-percentage.sh} +0 -0
  358. /package/.claude/skills/redis-coordination/{test-quorum-with-retry.sh → demos/test-quorum-with-retry.sh} +0 -0
  359. /package/.claude/skills/redis-coordination/{test-quorum.sh → demos/test-quorum.sh} +0 -0
  360. /package/.claude/skills/redis-coordination/{test-shutdown-handling.sh → demos/test-shutdown-handling.sh} +0 -0
  361. /package/.claude/skills/redis-coordination/{test-shutdown.sh → demos/test-shutdown.sh} +0 -0
  362. /package/.claude/skills/redis-coordination/{test-utils-unix.sh → demos/test-utils-unix.sh} +0 -0
  363. /package/.claude/skills/redis-coordination/{test-utils.sh → demos/test-utils.sh} +0 -0
  364. /package/.claude/skills/redis-coordination/{test-waiting-mode.sh → demos/test-waiting-mode.sh} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/agent-definition-parser.ts"],"sourcesContent":["/**\r\n * Agent Definition Parser\r\n *\r\n * Parses agent definition files (.md) with YAML frontmatter and markdown content.\r\n * Supports agent definitions in .claude/agents/ directory structure.\r\n */\r\n\r\nimport fs from 'fs/promises';\r\nimport path from 'path';\r\nimport { glob } from 'glob';\r\n\r\nexport interface AgentDefinition {\r\n // YAML frontmatter fields\r\n name: string;\r\n description: string;\r\n tools: string[];\r\n model: 'haiku' | 'sonnet' | 'opus';\r\n type?: string;\r\n color?: string;\r\n acl_level?: number;\r\n capabilities?: string[];\r\n validation_hooks?: string[];\r\n lifecycle?: {\r\n pre_task?: string;\r\n post_task?: string;\r\n };\r\n\r\n // Parsed markdown content\r\n content: string;\r\n\r\n // File metadata\r\n filePath: string;\r\n category?: string; // e.g., 'core-agents', 'specialized', 'custom'\r\n}\r\n\r\n/**\r\n * Parse YAML frontmatter from markdown content\r\n */\r\nfunction parseFrontmatter(content: string): { frontmatter: Record<string, any>; body: string } {\r\n const frontmatterRegex = /^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/;\r\n const match = content.match(frontmatterRegex);\r\n\r\n if (!match) {\r\n return { frontmatter: {}, body: content };\r\n }\r\n\r\n const [, yamlContent, body] = match;\r\n\r\n // Simple YAML parser (handles basic key-value pairs, arrays, and objects)\r\n const frontmatter: Record<string, any> = {};\r\n const lines = yamlContent.split('\\n');\r\n let currentKey = '';\r\n let currentArray: string[] = [];\r\n let isInArray = false;\r\n let isInObject = false;\r\n let currentObject: Record<string, string> = {};\r\n let objectKey = '';\r\n\r\n for (const line of lines) {\r\n const trimmed = line.trim();\r\n if (!trimmed || trimmed.startsWith('#')) continue;\r\n\r\n // Array item\r\n if (trimmed.startsWith('- ')) {\r\n if (!isInArray) {\r\n isInArray = true;\r\n currentArray = [];\r\n }\r\n currentArray.push(trimmed.substring(2).trim());\r\n continue;\r\n }\r\n\r\n // End of array\r\n if (isInArray && !trimmed.startsWith('- ')) {\r\n frontmatter[currentKey] = currentArray;\r\n isInArray = false;\r\n currentArray = [];\r\n }\r\n\r\n // Object field (indented key-value)\r\n if (trimmed.match(/^\\s+\\w+:/) && isInObject) {\r\n const [objKey, ...objValueParts] = trimmed.split(':');\r\n const objValue = objValueParts.join(':').trim().replace(/^[\"']|[\"']$/g, '');\r\n currentObject[objKey.trim()] = objValue;\r\n continue;\r\n }\r\n\r\n // Key-value pair\r\n const colonIndex = trimmed.indexOf(':');\r\n if (colonIndex !== -1) {\r\n const key = trimmed.substring(0, colonIndex).trim();\r\n const value = trimmed.substring(colonIndex + 1).trim();\r\n\r\n // Check if this starts an object\r\n if (value === '') {\r\n isInObject = true;\r\n currentObject = {};\r\n objectKey = key;\r\n continue;\r\n }\r\n\r\n // End previous object if any\r\n if (isInObject && !trimmed.match(/^\\s+/)) {\r\n frontmatter[objectKey] = currentObject;\r\n isInObject = false;\r\n currentObject = {};\r\n }\r\n\r\n currentKey = key;\r\n\r\n // Multi-line string (starts with |)\r\n if (value === '|') {\r\n continue; // Will be handled by next lines\r\n }\r\n\r\n // Remove quotes\r\n const cleanValue = value.replace(/^[\"']|[\"']$/g, '');\r\n frontmatter[key] = cleanValue;\r\n } else if (currentKey && trimmed && !isInArray && !isInObject) {\r\n // Continuation of multi-line string\r\n const existingValue = frontmatter[currentKey];\r\n frontmatter[currentKey] = existingValue\r\n ? `${existingValue}\\n${trimmed}`\r\n : trimmed;\r\n }\r\n }\r\n\r\n // Handle trailing array or object\r\n if (isInArray) {\r\n frontmatter[currentKey] = currentArray;\r\n }\r\n if (isInObject) {\r\n frontmatter[objectKey] = currentObject;\r\n }\r\n\r\n return { frontmatter, body: body.trim() };\r\n}\r\n\r\n/**\r\n * Find agent definition file by agent type/name\r\n */\r\nasync function findAgentFile(agentType: string, baseDir: string = '.claude/agents'): Promise<string | null> {\r\n // Normalize agent type (handle both kebab-case and underscores)\r\n const normalizedType = agentType.toLowerCase().replace(/_/g, '-');\r\n\r\n // Search patterns (in order of priority)\r\n const patterns = [\r\n // Exact match in any subdirectory\r\n `${baseDir}/**/${normalizedType}.md`,\r\n // Match with different casing\r\n `${baseDir}/**/*${normalizedType}*.md`,\r\n ];\r\n\r\n for (const pattern of patterns) {\r\n const files = await glob(pattern, { nodir: true, absolute: true });\r\n if (files.length > 0) {\r\n // Prefer exact match over partial match\r\n const exactMatch = files.find(f => {\r\n const basename = path.basename(f, '.md').toLowerCase();\r\n return basename === normalizedType;\r\n });\r\n return exactMatch || files[0];\r\n }\r\n }\r\n\r\n return null;\r\n}\r\n\r\n/**\r\n * Parse agent definition from file\r\n */\r\nexport async function parseAgentDefinition(agentType: string): Promise<AgentDefinition> {\r\n // Find agent file\r\n const filePath = await findAgentFile(agentType);\r\n\r\n if (!filePath) {\r\n throw new Error(`Agent definition not found: ${agentType}`);\r\n }\r\n\r\n // Read file content\r\n const content = await fs.readFile(filePath, 'utf-8');\r\n\r\n // Parse frontmatter and body\r\n const { frontmatter, body } = parseFrontmatter(content);\r\n\r\n // Extract category from path\r\n const relativePath = path.relative('.claude/agents', filePath);\r\n const category = relativePath.includes('/')\r\n ? relativePath.split('/')[0]\r\n : undefined;\r\n\r\n // Build agent definition\r\n const definition: AgentDefinition = {\r\n name: frontmatter.name || agentType,\r\n description: frontmatter.description || '',\r\n tools: Array.isArray(frontmatter.tools) ? frontmatter.tools : [],\r\n model: frontmatter.model || 'haiku',\r\n type: frontmatter.type,\r\n color: frontmatter.color,\r\n acl_level: frontmatter.acl_level ? parseInt(String(frontmatter.acl_level), 10) : undefined,\r\n capabilities: frontmatter.capabilities,\r\n validation_hooks: frontmatter.validation_hooks,\r\n lifecycle: frontmatter.lifecycle,\r\n content: body,\r\n filePath,\r\n category,\r\n };\r\n\r\n return definition;\r\n}\r\n\r\n/**\r\n * List all available agent definitions\r\n */\r\nexport async function listAgentDefinitions(baseDir: string = '.claude/agents'): Promise<string[]> {\r\n const pattern = `${baseDir}/**/*.md`;\r\n const files = await glob(pattern, { nodir: true });\r\n\r\n return files.map(f => path.basename(f, '.md'));\r\n}\r\n\r\n/**\r\n * Check if agent definition includes CFN Loop protocol\r\n */\r\nexport function hasCFNLoopProtocol(definition: AgentDefinition): boolean {\r\n const content = definition.content.toLowerCase();\r\n return (\r\n content.includes('cfn loop') &&\r\n content.includes('redis completion protocol') ||\r\n content.includes('invoke-waiting-mode.sh')\r\n );\r\n}\r\n"],"names":["fs","path","glob","parseFrontmatter","content","frontmatterRegex","match","frontmatter","body","yamlContent","lines","split","currentKey","currentArray","isInArray","isInObject","currentObject","objectKey","line","trimmed","trim","startsWith","push","substring","objKey","objValueParts","objValue","join","replace","colonIndex","indexOf","key","value","cleanValue","existingValue","findAgentFile","agentType","baseDir","normalizedType","toLowerCase","patterns","pattern","files","nodir","absolute","length","exactMatch","find","f","basename","parseAgentDefinition","filePath","Error","readFile","relativePath","relative","category","includes","undefined","definition","name","description","tools","Array","isArray","model","type","color","acl_level","parseInt","String","capabilities","validation_hooks","lifecycle","listAgentDefinitions","map","hasCFNLoopProtocol"],"mappings":"AAAA;;;;;CAKC,GAED,OAAOA,QAAQ,cAAc;AAC7B,OAAOC,UAAU,OAAO;AACxB,SAASC,IAAI,QAAQ,OAAO;AA0B5B;;CAEC,GACD,SAASC,iBAAiBC,OAAe;IACvC,MAAMC,mBAAmB;IACzB,MAAMC,QAAQF,QAAQE,KAAK,CAACD;IAE5B,IAAI,CAACC,OAAO;QACV,OAAO;YA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CrE,SAASI;QACT2C;QACAK;IACF;IAEA,OAAOG;AACT;AAEA;;CAEC,GACD,OAAO,eAAee,qBAAqBrC,UAAkB,gBAAgB;IAC3E,MAAMI,UAAU,GAAGJ,QAAQ,QAAQ,CAAC;IACpC,MAAMK,QAAQ,MAAMxC,KAAKuC,SAAS;QAAEE,OAAO;IAAK;IAEhD,OAAOD,MAAMiC,GAAG,CAAC3B,CAAAA,IAAK/C,KAAKgD,QAAQ,CAACD,GAAG;AACzC;AAEA;;CAEC,GACD,OAAO,SAAS4B,mBAAmBjB,UAA2B;IAC5D,MAAMvD,UAAUuD,WAAWvD,OAAO,CAACmC,WAAW;IAC9C,OACEnC,QAAQqD,QAAQ,CAAC,eACjBrD,QAAQqD,QAAQ,CAAC,gCACjBrD,QAAQqD,QAAQ,CAAC;AAErB"}
1
+ {"version":3,"sources":["../../src/cli/agent-definition-parser.ts"],"sourcesContent":["/**\r\n * Agent Definition Parser\r\n *\r\n * Parses agent definition files (.md) with YAML frontmatter and markdown content.\r\n * Supports agent definitions in .claude/agents/ directory structure.\r\n */\r\n\r\nimport fs from 'fs/promises';\r\nimport path from 'path';\r\nimport { glob } from 'glob';\r\n\r\nexport interface AgentDefinition {\r\n // YAML frontmatter fields\r\n name: string;\r\n description: string;\r\n tools: string[];\r\n model: 'haiku' | 'sonnet' | 'opus';\r\n type?: string;\r\n color?: string;\r\n acl_level?: number;\r\n capabilities?: string[];\r\n validation_hooks?: string[];\r\n lifecycle?: {\r\n pre_task?: string;\r\n post_task?: string;\r\n };\r\n\r\n // Parsed markdown content\r\n content: string;\r\n\r\n // File metadata\r\n filePath: string;\r\n category?: string; // e.g., 'core-agents', 'specialized', 'custom'\r\n}\r\n\r\n/**\r\n * Parse YAML frontmatter from markdown content\r\n */\r\nfunction parseFrontmatter(content: string): { frontmatter: Record<string, any>; body: string } {\r\n const frontmatterRegex = /^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/;\r\n const match = content.match(frontmatterRegex);\r\n\r\n if (!match) {\r\n return { frontmatter: {}, body: content };\r\n }\r\n\r\n const [, yamlContent, body] = match;\r\n\r\n // Simple YAML parser (handles basic key-value pairs, arrays, and objects)\r\n const frontmatter: Record<string, any> = {};\r\n const lines = yamlContent.split('\\n');\r\n let currentKey = '';\r\n let currentArray: string[] = [];\r\n let isInArray = false;\r\n let isInObject = false;\r\n let currentObject: Record<string, string> = {};\r\n let objectKey = '';\r\n\r\n for (const line of lines) {\r\n const trimmed = line.trim();\r\n if (!trimmed || trimmed.startsWith('#')) continue;\r\n\r\n // Array item\r\n if (trimmed.startsWith('- ')) {\r\n if (!isInArray) {\r\n isInArray = true;\r\n currentArray = [];\r\n }\r\n currentArray.push(trimmed.substring(2).trim());\r\n continue;\r\n }\r\n\r\n // End of array\r\n if (isInArray && !trimmed.startsWith('- ')) {\r\n frontmatter[currentKey] = currentArray;\r\n isInArray = false;\r\n currentArray = [];\r\n }\r\n\r\n // Object field (indented key-value)\r\n if (trimmed.match(/^\\s+\\w+:/) && isInObject) {\r\n const [objKey, ...objValueParts] = trimmed.split(':');\r\n const objValue = objValueParts.join(':').trim().replace(/^[\"']|[\"']$/g, '');\r\n currentObject[objKey.trim()] = objValue;\r\n continue;\r\n }\r\n\r\n // Key-value pair\r\n const colonIndex = trimmed.indexOf(':');\r\n if (colonIndex !== -1) {\r\n const key = trimmed.substring(0, colonIndex).trim();\r\n const value = trimmed.substring(colonIndex + 1).trim();\r\n\r\n // Check if this starts an object\r\n if (value === '') {\r\n isInObject = true;\r\n currentObject = {};\r\n objectKey = key;\r\n continue;\r\n }\r\n\r\n // End previous object if any\r\n if (isInObject && !trimmed.match(/^\\s+/)) {\r\n frontmatter[objectKey] = currentObject;\r\n isInObject = false;\r\n currentObject = {};\r\n }\r\n\r\n currentKey = key;\r\n\r\n // Multi-line string (starts with |)\r\n if (value === '|') {\r\n continue; // Will be handled by next lines\r\n }\r\n\r\n // Inline array (e.g., [item1, item2, item3])\r\n if (value.startsWith('[') && value.endsWith(']')) {\r\n const arrayContent = value.substring(1, value.length - 1);\r\n const items = arrayContent.split(',').map(item => item.trim());\r\n frontmatter[key] = items;\r\n continue;\r\n }\r\n\r\n // Remove quotes\r\n const cleanValue = value.replace(/^[\"']|[\"']$/g, '');\r\n frontmatter[key] = cleanValue;\r\n } else if (currentKey && trimmed && !isInArray && !isInObject) {\r\n // Continuation of multi-line string\r\n const existingValue = frontmatter[currentKey];\r\n frontmatter[currentKey] = existingValue\r\n ? `${existingValue}\\n${trimmed}`\r\n : trimmed;\r\n }\r\n }\r\n\r\n // Handle trailing array or object\r\n if (isInArray) {\r\n frontmatter[currentKey] = currentArray;\r\n }\r\n if (isInObject) {\r\n frontmatter[objectKey] = currentObject;\r\n }\r\n\r\n return { frontmatter, body: body.trim() };\r\n}\r\n\r\n/**\r\n * Find agent definition file by agent type/name\r\n */\r\nasync function findAgentFile(agentType: string, baseDir: string = '.claude/agents'): Promise<string | null> {\r\n // Normalize agent type (handle both kebab-case and underscores)\r\n const normalizedType = agentType.toLowerCase().replace(/_/g, '-');\r\n\r\n // Search patterns (in order of priority)\r\n const patterns = [\r\n // Exact match in any subdirectory\r\n `${baseDir}/**/${normalizedType}.md`,\r\n // Match with different casing\r\n `${baseDir}/**/*${normalizedType}*.md`,\r\n ];\r\n\r\n for (const pattern of patterns) {\r\n const files = await glob(pattern, { nodir: true, absolute: true });\r\n if (files.length > 0) {\r\n // Prefer exact match over partial match\r\n const exactMatch = files.find(f => {\r\n const basename = path.basename(f, '.md').toLowerCase();\r\n return basename === normalizedType;\r\n });\r\n return exactMatch || files[0];\r\n }\r\n }\r\n\r\n return null;\r\n}\r\n\r\n/**\r\n * Parse agent definition from file\r\n */\r\nexport async function parseAgentDefinition(agentType: string): Promise<AgentDefinition> {\r\n // Find agent file\r\n const filePath = await findAgentFile(agentType);\r\n\r\n if (!filePath) {\r\n throw new Error(`Agent definition not found: ${agentType}`);\r\n }\r\n\r\n // Read file content\r\n const content = await fs.readFile(filePath, 'utf-8');\r\n\r\n // Parse frontmatter and body\r\n const { frontmatter, body } = parseFrontmatter(content);\r\n\r\n // Extract category from path\r\n const relativePath = path.relative('.claude/agents', filePath);\r\n const category = relativePath.includes('/')\r\n ? relativePath.split('/')[0]\r\n : undefined;\r\n\r\n // Build agent definition\r\n const definition: AgentDefinition = {\r\n name: frontmatter.name || agentType,\r\n description: frontmatter.description || '',\r\n tools: Array.isArray(frontmatter.tools) ? frontmatter.tools : [],\r\n model: frontmatter.model || 'haiku',\r\n type: frontmatter.type,\r\n color: frontmatter.color,\r\n acl_level: frontmatter.acl_level ? parseInt(String(frontmatter.acl_level), 10) : undefined,\r\n capabilities: frontmatter.capabilities,\r\n validation_hooks: frontmatter.validation_hooks,\r\n lifecycle: frontmatter.lifecycle,\r\n content: body,\r\n filePath,\r\n category,\r\n };\r\n\r\n return definition;\r\n}\r\n\r\n/**\r\n * List all available agent definitions\r\n */\r\nexport async function listAgentDefinitions(baseDir: string = '.claude/agents'): Promise<string[]> {\r\n const pattern = `${baseDir}/**/*.md`;\r\n const files = await glob(pattern, { nodir: true });\r\n\r\n return files.map(f => path.basename(f, '.md'));\r\n}\r\n\r\n/**\r\n * Check if agent definition includes CFN Loop protocol\r\n */\r\nexport function hasCFNLoopProtocol(definition: AgentDefinition): boolean {\r\n const content = definition.content.toLowerCase();\r\n return (\r\n content.includes('cfn loop') &&\r\n content.includes('redis completion protocol') ||\r\n content.includes('invoke-waiting-mode.sh')\r\n );\r\n}\r\n"],"names":["fs","path","glob","parseFrontmatter","content","frontmatterRegex","match","frontmatter","body","yamlContent","lines","split","currentKey","currentArray","isInArray","isInObject","currentObject","objectKey","line","trimmed","trim","startsWith","push","substring","objKey","objValueParts","objValue","join","replace","colonIndex","indexOf","key","value","endsWith","arrayContent","length","items","map","item","cleanValue","existingValue","findAgentFile","agentType","baseDir","normalizedType","toLowerCase","patterns","pattern","files","nodir","absolute","exactMatch","find","f","basename","parseAgentDefinition","filePath","Error","readFile","relativePath","relative","category","includes","undefined","definition","name","description","tools","Array","isArray","model","type","color","acl_level","parseInt","String","capabilities","validation_hooks","lifecycle","listAgentDefinitions","hasCFNLoopProtocol"],"mappings":"AAAA;;;;;CAKC,GAED,OAAOA,QAAQ,cAAc;AAC7B,OAAOC,UAAU,OAAO;AACxB,SAASC,IAAI,QAAQ,OAAO;AA0B5B;;CAEC,GACD,SAASC,iBAAiBC,OAAe;IACvC,MAAMC,mBAAmB;IACzB,MAAMC,QAAQF,QAAQE,KAAK,CAACD;IAE5B,IAAI,CAACC,OAAO;QACV,OAAO;YAAEC,aAAa,CAAC;YAAGC,MAAMJ;QAAQ;IAC1C;IAEA,MAAM,GAAGK,aAAaD,KAAK,GAAGF;IAE9B,0EAA0E;IAC1E,MAAMC,cAAmC,CAAC;IAC1C,MAAMG,QAAQD,YAAYE,KAAK,CAAC;IAChC,IAAIC,aAAa;IACjB,IAAIC,eAAyB,EAAE;IAC/B,IAAIC,YAAY;IAChB,IAAIC,aAAa;IACjB,IAAIC,gBAAwC,CAAC;IAC7C,IAAIC,YAAY;IAEhB,KAAK,MAAMC,QAAQR,MAAO;QACxB,MAAMS,UAAUD,KAAKE,IAAI;QACzB,IAAI,CAACD,WAAWA,QAAQE,UAAU,CAAC,MAAM;QAEzC,aAAa;QACb,IAAIF,QAAQE,UAAU,CAAC,OAAO;YAC5B,IAAI,CAACP,WAAW;gBACdA,YAAY;gBACZD,eAAe,EAAE;YACnB;YACAA,aAAaS,IAAI,CAACH,QAAQI,SAAS,CAAC,GAAGH,IAAI;YAC3C;QACF;QAEA,eAAe;QACf,IAAIN,aAAa,CAACK,QAAQE,UAAU,CAAC,OAAO;YAC1Cd,WAAW,CAACK,WAAW,GAAGC;YAC1BC,YAAY;YACZD,eAAe,EAAE;QACnB;QAEA,oCAAoC;QACpC,IAAIM,QAAQb,KAAK,CAAC,eAAeS,YAAY;YAC3C,MAAM,CAACS,QAAQ,GAAGC,cAAc,GAAGN,QAAQR,KAAK,CAAC;YACjD,MAAMe,WAAWD,cAAcE,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';
9
+ import { exec } from 'child_process';
10
+ import { promisify } from 'util';
9
11
  import { getAgentId } from './agent-prompt-builder.js';
10
12
  import { buildCLIAgentSystemPrompt, loadContextFromEnv } from './cli-agent-context.js';
13
+ import { loadMessages, storeMessage, getCurrentFork, formatMessagesForAPI } from './conversation-fork.js';
14
+ import { convertToolNames } from './tool-definitions.js';
11
15
  import fs from 'fs/promises';
12
16
  import path from 'path';
13
17
  import os from 'os';
18
+ const execAsync = promisify(exec);
19
+ /**
20
+ * Extract confidence score from agent output
21
+ * Looks for patterns like:
22
+ * - "confidence: 0.85"
23
+ * - "Confidence: 0.90"
24
+ * - "confidence score: 0.95"
25
+ * - "self-confidence: 0.88"
26
+ */ function extractConfidence(output) {
27
+ if (!output) return 0.85;
28
+ // Try multiple patterns
29
+ const patterns = [
30
+ /confidence:\s*([0-9.]+)/i,
31
+ /confidence\s+score:\s*([0-9.]+)/i,
32
+ /self-confidence:\s*([0-9.]+)/i,
33
+ /my\s+confidence:\s*([0-9.]+)/i
34
+ ];
35
+ for (const pattern of patterns){
36
+ const match = output.match(pattern);
37
+ if (match && match[1]) {
38
+ const score = parseFloat(match[1]);
39
+ if (score >= 0 && score <= 1) {
40
+ return score;
41
+ }
42
+ }
43
+ }
44
+ // Default to 0.85 if not found
45
+ return 0.85;
46
+ }
47
+ /**
48
+ * Execute CFN Loop protocol after agent completes work
49
+ *
50
+ * Steps:
51
+ * 1. Signal completion to orchestrator
52
+ * 2. Report confidence score
53
+ * 3. Enter waiting mode (if iterations enabled)
54
+ */ async function executeCFNProtocol(taskId, agentId, output, iteration, enableIterations = false, maxIterations = 10) {
55
+ console.log(`\n[CFN Protocol] Starting for agent ${agentId}`);
56
+ console.log(`[CFN Protocol] Task ID: ${taskId}, Iteration: ${iteration}`);
57
+ try {
58
+ // Step 1: Signal completion
59
+ console.log('[CFN Protocol] Step 1: Signaling completion...');
60
+ await execAsync(`redis-cli lpush "swarm:${taskId}:${agentId}:done" "complete"`);
61
+ console.log('[CFN Protocol] ✓ Completion signaled');
62
+ // Step 2: Extract and report confidence
63
+ const confidence = extractConfidence(output);
64
+ console.log(`[CFN Protocol] Step 2: Reporting confidence (${confidence})...`);
65
+ const reportCmd = `./.claude/skills/redis-coordination/invoke-waiting-mode.sh report \
66
+ --task-id "${taskId}" \
67
+ --agent-id "${agentId}" \
68
+ --confidence ${confidence} \
69
+ --iteration ${iteration}`;
70
+ await execAsync(reportCmd);
71
+ console.log('[CFN Protocol] ✓ Confidence reported');
72
+ // Step 3: Exit cleanly (BUG #18 FIX - removed waiting mode)
73
+ // Orchestrator will spawn appropriate specialist agent for next iteration
74
+ // This enables adaptive agent specialization based on feedback type
75
+ console.log('[CFN Protocol] Step 3: Exiting cleanly (iteration complete)');
76
+ console.log('[CFN Protocol] Protocol complete\n');
77
+ } catch (error) {
78
+ console.error('[CFN Protocol] Error:', error);
79
+ throw error;
80
+ }
81
+ }
14
82
  /**
15
83
  * Check if custom routing (z.ai) is enabled
16
84
  */ async function isCustomRoutingEnabled() {
@@ -42,20 +110,86 @@ import os from 'os';
42
110
  console.log(`[agent-executor] Model: ${definition.model}`);
43
111
  console.log('');
44
112
  try {
45
- // Build system prompt with natural language context (Phase 1 enhancement)
46
- console.log('[agent-executor] Building system prompt with context...');
47
- const contextOptions = loadContextFromEnv();
48
- // Override agent type with definition name
49
- contextOptions.agentType = definition.name;
50
- // Override iteration/taskId if provided in context
51
- if (context.taskId) contextOptions.taskId = context.taskId;
52
- if (context.iteration) contextOptions.iteration = context.iteration;
53
- const systemPrompt = await buildCLIAgentSystemPrompt(contextOptions);
54
- console.log('[agent-executor] System prompt built successfully');
113
+ // Check for conversation fork (Sprint 4 enhancement)
114
+ const forkId = process.env.FORK_ID || await getCurrentFork(context.taskId || '', agentId);
115
+ const iteration = context.iteration || 1;
116
+ let systemPrompt;
117
+ let messages = [];
118
+ if (forkId && iteration > 1) {
119
+ // Continue from fork (iterations 2+)
120
+ console.log(`[agent-executor] Continuing from fork: ${forkId}`);
121
+ // Load fork messages
122
+ const forkMessages = await loadMessages(context.taskId || '', agentId, forkId);
123
+ console.log(`[agent-executor] Loaded ${forkMessages.length} messages from fork`);
124
+ // Extract system prompt from first message (it's always the system message)
125
+ // The fork messages are assistant/user pairs, we need to add system separately
126
+ systemPrompt = forkMessages[0]?.content || '';
127
+ // Format remaining messages for API
128
+ messages = formatMessagesForAPI(forkMessages.slice(1));
129
+ // Add new user message with feedback
130
+ messages.push({
131
+ role: 'user',
132
+ content: prompt
133
+ });
134
+ console.log(`[agent-executor] Fork continuation: ${messages.length} messages`);
135
+ } else {
136
+ // New conversation (iteration 1)
137
+ console.log('[agent-executor] Starting new conversation');
138
+ console.log('[agent-executor] Building system prompt with context...');
139
+ const contextOptions = loadContextFromEnv();
140
+ contextOptions.agentType = definition.name;
141
+ if (context.taskId) contextOptions.taskId = context.taskId;
142
+ if (context.iteration) contextOptions.iteration = context.iteration;
143
+ systemPrompt = await buildCLIAgentSystemPrompt(contextOptions);
144
+ console.log('[agent-executor] System prompt built successfully');
145
+ // Initial user message
146
+ messages = [
147
+ {
148
+ role: 'user',
149
+ content: prompt
150
+ }
151
+ ];
152
+ }
55
153
  console.log('');
56
154
  // Dynamic import to avoid bundling issues
57
155
  const { executeAgentAPI } = await import('./anthropic-client.js');
58
- const result = await executeAgentAPI(definition.name, agentId, definition.model, prompt, systemPrompt);
156
+ // Convert agent tool names to Anthropic API format
157
+ const tools = definition.tools && definition.tools.length > 0 ? convertToolNames(definition.tools) : undefined;
158
+ const result = await executeAgentAPI(definition.name, agentId, definition.model, prompt, systemPrompt, messages.length > 1 ? messages : undefined, undefined, tools // Pass converted tools
159
+ );
160
+ // Store messages in conversation history (for future forking)
161
+ if (context.taskId) {
162
+ // Store user message
163
+ const userMessage = {
164
+ role: 'user',
165
+ content: prompt,
166
+ iteration,
167
+ timestamp: new Date().toISOString()
168
+ };
169
+ await storeMessage(context.taskId, agentId, userMessage);
170
+ // Store assistant response
171
+ if (result.output) {
172
+ const assistantMessage = {
173
+ role: 'assistant',
174
+ content: result.output,
175
+ iteration,
176
+ timestamp: new Date().toISOString()
177
+ };
178
+ await storeMessage(context.taskId, agentId, assistantMessage);
179
+ }
180
+ console.log(`[agent-executor] Stored messages for iteration ${iteration}`);
181
+ // Execute CFN Loop protocol (signal completion, report confidence, enter waiting mode)
182
+ // Iterations are enabled for CFN Loop tasks (indicated by presence of taskId)
183
+ try {
184
+ const maxIterations = 10; // Default max iterations
185
+ const enableIterations = true; // Enable iterations for all CFN Loop tasks
186
+ await executeCFNProtocol(context.taskId, agentId, result.output, iteration, enableIterations, maxIterations);
187
+ } catch (error) {
188
+ console.error('[agent-executor] CFN Protocol execution failed:', error);
189
+ // Don't fail the entire agent execution if CFN protocol fails
190
+ // This allows agents to complete even if Redis coordination has issues
191
+ }
192
+ }
59
193
  return {
60
194
  success: result.success,
61
195
  agentId,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/agent-executor.ts"],"sourcesContent":["/**\r\n * Agent Executor\r\n *\r\n * Executes CLI-spawned agents by:\r\n * 1. Checking custom routing configuration (z.ai vs Anthropic)\r\n * 2. Invoking the appropriate API\r\n * 3. Managing agent lifecycle and output\r\n */\r\n\r\nimport { spawn } from 'child_process';\r\nimport { AgentDefinition } from './agent-definition-parser.js';\r\nimport { TaskContext, getAgentId } from './agent-prompt-builder.js';\r\nimport { buildCLIAgentSystemPrompt, loadContextFromEnv } from './cli-agent-context.js';\r\nimport fs from 'fs/promises';\r\nimport path from 'path';\r\nimport os from 'os';\r\n\r\nexport interface AgentExecutionResult {\r\n success: boolean;\r\n agentId: string;\r\n output?: string;\r\n error?: string;\r\n exitCode: number;\r\n}\r\n\r\n/**\r\n * Check if custom routing (z.ai) is enabled\r\n */\r\nasync function isCustomRoutingEnabled(): Promise<boolean> {\r\n // Check environment variable\r\n if (process.env.CLAUDE_API_PROVIDER === 'zai') {\r\n return true;\r\n }\r\n\r\n // Check config file (.claude/config/api-provider.json)\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 return config.provider === 'zai' || config.provider === 'z.ai';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Get API provider configuration\r\n */\r\nasync function getAPIProvider(): Promise<'anthropic' | 'zai'> {\r\n const customEnabled = await isCustomRoutingEnabled();\r\n return customEnabled ? 'zai' : 'anthropic';\r\n}\r\n\r\n/**\r\n * Execute agent using direct API calls\r\n */\r\nasync function executeViaAPI(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext\r\n): Promise<AgentExecutionResult> {\r\n const agentId = getAgentId(definition, context);\r\n\r\n console.log(`[agent-executor] Executing agent via API: ${definition.name}`);\r\n console.log(`[agent-executor] Agent ID: ${agentId}`);\r\n console.log(`[agent-executor] Model: ${definition.model}`);\r\n console.log('');\r\n\r\n try {\r\n // Build system prompt with natural language context (Phase 1 enhancement)\r\n console.log('[agent-executor] Building system prompt with context...');\r\n const contextOptions = loadContextFromEnv();\r\n // Override agent type with definition name\r\n contextOptions.agentType = definition.name;\r\n // Override iteration/taskId if provided in context\r\n if (context.taskId) contextOptions.taskId = context.taskId;\r\n if (context.iteration) contextOptions.iteration = context.iteration;\r\n\r\n const systemPrompt = await buildCLIAgentSystemPrompt(contextOptions);\r\n console.log('[agent-executor] System prompt built successfully');\r\n console.log('');\r\n\r\n // Dynamic import to avoid bundling issues\r\n const { executeAgentAPI } = await import('./anthropic-client.js');\r\n\r\n const result = await executeAgentAPI(\r\n definition.name,\r\n agentId,\r\n definition.model,\r\n prompt,\r\n systemPrompt\r\n );\r\n\r\n return {\r\n success: result.success,\r\n agentId,\r\n output: result.output,\r\n error: result.error,\r\n exitCode: result.success ? 0 : 1,\r\n };\r\n } catch (error) {\r\n console.error('[agent-executor] API execution failed:', error);\r\n return {\r\n success: false,\r\n agentId,\r\n error: error instanceof Error ? error.message : String(error),\r\n exitCode: 1,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Execute agent using shell script (fallback/simulation)\r\n */\r\nasync function executeViaScript(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext\r\n): Promise<AgentExecutionResult> {\r\n const agentId = getAgentId(definition, context);\r\n\r\n // Write prompt to temporary file\r\n const tmpDir = os.tmpdir();\r\n const promptFile = path.join(tmpDir, `agent-${agentId}-${Date.now()}.md`);\r\n await fs.writeFile(promptFile, prompt, 'utf-8');\r\n\r\n console.log(`[agent-executor] Executing agent via script: ${definition.name}`);\r\n console.log(`[agent-executor] Agent ID: ${agentId}`);\r\n console.log(`[agent-executor] Model: ${definition.model}`);\r\n console.log(`[agent-executor] Prompt file: ${promptFile}`);\r\n\r\n return new Promise((resolve) => {\r\n const scriptPath = path.join('.claude', 'skills', 'agent-execution', 'execute-agent.sh');\r\n\r\n // Build environment variables\r\n const env = {\r\n ...process.env,\r\n AGENT_TYPE: definition.name,\r\n AGENT_ID: agentId,\r\n AGENT_MODEL: definition.model,\r\n AGENT_TOOLS: definition.tools.join(','),\r\n TASK_ID: context.taskId || '',\r\n ITERATION: String(context.iteration || 1),\r\n MODE: context.mode || 'cli',\r\n PROMPT_FILE: promptFile,\r\n };\r\n\r\n // Check if execute script exists\r\n fs.access(scriptPath)\r\n .then(() => {\r\n // Use execution script\r\n const proc = spawn('bash', [scriptPath], { env, stdio: 'inherit' });\r\n\r\n proc.on('exit', (code) => {\r\n resolve({\r\n success: code === 0,\r\n agentId,\r\n exitCode: code || 0,\r\n });\r\n });\r\n\r\n proc.on('error', (err) => {\r\n resolve({\r\n success: false,\r\n agentId,\r\n error: err.message,\r\n exitCode: 1,\r\n });\r\n });\r\n })\r\n .catch(() => {\r\n // Fallback: Print prompt\r\n console.log('\\n=== Agent Prompt ===');\r\n console.log(prompt.substring(0, 500) + '...');\r\n console.log('\\n[agent-executor] Execution script not found');\r\n console.log('[agent-executor] Using simulation mode\\n');\r\n\r\n resolve({\r\n success: true,\r\n agentId,\r\n output: prompt,\r\n exitCode: 0,\r\n });\r\n });\r\n });\r\n}\r\n\r\n/**\r\n * Main agent execution function\r\n */\r\nexport async function executeAgent(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext,\r\n options: {\r\n method?: 'auto' | 'api' | 'script';\r\n } = {}\r\n): Promise<AgentExecutionResult> {\r\n const method = options.method || 'auto';\r\n\r\n // Auto-select execution method\r\n if (method === 'auto') {\r\n // Try API execution first, fallback to script if API key not available\r\n try {\r\n return await executeViaAPI(definition, prompt, context);\r\n } catch (error) {\r\n if (error instanceof Error && error.message.includes('API key not found')) {\r\n console.log('[agent-executor] API key not found, using script fallback');\r\n return executeViaScript(definition, prompt, context);\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n if (method === 'api') {\r\n return executeViaAPI(definition, prompt, context);\r\n }\r\n\r\n return executeViaScript(definition, prompt, context);\r\n}\r\n\r\n/**\r\n * Write agent output to file for debugging\r\n */\r\nexport async function saveAgentOutput(\r\n agentId: string,\r\n output: string,\r\n outputDir: string = '.claude/tmp/agent-output'\r\n): Promise<string> {\r\n await fs.mkdir(outputDir, { recursive: true });\r\n\r\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\r\n const filename = `${agentId}-${timestamp}.txt`;\r\n const filepath = path.join(outputDir, filename);\r\n\r\n await fs.writeFile(filepath, output, 'utf-8');\r\n\r\n return filepath;\r\n}\r\n"],"names":["spawn","getAgentId","buildCLIAgentSystemPrompt","loadContextFromEnv","fs","path","os","isCustomRoutingEnabled","process","env","CLAUDE_API_PROVIDER","configPath","join","config","JSON","parse","readFile","provider","getAPIProvider","customEnabled","executeViaAPI","definition","prompt","context","agentId","console","log","name","model","contextOptions","agentType","taskId","iteration","systemPrompt","executeAgentAPI","result","success","output","error","exitCode","Error","message","String","executeViaScript","tmpDir","tmpdir","promptFile","Date","now","writeFile","Promise","resolve","scriptPath","AGENT_TYPE","AGENT_ID","AGENT_MODEL","AGENT_TOOLS","tools","TASK_ID","ITERATION","MODE","mode","PROMPT_FILE","access","then","proc","stdio","on","code","err","catch","substring","executeAgent","options","method","includes","saveAgentOutput","outputDir","mkdir","recursive","timestamp","toISOString","replace","filename","filepath"],"mappings":"AAAA;;;;;;;CAOC,GAED,SAASA,KAAK,QAAQ,gBAAgB;AAEtC,SAAsBC,UAAU,QAAQ,4BAA4B;AACpE,SAASC,yBAAyB,EAAEC,kBAAkB,QAAQ,yBAAyB;AACvF,OAAOC,QAAQ,cAAc;AAC7B,OAAOC,UAAU,OAAO;AACxB,OAAOC,QAAQ,KAAK;AAUpB;;CAEC,GACD,eAAeC;IACb,6BAA6B;IAC7B,IAAIC,QAAQC,GAAG,CAACC,mBAAmB,KAAK,OAAO;QAC7C,OAAO;IACT;IAEA,uDAAuD;IACvD,IAAI;QACF,MAAMC,aAAaN,KAAKO,IAAI,CAAC,WAAW,UAAU;QAClD,MAAMC,SAASC,KAAKC,KAAK,CAAC,MAAMX,GAAGY,QAAQ,CAACL,YAAY;QACxD,OAAOE,OAAOI,QAAQ,KAAK,SAASJ,OAAOI,QAAQ,KAAK;IAC1D,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA;;CAEC,GACD,eAAeC;IACb,MAAMC,gBAAgB,MAAMZ;IAC5B,OAAOY,gBAAgB,QAAQ;AACjC;AAEA;;CAEC,GACD,eAAeC,cACbC,UAA2B,EAC3BC,MAAc,EACdC,OAAoB;IAEpB,MAAMC,UAAUvB,WAAWoB,YAAYE;IAEvCE,QAAQC,GAAG,CAAC,CAAC,0CAA0C,EAAEL,WAAWM,IAAI,EAAE;IAC1EF,QAAQC,GAAG,CAAC,CAAC,2BAA2B,EAAEF,SAAS;IACnDC,QAAQC,GAAG,CAAC,CAAC,wBAAwB,EAAEL,WAAWO,KAAK,EAAE;IACzDH,QAAQC,GAAG,CAAC;IAEZ,IAAI;QACF,0EAA0E;QAC1ED,QAAQC,GAAG,CAAC;QACZ,MAAMG,iBAAiB1B;QACvB,2CAA2C;QAC3C0B,eAAeC,SAAS,GAAGT,WAAWM,IAAI;QAC1C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Ac,EACdC,OAAoB,EACpBkD,UAEI,CAAC,CAAC;IAEN,MAAMC,SAASD,QAAQC,MAAM,IAAI;IAEjC,+BAA+B;IAC/B,IAAIA,WAAW,QAAQ;QACrB,uEAAuE;QACvE,IAAI;YACF,OAAO,MAAMtD,cAAcC,YAAYC,QAAQC;QACjD,EAAE,OAAOe,OAAO;YACd,IAAIA,iBAAiBE,SAASF,MAAMG,OAAO,CAACkC,QAAQ,CAAC,sBAAsB;gBACzElD,QAAQC,GAAG,CAAC;gBACZ,OAAOiB,iBAAiBtB,YAAYC,QAAQC;YAC9C;YACA,MAAMe;QACR;IACF;IAEA,IAAIoC,WAAW,OAAO;QACpB,OAAOtD,cAAcC,YAAYC,QAAQC;IAC3C;IAEA,OAAOoB,iBAAiBtB,YAAYC,QAAQC;AAC9C;AAEA;;CAEC,GACD,OAAO,eAAeqD,gBACpBpD,OAAe,EACfa,MAAc,EACdwC,YAAoB,0BAA0B;IAE9C,MAAMzE,GAAG0E,KAAK,CAACD,WAAW;QAAEE,WAAW;IAAK;IAE5C,MAAMC,YAAY,IAAIjC,OAAOkC,WAAW,GAAGC,OAAO,CAAC,SAAS;IAC5D,MAAMC,WAAW,GAAG3D,QAAQ,CAAC,EAAEwD,UAAU,IAAI,CAAC;IAC9C,MAAMI,WAAW/E,KAAKO,IAAI,CAACiE,WAAWM;IAEtC,MAAM/E,GAAG6C,SAAS,CAACmC,UAAU/C,QAAQ;IAErC,OAAO+C;AACT"}
1
+ {"version":3,"sources":["../../src/cli/agent-executor.ts"],"sourcesContent":["/**\r\n * Agent Executor\r\n *\r\n * Executes CLI-spawned agents by:\r\n * 1. Checking custom routing configuration (z.ai vs Anthropic)\r\n * 2. Invoking the appropriate API\r\n * 3. Managing agent lifecycle and output\r\n */\r\n\r\nimport { spawn } from 'child_process';\r\nimport { exec } from 'child_process';\r\nimport { promisify } from 'util';\r\nimport { AgentDefinition } from './agent-definition-parser.js';\r\nimport { TaskContext, getAgentId } from './agent-prompt-builder.js';\r\nimport { buildCLIAgentSystemPrompt, loadContextFromEnv } from './cli-agent-context.js';\r\nimport {\r\n loadMessages,\r\n storeMessage,\r\n getCurrentFork,\r\n formatMessagesForAPI,\r\n type Message\r\n} from './conversation-fork.js';\r\nimport { convertToolNames } from './tool-definitions.js';\r\nimport fs from 'fs/promises';\r\nimport path from 'path';\r\nimport os from 'os';\r\n\r\nconst execAsync = promisify(exec);\r\n\r\nexport interface AgentExecutionResult {\r\n success: boolean;\r\n agentId: string;\r\n output?: string;\r\n error?: string;\r\n exitCode: number;\r\n}\r\n\r\n/**\r\n * Extract confidence score from agent output\r\n * Looks for patterns like:\r\n * - \"confidence: 0.85\"\r\n * - \"Confidence: 0.90\"\r\n * - \"confidence score: 0.95\"\r\n * - \"self-confidence: 0.88\"\r\n */\r\nfunction extractConfidence(output: string | undefined): number {\r\n if (!output) return 0.85;\r\n\r\n // Try multiple patterns\r\n const patterns = [\r\n /confidence:\\s*([0-9.]+)/i,\r\n /confidence\\s+score:\\s*([0-9.]+)/i,\r\n /self-confidence:\\s*([0-9.]+)/i,\r\n /my\\s+confidence:\\s*([0-9.]+)/i,\r\n ];\r\n\r\n for (const pattern of patterns) {\r\n const match = output.match(pattern);\r\n if (match && match[1]) {\r\n const score = parseFloat(match[1]);\r\n if (score >= 0 && score <= 1) {\r\n return score;\r\n }\r\n }\r\n }\r\n\r\n // Default to 0.85 if not found\r\n return 0.85;\r\n}\r\n\r\n/**\r\n * Execute CFN Loop protocol after agent completes work\r\n *\r\n * Steps:\r\n * 1. Signal completion to orchestrator\r\n * 2. Report confidence score\r\n * 3. Enter waiting mode (if iterations enabled)\r\n */\r\nasync function executeCFNProtocol(\r\n taskId: string,\r\n agentId: string,\r\n output: string | undefined,\r\n iteration: number,\r\n enableIterations: boolean = false,\r\n maxIterations: number = 10\r\n): Promise<void> {\r\n console.log(`\\n[CFN Protocol] Starting for agent ${agentId}`);\r\n console.log(`[CFN Protocol] Task ID: ${taskId}, Iteration: ${iteration}`);\r\n\r\n try {\r\n // Step 1: Signal completion\r\n console.log('[CFN Protocol] Step 1: Signaling completion...');\r\n await execAsync(`redis-cli lpush \"swarm:${taskId}:${agentId}:done\" \"complete\"`);\r\n console.log('[CFN Protocol] ✓ Completion signaled');\r\n\r\n // Step 2: Extract and report confidence\r\n const confidence = extractConfidence(output);\r\n console.log(`[CFN Protocol] Step 2: Reporting confidence (${confidence})...`);\r\n\r\n const reportCmd = `./.claude/skills/redis-coordination/invoke-waiting-mode.sh report \\\r\n --task-id \"${taskId}\" \\\r\n --agent-id \"${agentId}\" \\\r\n --confidence ${confidence} \\\r\n --iteration ${iteration}`;\r\n\r\n await execAsync(reportCmd);\r\n console.log('[CFN Protocol] ✓ Confidence reported');\r\n\r\n // Step 3: Exit cleanly (BUG #18 FIX - removed waiting mode)\r\n // Orchestrator will spawn appropriate specialist agent for next iteration\r\n // This enables adaptive agent specialization based on feedback type\r\n console.log('[CFN Protocol] Step 3: Exiting cleanly (iteration complete)');\r\n console.log('[CFN Protocol] Protocol complete\\n');\r\n } catch (error) {\r\n console.error('[CFN Protocol] Error:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Check if custom routing (z.ai) is enabled\r\n */\r\nasync function isCustomRoutingEnabled(): Promise<boolean> {\r\n // Check environment variable\r\n if (process.env.CLAUDE_API_PROVIDER === 'zai') {\r\n return true;\r\n }\r\n\r\n // Check config file (.claude/config/api-provider.json)\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 return config.provider === 'zai' || config.provider === 'z.ai';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Get API provider configuration\r\n */\r\nasync function getAPIProvider(): Promise<'anthropic' | 'zai'> {\r\n const customEnabled = await isCustomRoutingEnabled();\r\n return customEnabled ? 'zai' : 'anthropic';\r\n}\r\n\r\n/**\r\n * Execute agent using direct API calls\r\n */\r\nasync function executeViaAPI(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext\r\n): Promise<AgentExecutionResult> {\r\n const agentId = getAgentId(definition, context);\r\n\r\n console.log(`[agent-executor] Executing agent via API: ${definition.name}`);\r\n console.log(`[agent-executor] Agent ID: ${agentId}`);\r\n console.log(`[agent-executor] Model: ${definition.model}`);\r\n console.log('');\r\n\r\n try {\r\n // Check for conversation fork (Sprint 4 enhancement)\r\n const forkId = process.env.FORK_ID || await getCurrentFork(context.taskId || '', agentId);\r\n const iteration = context.iteration || 1;\r\n\r\n let systemPrompt: string;\r\n let messages: Array<{role: string, content: string}> = [];\r\n\r\n if (forkId && iteration > 1) {\r\n // Continue from fork (iterations 2+)\r\n console.log(`[agent-executor] Continuing from fork: ${forkId}`);\r\n\r\n // Load fork messages\r\n const forkMessages = await loadMessages(context.taskId || '', agentId, forkId);\r\n console.log(`[agent-executor] Loaded ${forkMessages.length} messages from fork`);\r\n\r\n // Extract system prompt from first message (it's always the system message)\r\n // The fork messages are assistant/user pairs, we need to add system separately\r\n systemPrompt = forkMessages[0]?.content || '';\r\n\r\n // Format remaining messages for API\r\n messages = formatMessagesForAPI(forkMessages.slice(1));\r\n\r\n // Add new user message with feedback\r\n messages.push({\r\n role: 'user',\r\n content: prompt\r\n });\r\n\r\n console.log(`[agent-executor] Fork continuation: ${messages.length} messages`);\r\n } else {\r\n // New conversation (iteration 1)\r\n console.log('[agent-executor] Starting new conversation');\r\n console.log('[agent-executor] Building system prompt with context...');\r\n\r\n const contextOptions = loadContextFromEnv();\r\n contextOptions.agentType = definition.name;\r\n if (context.taskId) contextOptions.taskId = context.taskId;\r\n if (context.iteration) contextOptions.iteration = context.iteration;\r\n\r\n systemPrompt = await buildCLIAgentSystemPrompt(contextOptions);\r\n console.log('[agent-executor] System prompt built successfully');\r\n\r\n // Initial user message\r\n messages = [{\r\n role: 'user',\r\n content: prompt\r\n }];\r\n }\r\n\r\n console.log('');\r\n\r\n // Dynamic import to avoid bundling issues\r\n const { executeAgentAPI } = await import('./anthropic-client.js');\r\n\r\n // Convert agent tool names to Anthropic API format\r\n const tools = definition.tools && definition.tools.length > 0\r\n ? convertToolNames(definition.tools)\r\n : undefined;\r\n\r\n const result = await executeAgentAPI(\r\n definition.name,\r\n agentId,\r\n definition.model,\r\n prompt,\r\n systemPrompt,\r\n messages.length > 1 ? messages : undefined,\r\n undefined, // maxTokens (use default)\r\n tools // Pass converted tools\r\n );\r\n\r\n // Store messages in conversation history (for future forking)\r\n if (context.taskId) {\r\n // Store user message\r\n const userMessage: Message = {\r\n role: 'user',\r\n content: prompt,\r\n iteration,\r\n timestamp: new Date().toISOString()\r\n };\r\n await storeMessage(context.taskId, agentId, userMessage);\r\n\r\n // Store assistant response\r\n if (result.output) {\r\n const assistantMessage: Message = {\r\n role: 'assistant',\r\n content: result.output,\r\n iteration,\r\n timestamp: new Date().toISOString()\r\n };\r\n await storeMessage(context.taskId, agentId, assistantMessage);\r\n }\r\n\r\n console.log(`[agent-executor] Stored messages for iteration ${iteration}`);\r\n\r\n // Execute CFN Loop protocol (signal completion, report confidence, enter waiting mode)\r\n // Iterations are enabled for CFN Loop tasks (indicated by presence of taskId)\r\n try {\r\n const maxIterations = 10; // Default max iterations\r\n const enableIterations = true; // Enable iterations for all CFN Loop tasks\r\n\r\n await executeCFNProtocol(\r\n context.taskId,\r\n agentId,\r\n result.output,\r\n iteration,\r\n enableIterations,\r\n maxIterations\r\n );\r\n } catch (error) {\r\n console.error('[agent-executor] CFN Protocol execution failed:', error);\r\n // Don't fail the entire agent execution if CFN protocol fails\r\n // This allows agents to complete even if Redis coordination has issues\r\n }\r\n }\r\n\r\n return {\r\n success: result.success,\r\n agentId,\r\n output: result.output,\r\n error: result.error,\r\n exitCode: result.success ? 0 : 1,\r\n };\r\n } catch (error) {\r\n console.error('[agent-executor] API execution failed:', error);\r\n return {\r\n success: false,\r\n agentId,\r\n error: error instanceof Error ? error.message : String(error),\r\n exitCode: 1,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Execute agent using shell script (fallback/simulation)\r\n */\r\nasync function executeViaScript(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext\r\n): Promise<AgentExecutionResult> {\r\n const agentId = getAgentId(definition, context);\r\n\r\n // Write prompt to temporary file\r\n const tmpDir = os.tmpdir();\r\n const promptFile = path.join(tmpDir, `agent-${agentId}-${Date.now()}.md`);\r\n await fs.writeFile(promptFile, prompt, 'utf-8');\r\n\r\n console.log(`[agent-executor] Executing agent via script: ${definition.name}`);\r\n console.log(`[agent-executor] Agent ID: ${agentId}`);\r\n console.log(`[agent-executor] Model: ${definition.model}`);\r\n console.log(`[agent-executor] Prompt file: ${promptFile}`);\r\n\r\n return new Promise((resolve) => {\r\n const scriptPath = path.join('.claude', 'skills', 'agent-execution', 'execute-agent.sh');\r\n\r\n // Build environment variables\r\n const env = {\r\n ...process.env,\r\n AGENT_TYPE: definition.name,\r\n AGENT_ID: agentId,\r\n AGENT_MODEL: definition.model,\r\n AGENT_TOOLS: definition.tools.join(','),\r\n TASK_ID: context.taskId || '',\r\n ITERATION: String(context.iteration || 1),\r\n MODE: context.mode || 'cli',\r\n PROMPT_FILE: promptFile,\r\n };\r\n\r\n // Check if execute script exists\r\n fs.access(scriptPath)\r\n .then(() => {\r\n // Use execution script\r\n const proc = spawn('bash', [scriptPath], { env, stdio: 'inherit' });\r\n\r\n proc.on('exit', (code) => {\r\n resolve({\r\n success: code === 0,\r\n agentId,\r\n exitCode: code || 0,\r\n });\r\n });\r\n\r\n proc.on('error', (err) => {\r\n resolve({\r\n success: false,\r\n agentId,\r\n error: err.message,\r\n exitCode: 1,\r\n });\r\n });\r\n })\r\n .catch(() => {\r\n // Fallback: Print prompt\r\n console.log('\\n=== Agent Prompt ===');\r\n console.log(prompt.substring(0, 500) + '...');\r\n console.log('\\n[agent-executor] Execution script not found');\r\n console.log('[agent-executor] Using simulation mode\\n');\r\n\r\n resolve({\r\n success: true,\r\n agentId,\r\n output: prompt,\r\n exitCode: 0,\r\n });\r\n });\r\n });\r\n}\r\n\r\n/**\r\n * Main agent execution function\r\n */\r\nexport async function executeAgent(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext,\r\n options: {\r\n method?: 'auto' | 'api' | 'script';\r\n } = {}\r\n): Promise<AgentExecutionResult> {\r\n const method = options.method || 'auto';\r\n\r\n // Auto-select execution method\r\n if (method === 'auto') {\r\n // Try API execution first, fallback to script if API key not available\r\n try {\r\n return await executeViaAPI(definition, prompt, context);\r\n } catch (error) {\r\n if (error instanceof Error && error.message.includes('API key not found')) {\r\n console.log('[agent-executor] API key not found, using script fallback');\r\n return executeViaScript(definition, prompt, context);\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n if (method === 'api') {\r\n return executeViaAPI(definition, prompt, context);\r\n }\r\n\r\n return executeViaScript(definition, prompt, context);\r\n}\r\n\r\n/**\r\n * Write agent output to file for debugging\r\n */\r\nexport async function saveAgentOutput(\r\n agentId: string,\r\n output: string,\r\n outputDir: string = '.claude/tmp/agent-output'\r\n): Promise<string> {\r\n await fs.mkdir(outputDir, { recursive: true });\r\n\r\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\r\n const filename = `${agentId}-${timestamp}.txt`;\r\n const filepath = path.join(outputDir, filename);\r\n\r\n await fs.writeFile(filepath, output, 'utf-8');\r\n\r\n return filepath;\r\n}\r\n"],"names":["spawn","exec","promisify","getAgentId","buildCLIAgentSystemPrompt","loadContextFromEnv","loadMessages","storeMessage","getCurrentFork","formatMessagesForAPI","convertToolNames","fs","path","os","execAsync","extractConfidence","output","patterns","pattern","match","score","parseFloat","executeCFNProtocol","taskId","agentId","iteration","enableIterations","maxIterations","console","log","confidence","reportCmd","error","isCustomRoutingEnabled","process","env","CLAUDE_API_PROVIDER","configPath","join","config","JSON","parse","readFile","provider","getAPIProvider","customEnabled","executeViaAPI","definition","prompt","context","name","model","forkId","FORK_ID","systemPrompt","messages","forkMessages","length","content","slice","push","role","contextOptions","agentType","executeAgentAPI","tools","undefined","result","userMessage","timestamp","Date","toISOString","assistantMessage","success","exitCode","Error","message","String","executeViaScript","tmpDir","tmpdir","promptFile","now","writeFile","Promise","resolve","scriptPath","AGENT_TYPE","AGENT_ID","AGENT_MODEL","AGENT_TOOLS","TASK_ID","ITERATION","MODE","mode","PROMPT_FILE","access","then","proc","stdio","on","code","err","catch","substring","executeAgent","options","method","includes","saveAgentOutput","outputDir","mkdir","recursive","replace","filename","filepath"],"mappings":"AAAA;;;;;;;CAOC,GAED,SAASA,KAAK,QAAQ,gBAAgB;AACtC,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AAEjC,SAAsBC,UAAU,QAAQ,4BAA4B;AACpE,SAASC,yBAAyB,EAAEC,kBAAkB,QAAQ,yBAAyB;AACvF,SACEC,YAAY,EACZC,YAAY,EACZC,cAAc,EACdC,oBAAoB,QAEf,yBAAyB;AAChC,SAASC,gBAAgB,QAAQ,wBAAwB;AACzD,OAAOC,QAAQ,cAAc;AAC7B,OAAOC,UAAU,OAAO;AACxB,OAAOC,QAAQ,KAAK;AAEpB,MAAMC,YAAYZ,UAAUD;AAU5B;;;;;;;CAOC,GACD,SAASc,kBAAkBC,MAA0B;IACnD,IAAI,CAACA,QAAQ,OAAO;IAEpB,wBAAwB;IACxB,MAAMC,WAAW;QACf;QACA;QACA;QACA;KACD;IAED,KAAK,MAAMC,WAAWD,SAAU;QAC9B,MAAME,QAAQH,OAAOG,KAAK,CAACD;QAC3B,IAAIC,SAASA,KAAK,CAAC,EAAE,EAAE;YACrB,MAAMC,QAAQC,WAAWF,KAAK,CAAC,EAAE;YACjC,IAAIC,SAAS,KAAKA,SAAS,GAAG;gBAC5B,OAAOA;YACT;QACF;IACF;IAEA,+BAA+B;IAC/B,OAAO;AACT;AAEA;;;;;;;CAOC,GACD,eAAeE,mBACbC,MAAc,EACdC,OAAe,EACfR,MAA0B,EAC1BS,SAAiB,EACjBC,mBAA4B,KAAK,EACjCC,gBAAwB,EAAE;IAE1B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W,QAAQ;QACrB,uEAAuE;QACvE,IAAI;YACF,OAAO,MAAM7D,cAAcC,YAAYC,QAAQC;QACjD,EAAE,OAAOjB,OAAO;YACd,IAAIA,iBAAiB2C,SAAS3C,MAAM4C,OAAO,CAACgC,QAAQ,CAAC,sBAAsB;gBACzEhF,QAAQC,GAAG,CAAC;gBACZ,OAAOiD,iBAAiB/B,YAAYC,QAAQC;YAC9C;YACA,MAAMjB;QACR;IACF;IAEA,IAAI2E,WAAW,OAAO;QACpB,OAAO7D,cAAcC,YAAYC,QAAQC;IAC3C;IAEA,OAAO6B,iBAAiB/B,YAAYC,QAAQC;AAC9C;AAEA;;CAEC,GACD,OAAO,eAAe4D,gBACpBrF,OAAe,EACfR,MAAc,EACd8F,YAAoB,0BAA0B;IAE9C,MAAMnG,GAAGoG,KAAK,CAACD,WAAW;QAAEE,WAAW;IAAK;IAE5C,MAAM3C,YAAY,IAAIC,OAAOC,WAAW,GAAG0C,OAAO,CAAC,SAAS;IAC5D,MAAMC,WAAW,GAAG1F,QAAQ,CAAC,EAAE6C,UAAU,IAAI,CAAC;IAC9C,MAAM8C,WAAWvG,KAAK0B,IAAI,CAACwE,WAAWI;IAEtC,MAAMvG,GAAGwE,SAAS,CAACgC,UAAUnG,QAAQ;IAErC,OAAOmG;AACT"}
@@ -56,15 +56,91 @@ redis-cli lpush "swarm:${taskId}:\${AGENT_ID}:done" "complete"
56
56
  **IMPORTANT:** You MUST complete all 4 steps in order. The orchestrator is waiting for your completion signal.
57
57
  `;
58
58
  }
59
+ /**
60
+ * Parse and enrich JSON context into natural language instructions
61
+ */ function enrichJSONContext(jsonObj) {
62
+ const sections = [];
63
+ // Extract task description
64
+ if (jsonObj.task) {
65
+ sections.push(`**Task:** ${jsonObj.task}`);
66
+ }
67
+ // Parse files - convert comma-separated string to bullet list
68
+ if (jsonObj.files) {
69
+ const fileList = typeof jsonObj.files === 'string' ? jsonObj.files.split(',').map((f)=>f.trim()).filter((f)=>f) : Array.isArray(jsonObj.files) ? jsonObj.files : [];
70
+ if (fileList.length > 0) {
71
+ sections.push('\n**Files to process:**');
72
+ fileList.forEach((file)=>sections.push(`- ${file}`));
73
+ }
74
+ }
75
+ // Add requirements/deliverables
76
+ if (jsonObj.requirements) {
77
+ const reqs = Array.isArray(jsonObj.requirements) ? jsonObj.requirements : [
78
+ jsonObj.requirements
79
+ ];
80
+ sections.push('\n**Requirements:**');
81
+ reqs.forEach((req, i)=>sections.push(`${i + 1}. ${req}`));
82
+ }
83
+ if (jsonObj.deliverables) {
84
+ const delivs = Array.isArray(jsonObj.deliverables) ? jsonObj.deliverables : [
85
+ jsonObj.deliverables
86
+ ];
87
+ sections.push('\n**Deliverables:**');
88
+ delivs.forEach((deliv)=>sections.push(`- ${deliv}`));
89
+ }
90
+ // Add batch information
91
+ if (jsonObj.batch) {
92
+ sections.push(`\n**Batch:** ${jsonObj.batch}`);
93
+ }
94
+ // Add directory context
95
+ if (jsonObj.directory) {
96
+ sections.push(`\n**Working Directory:** ${jsonObj.directory}`);
97
+ }
98
+ // Add acceptance criteria
99
+ if (jsonObj.acceptanceCriteria) {
100
+ const criteria = Array.isArray(jsonObj.acceptanceCriteria) ? jsonObj.acceptanceCriteria : [
101
+ jsonObj.acceptanceCriteria
102
+ ];
103
+ sections.push('\n**Acceptance Criteria:**');
104
+ criteria.forEach((criterion)=>sections.push(`- ${criterion}`));
105
+ }
106
+ // Add explicit instructions if present
107
+ if (jsonObj.instructions) {
108
+ sections.push('\n**Instructions:**');
109
+ const instrs = Array.isArray(jsonObj.instructions) ? jsonObj.instructions : [
110
+ jsonObj.instructions
111
+ ];
112
+ instrs.forEach((instr, i)=>sections.push(`${i + 1}. ${instr}`));
113
+ }
114
+ return sections.join('\n');
115
+ }
59
116
  /**
60
117
  * Build task description from context
61
118
  */ function buildTaskDescription(agentType, context) {
62
119
  let desc = '';
63
120
  if (context.context) {
64
- desc = context.context;
121
+ // Try to parse as JSON first
122
+ let contextStr = context.context.trim();
123
+ // Check if context looks like JSON
124
+ if (contextStr.startsWith('{') && contextStr.endsWith('}') || contextStr.startsWith('[') && contextStr.endsWith(']')) {
125
+ try {
126
+ const jsonObj = JSON.parse(contextStr);
127
+ desc = enrichJSONContext(jsonObj);
128
+ // Add instruction footer for structured tasks
129
+ if (jsonObj.files || jsonObj.deliverables) {
130
+ desc += '\n\n**Process each item systematically and report confidence when complete.**';
131
+ }
132
+ } catch (e) {
133
+ // Not valid JSON, treat as plain text
134
+ desc = context.context;
135
+ }
136
+ } else {
137
+ // Plain text context
138
+ desc = context.context;
139
+ }
65
140
  } else {
66
141
  desc = `Execute task as ${agentType} agent`;
67
142
  }
143
+ // Add metadata fields
68
144
  if (context.taskId) {
69
145
  desc += `\n\n**Task ID:** ${context.taskId}`;
70
146
  }
@@ -170,7 +246,11 @@ ${env.join('\n')}
170
246
  }
171
247
  /**
172
248
  * Extract agent ID from context
249
+ * If agentId is explicitly provided in context, use it; otherwise generate from name + iteration
173
250
  */ export function getAgentId(definition, context) {
251
+ if (context.agentId) {
252
+ return context.agentId;
253
+ }
174
254
  return `${definition.name}-${context.iteration || 1}`;
175
255
  }
176
256
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/agent-prompt-builder.ts"],"sourcesContent":["/**\r\n * Agent Prompt Builder\r\n *\r\n * Builds comprehensive prompts for CLI-spawned agents by combining:\r\n * - Agent definition (YAML + markdown)\r\n * - Task context (taskId, iteration, mode)\r\n * - CFN Loop protocol (if applicable)\r\n * - Iteration history (Sprint 3 - Phase 2)\r\n * - Environment variables\r\n */\r\n\r\nimport { AgentDefinition, hasCFNLoopProtocol } from './agent-definition-parser.js';\r\nimport { loadIterationHistory, formatIterationHistory } from './iteration-history.js';\r\n\r\nexport interface TaskContext {\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 * Build CFN Loop protocol instructions\r\n */\r\nfunction buildCFNLoopProtocol(taskId: string, agentId: string): string {\r\n return `\r\n## CFN Loop Redis Completion Protocol\r\n\r\nYou are participating in a CFN Loop workflow. Follow this protocol EXACTLY:\r\n\r\n### Step 1: Complete Work\r\nExecute your assigned task (implementation, review, testing, etc.)\r\n\r\n### Step 2: Signal Completion\r\n\\`\\`\\`bash\r\nredis-cli lpush \"swarm:${taskId}:\\${AGENT_ID}:done\" \"complete\"\r\n\\`\\`\\`\r\n\r\n### Step 3: Report Confidence Score\r\n\\`\\`\\`bash\r\n./.claude/skills/redis-coordination/invoke-waiting-mode.sh report \\\\\r\n --task-id \"${taskId}\" \\\\\r\n --agent-id \"\\${AGENT_ID}\" \\\\\r\n --confidence [0.0-1.0] \\\\\r\n --iteration ${taskId.includes('iteration') ? 'CURRENT_ITERATION' : '1'}\r\n\\`\\`\\`\r\n\r\n### Step 4: Enter Waiting Mode (for potential iteration)\r\n\\`\\`\\`bash\r\n./.claude/skills/redis-coordination/invoke-waiting-mode.sh enter \\\\\r\n --task-id \"${taskId}\" \\\\\r\n --agent-id \"\\${AGENT_ID}\" \\\\\r\n --context \"iteration-complete\"\r\n\\`\\`\\`\r\n\r\n**Critical Context Variables:**\r\n- TASK_ID: ${taskId}\r\n- AGENT_ID: ${agentId} (your unique identifier)\r\n- Confidence: Your self-assessment score (0.0-1.0)\r\n\r\n**Why This Matters:**\r\n- Zero-token blocking coordination (BLPOP waits without API calls)\r\n- Orchestrator collects confidence/consensus scores automatically\r\n- Supports autonomous iteration based on quality gates\r\n- Agent woken instantly (<100ms) if iteration needed\r\n\r\n**IMPORTANT:** You MUST complete all 4 steps in order. The orchestrator is waiting for your completion signal.\r\n`;\r\n}\r\n\r\n/**\r\n * Build task description from context\r\n */\r\nfunction buildTaskDescription(agentType: string, context: TaskContext): string {\r\n let desc = '';\r\n\r\n if (context.context) {\r\n desc = context.context;\r\n } else {\r\n desc = `Execute task as ${agentType} agent`;\r\n }\r\n\r\n if (context.taskId) {\r\n desc += `\\n\\n**Task ID:** ${context.taskId}`;\r\n }\r\n\r\n if (context.iteration) {\r\n desc += `\\n**Iteration:** ${context.iteration}`;\r\n }\r\n\r\n if (context.mode) {\r\n desc += `\\n**Mode:** ${context.mode}`;\r\n }\r\n\r\n if (context.priority) {\r\n desc += `\\n**Priority:** ${context.priority}`;\r\n }\r\n\r\n if (context.parentTaskId) {\r\n desc += `\\n**Parent Task:** ${context.parentTaskId}`;\r\n }\r\n\r\n return desc;\r\n}\r\n\r\n/**\r\n * Build environment context section\r\n */\r\nfunction buildEnvironmentContext(context: TaskContext): string {\r\n const env: string[] = [];\r\n\r\n if (context.taskId) env.push(`TASK_ID=${context.taskId}`);\r\n if (context.iteration) env.push(`ITERATION=${context.iteration}`);\r\n if (context.mode) env.push(`MODE=${context.mode}`);\r\n if (context.priority) env.push(`PRIORITY=${context.priority}`);\r\n if (context.parentTaskId) env.push(`PARENT_TASK_ID=${context.parentTaskId}`);\r\n\r\n if (env.length === 0) return '';\r\n\r\n return `\r\n## Environment Variables\r\n\r\n\\`\\`\\`bash\r\n${env.join('\\n')}\r\n\\`\\`\\`\r\n`;\r\n}\r\n\r\n/**\r\n * Build complete prompt for agent execution (async for iteration history)\r\n */\r\nexport async function buildAgentPrompt(\r\n definition: AgentDefinition,\r\n context: TaskContext\r\n): Promise<string> {\r\n const agentId = `${definition.name}-${context.iteration || 1}`;\r\n\r\n const sections: string[] = [];\r\n\r\n // 1. Agent definition header\r\n sections.push(`# Agent: ${definition.name}`);\r\n sections.push('');\r\n sections.push(definition.description);\r\n sections.push('');\r\n\r\n // 2. Task description\r\n sections.push('## Task');\r\n sections.push('');\r\n sections.push(buildTaskDescription(definition.name, context));\r\n sections.push('');\r\n\r\n // 3. Iteration history (Sprint 3 - Phase 2)\r\n // Load and format previous iterations if iteration > 1\r\n if (context.taskId && context.iteration && context.iteration > 1) {\r\n try {\r\n const history = await loadIterationHistory(context.taskId, agentId, context.iteration);\r\n const historyText = formatIterationHistory(history, context.iteration);\r\n sections.push(historyText);\r\n sections.push('');\r\n } catch (err) {\r\n console.warn(`[agent-prompt-builder] Failed to load iteration history:`, err);\r\n // Continue without history\r\n }\r\n }\r\n\r\n // 4. Agent definition content (from markdown file)\r\n sections.push('## Agent Definition');\r\n sections.push('');\r\n sections.push(definition.content);\r\n sections.push('');\r\n\r\n // 5. CFN Loop protocol (if agent supports it AND task context includes taskId)\r\n if (context.taskId && hasCFNLoopProtocol(definition)) {\r\n sections.push(buildCFNLoopProtocol(context.taskId, agentId));\r\n sections.push('');\r\n }\r\n\r\n // 6. Environment context\r\n const envContext = buildEnvironmentContext(context);\r\n if (envContext) {\r\n sections.push(envContext);\r\n sections.push('');\r\n }\r\n\r\n // 7. Execution instructions\r\n sections.push('## Execution Instructions');\r\n sections.push('');\r\n sections.push('1. Read and understand the task requirements');\r\n if (context.iteration && context.iteration > 1) {\r\n sections.push('2. Review iteration history and feedback from validators');\r\n sections.push('3. Address specific feedback points from previous iteration');\r\n sections.push('4. Execute your core responsibilities as defined above');\r\n } else {\r\n sections.push('2. Execute your core responsibilities as defined above');\r\n sections.push('3. Follow any protocol steps (CFN Loop, validation hooks, etc.)');\r\n }\r\n sections.push('4. Provide clear, concise output');\r\n sections.push('5. Report confidence score if applicable');\r\n sections.push('');\r\n\r\n // 8. Tool reminder\r\n if (definition.tools && definition.tools.length > 0) {\r\n sections.push('## Available Tools');\r\n sections.push('');\r\n sections.push(`You have access to: ${definition.tools.join(', ')}`);\r\n sections.push('');\r\n }\r\n\r\n return sections.join('\\n');\r\n}\r\n\r\n/**\r\n * Extract agent ID from context\r\n */\r\nexport function getAgentId(definition: AgentDefinition, context: TaskContext): string {\r\n return `${definition.name}-${context.iteration || 1}`;\r\n}\r\n\r\n/**\r\n * Build system prompt for agent (optional, for structured agent behavior)\r\n */\r\nexport function buildSystemPrompt(definition: AgentDefinition): string {\r\n return `You are ${definition.name}, a specialized AI agent.\r\n\r\nType: ${definition.type || 'specialist'}\r\nModel: ${definition.model}\r\nTools: ${definition.tools.join(', ')}\r\n\r\nFollow your agent definition exactly and complete assigned tasks with high quality.`;\r\n}\r\n"],"names":["hasCFNLoopProtocol","loadIterationHistory","formatIterationHistory","buildCFNLoopProtocol","taskId","agentId","includes","buildTaskDescription","agentType","context","desc","iteration","mode","priority","parentTaskId","buildEnvironmentContext","env","push","length","join","buildAgentPrompt","definition","name","sections","description","history","historyText","err","console","warn","content","envContext","tools","getAgentId","buildSystemPrompt","type","model"],"mappings":"AAAA;;;;;;;;;CASC,GAED,SAA0BA,kBAAkB,QAAQ,+BAA+B;AACnF,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,yBAAyB;AAWtF;;CAEC,GACD,SAASC,qBAAqBC,MAAc,EAAEC,OAAe;IAC3D,OAAO,CAAC;;;;;;;;;;uBAUa,EAAED,OAAO;;;;;;aAMnB,EAAEA,OAAO;;;cAGR,EAAEA,OAAOE,QAAQ,CAAC,eAAe,sBAAsB,IAAI;;;;;;aAM5D,EAAEF,OAAO;;;;;;WAMX,EAAEA,OAAO;YACR,EAAEC,QAAQ;;;;;;;;;;AAUtB,CAAC;AACD;AAEA;;CAEC,GACD,SAASE,qBAAqBC,SAAiB,EAAEC,OAAoB;IACnE,IAAIC,OAAO;IAEX,IAAID,QAAQA,OAAO,EAAE;QACnBC,OAAOD,QAAQA,OAAO;IACxB,OAAO;QACLC,OAAO,CAAC,gBAAgB,EAAEF,UAAU,MAAM,CAAC;IAC7C;IAEA,IAAIC,QAAQL,MAAM,EAAE;QAClBM,QAAQ,CAAC,iBAAiB,EAAED,QAAQL,MAAM,EAAE;IAC9C;IAEA,IAAIK,QAAQE,SAAS,EAAE;QACrBD,QAAQ,CAAC,iBAAiB,EAAED,QAAQE,SAAS,EAAE;IACjD;IAEA,IAAIF,QAAQG,IAAI,EAAE;QAChBF,QAAQ,CAAC,YAAY,EAAED,QAAQG,IAAI,EAAE;IACvC;IAEA,IAAIH,QAAQI,QAAQ,EAAE;QACpBH,QAAQ,CAAC,gBAAgB,EAAED,QAAQI,QAAQ,EAAE;IAC/C;I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IAAIX,WAAWW,KAAK,CAACd,MAAM,GAAG,GAAG;QACnDK,SAASN,IAAI,CAAC;QACdM,SAASN,IAAI,CAAC;QACdM,SAASN,IAAI,CAAC,CAAC,oBAAoB,EAAEI,WAAWW,KAAK,CAACb,IAAI,CAAC,OAAO;QAClEI,SAASN,IAAI,CAAC;IAChB;IAEA,OAAOM,SAASJ,IAAI,CAAC;AACvB;AAEA;;CAEC,GACD,OAAO,SAASc,WAAWZ,UAA2B,EAAEZ,OAAoB;IAC1E,OAAO,GAAGY,WAAWC,IAAI,CAAC,CAAC,EAAEb,QAAQE,SAAS,IAAI,GAAG;AACvD;AAEA;;CAEC,GACD,OAAO,SAASuB,kBAAkBb,UAA2B;IAC3D,OAAO,CAAC,QAAQ,EAAEA,WAAWC,IAAI,CAAC;;MAE9B,EAAED,WAAWc,IAAI,IAAI,aAAa;OACjC,EAAEd,WAAWe,KAAK,CAAC;OACnB,EAAEf,WAAWW,KAAK,CAACb,IAAI,CAAC,MAAM;;mFAE8C,CAAC;AACpF"}
1
+ {"version":3,"sources":["../../src/cli/agent-prompt-builder.ts"],"sourcesContent":["/**\r\n * Agent Prompt Builder\r\n *\r\n * Builds comprehensive prompts for CLI-spawned agents by combining:\r\n * - Agent definition (YAML + markdown)\r\n * - Task context (taskId, iteration, mode)\r\n * - CFN Loop protocol (if applicable)\r\n * - Iteration history (Sprint 3 - Phase 2)\r\n * - Environment variables\r\n */\r\n\r\nimport { AgentDefinition, hasCFNLoopProtocol } from './agent-definition-parser.js';\r\nimport { loadIterationHistory, formatIterationHistory } from './iteration-history.js';\r\n\r\nexport interface TaskContext {\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 agentId?: string;\r\n}\r\n\r\n/**\r\n * Build CFN Loop protocol instructions\r\n */\r\nfunction buildCFNLoopProtocol(taskId: string, agentId: string): string {\r\n return `\r\n## CFN Loop Redis Completion Protocol\r\n\r\nYou are participating in a CFN Loop workflow. Follow this protocol EXACTLY:\r\n\r\n### Step 1: Complete Work\r\nExecute your assigned task (implementation, review, testing, etc.)\r\n\r\n### Step 2: Signal Completion\r\n\\`\\`\\`bash\r\nredis-cli lpush \"swarm:${taskId}:\\${AGENT_ID}:done\" \"complete\"\r\n\\`\\`\\`\r\n\r\n### Step 3: Report Confidence Score\r\n\\`\\`\\`bash\r\n./.claude/skills/redis-coordination/invoke-waiting-mode.sh report \\\\\r\n --task-id \"${taskId}\" \\\\\r\n --agent-id \"\\${AGENT_ID}\" \\\\\r\n --confidence [0.0-1.0] \\\\\r\n --iteration ${taskId.includes('iteration') ? 'CURRENT_ITERATION' : '1'}\r\n\\`\\`\\`\r\n\r\n### Step 4: Enter Waiting Mode (for potential iteration)\r\n\\`\\`\\`bash\r\n./.claude/skills/redis-coordination/invoke-waiting-mode.sh enter \\\\\r\n --task-id \"${taskId}\" \\\\\r\n --agent-id \"\\${AGENT_ID}\" \\\\\r\n --context \"iteration-complete\"\r\n\\`\\`\\`\r\n\r\n**Critical Context Variables:**\r\n- TASK_ID: ${taskId}\r\n- AGENT_ID: ${agentId} (your unique identifier)\r\n- Confidence: Your self-assessment score (0.0-1.0)\r\n\r\n**Why This Matters:**\r\n- Zero-token blocking coordination (BLPOP waits without API calls)\r\n- Orchestrator collects confidence/consensus scores automatically\r\n- Supports autonomous iteration based on quality gates\r\n- Agent woken instantly (<100ms) if iteration needed\r\n\r\n**IMPORTANT:** You MUST complete all 4 steps in order. The orchestrator is waiting for your completion signal.\r\n`;\r\n}\r\n\r\n/**\r\n * Parse and enrich JSON context into natural language instructions\r\n */\r\nfunction enrichJSONContext(jsonObj: any): string {\r\n const sections: string[] = [];\r\n\r\n // Extract task description\r\n if (jsonObj.task) {\r\n sections.push(`**Task:** ${jsonObj.task}`);\r\n }\r\n\r\n // Parse files - convert comma-separated string to bullet list\r\n if (jsonObj.files) {\r\n const fileList = typeof jsonObj.files === 'string'\r\n ? jsonObj.files.split(',').map(f => f.trim()).filter(f => f)\r\n : Array.isArray(jsonObj.files) ? jsonObj.files : [];\r\n\r\n if (fileList.length > 0) {\r\n sections.push('\\n**Files to process:**');\r\n fileList.forEach(file => sections.push(`- ${file}`));\r\n }\r\n }\r\n\r\n // Add requirements/deliverables\r\n if (jsonObj.requirements) {\r\n const reqs = Array.isArray(jsonObj.requirements) ? jsonObj.requirements : [jsonObj.requirements];\r\n sections.push('\\n**Requirements:**');\r\n reqs.forEach((req, i) => sections.push(`${i + 1}. ${req}`));\r\n }\r\n\r\n if (jsonObj.deliverables) {\r\n const delivs = Array.isArray(jsonObj.deliverables) ? jsonObj.deliverables : [jsonObj.deliverables];\r\n sections.push('\\n**Deliverables:**');\r\n delivs.forEach(deliv => sections.push(`- ${deliv}`));\r\n }\r\n\r\n // Add batch information\r\n if (jsonObj.batch) {\r\n sections.push(`\\n**Batch:** ${jsonObj.batch}`);\r\n }\r\n\r\n // Add directory context\r\n if (jsonObj.directory) {\r\n sections.push(`\\n**Working Directory:** ${jsonObj.directory}`);\r\n }\r\n\r\n // Add acceptance criteria\r\n if (jsonObj.acceptanceCriteria) {\r\n const criteria = Array.isArray(jsonObj.acceptanceCriteria)\r\n ? jsonObj.acceptanceCriteria\r\n : [jsonObj.acceptanceCriteria];\r\n sections.push('\\n**Acceptance Criteria:**');\r\n criteria.forEach(criterion => sections.push(`- ${criterion}`));\r\n }\r\n\r\n // Add explicit instructions if present\r\n if (jsonObj.instructions) {\r\n sections.push('\\n**Instructions:**');\r\n const instrs = Array.isArray(jsonObj.instructions) ? jsonObj.instructions : [jsonObj.instructions];\r\n instrs.forEach((instr, i) => sections.push(`${i + 1}. ${instr}`));\r\n }\r\n\r\n return sections.join('\\n');\r\n}\r\n\r\n/**\r\n * Build task description from context\r\n */\r\nfunction buildTaskDescription(agentType: string, context: TaskContext): string {\r\n let desc = '';\r\n\r\n if (context.context) {\r\n // Try to parse as JSON first\r\n let contextStr = context.context.trim();\r\n\r\n // Check if context looks like JSON\r\n if ((contextStr.startsWith('{') && contextStr.endsWith('}')) ||\r\n (contextStr.startsWith('[') && contextStr.endsWith(']'))) {\r\n try {\r\n const jsonObj = JSON.parse(contextStr);\r\n desc = enrichJSONContext(jsonObj);\r\n\r\n // Add instruction footer for structured tasks\r\n if (jsonObj.files || jsonObj.deliverables) {\r\n desc += '\\n\\n**Process each item systematically and report confidence when complete.**';\r\n }\r\n } catch (e) {\r\n // Not valid JSON, treat as plain text\r\n desc = context.context;\r\n }\r\n } else {\r\n // Plain text context\r\n desc = context.context;\r\n }\r\n } else {\r\n desc = `Execute task as ${agentType} agent`;\r\n }\r\n\r\n // Add metadata fields\r\n if (context.taskId) {\r\n desc += `\\n\\n**Task ID:** ${context.taskId}`;\r\n }\r\n\r\n if (context.iteration) {\r\n desc += `\\n**Iteration:** ${context.iteration}`;\r\n }\r\n\r\n if (context.mode) {\r\n desc += `\\n**Mode:** ${context.mode}`;\r\n }\r\n\r\n if (context.priority) {\r\n desc += `\\n**Priority:** ${context.priority}`;\r\n }\r\n\r\n if (context.parentTaskId) {\r\n desc += `\\n**Parent Task:** ${context.parentTaskId}`;\r\n }\r\n\r\n return desc;\r\n}\r\n\r\n/**\r\n * Build environment context section\r\n */\r\nfunction buildEnvironmentContext(context: TaskContext): string {\r\n const env: string[] = [];\r\n\r\n if (context.taskId) env.push(`TASK_ID=${context.taskId}`);\r\n if (context.iteration) env.push(`ITERATION=${context.iteration}`);\r\n if (context.mode) env.push(`MODE=${context.mode}`);\r\n if (context.priority) env.push(`PRIORITY=${context.priority}`);\r\n if (context.parentTaskId) env.push(`PARENT_TASK_ID=${context.parentTaskId}`);\r\n\r\n if (env.length === 0) return '';\r\n\r\n return `\r\n## Environment Variables\r\n\r\n\\`\\`\\`bash\r\n${env.join('\\n')}\r\n\\`\\`\\`\r\n`;\r\n}\r\n\r\n/**\r\n * Build complete prompt for agent execution (async for iteration history)\r\n */\r\nexport async function buildAgentPrompt(\r\n definition: AgentDefinition,\r\n context: TaskContext\r\n): Promise<string> {\r\n const agentId = `${definition.name}-${context.iteration || 1}`;\r\n\r\n const sections: string[] = [];\r\n\r\n // 1. Agent definition header\r\n sections.push(`# Agent: ${definition.name}`);\r\n sections.push('');\r\n sections.push(definition.description);\r\n sections.push('');\r\n\r\n // 2. Task description\r\n sections.push('## Task');\r\n sections.push('');\r\n sections.push(buildTaskDescription(definition.name, context));\r\n sections.push('');\r\n\r\n // 3. Iteration history (Sprint 3 - Phase 2)\r\n // Load and format previous iterations if iteration > 1\r\n if (context.taskId && context.iteration && context.iteration > 1) {\r\n try {\r\n const history = await loadIterationHistory(context.taskId, agentId, context.iteration);\r\n const historyText = formatIterationHistory(history, context.iteration);\r\n sections.push(historyText);\r\n sections.push('');\r\n } catch (err) {\r\n console.warn(`[agent-prompt-builder] Failed to load iteration history:`, err);\r\n // Continue without history\r\n }\r\n }\r\n\r\n // 4. Agent definition content (from markdown file)\r\n sections.push('## Agent Definition');\r\n sections.push('');\r\n sections.push(definition.content);\r\n sections.push('');\r\n\r\n // 5. CFN Loop protocol (if agent supports it AND task context includes taskId)\r\n if (context.taskId && hasCFNLoopProtocol(definition)) {\r\n sections.push(buildCFNLoopProtocol(context.taskId, agentId));\r\n sections.push('');\r\n }\r\n\r\n // 6. Environment context\r\n const envContext = buildEnvironmentContext(context);\r\n if (envContext) {\r\n sections.push(envContext);\r\n sections.push('');\r\n }\r\n\r\n // 7. Execution instructions\r\n sections.push('## Execution Instructions');\r\n sections.push('');\r\n sections.push('1. Read and understand the task requirements');\r\n if (context.iteration && context.iteration > 1) {\r\n sections.push('2. Review iteration history and feedback from validators');\r\n sections.push('3. Address specific feedback points from previous iteration');\r\n sections.push('4. Execute your core responsibilities as defined above');\r\n } else {\r\n sections.push('2. Execute your core responsibilities as defined above');\r\n sections.push('3. Follow any protocol steps (CFN Loop, validation hooks, etc.)');\r\n }\r\n sections.push('4. Provide clear, concise output');\r\n sections.push('5. Report confidence score if applicable');\r\n sections.push('');\r\n\r\n // 8. Tool reminder\r\n if (definition.tools && definition.tools.length > 0) {\r\n sections.push('## Available Tools');\r\n sections.push('');\r\n sections.push(`You have access to: ${definition.tools.join(', ')}`);\r\n sections.push('');\r\n }\r\n\r\n return sections.join('\\n');\r\n}\r\n\r\n/**\r\n * Extract agent ID from context\r\n * If agentId is explicitly provided in context, use it; otherwise generate from name + iteration\r\n */\r\nexport function getAgentId(definition: AgentDefinition, context: TaskContext): string {\r\n if (context.agentId) {\r\n return context.agentId;\r\n }\r\n return `${definition.name}-${context.iteration || 1}`;\r\n}\r\n\r\n/**\r\n * Build system prompt for agent (optional, for structured agent behavior)\r\n */\r\nexport function buildSystemPrompt(definition: AgentDefinition): string {\r\n return `You are ${definition.name}, a specialized AI agent.\r\n\r\nType: ${definition.type || 'specialist'}\r\nModel: ${definition.model}\r\nTools: ${definition.tools.join(', ')}\r\n\r\nFollow your agent definition exactly and complete assigned tasks with high quality.`;\r\n}\r\n"],"names":["hasCFNLoopProtocol","loadIterationHistory","formatIterationHistory","buildCFNLoopProtocol","taskId","agentId","includes","enrichJSONContext","jsonObj","sections","task","push","files","fileList","split","map","f","trim","filter","Array","isArray","length","forEach","file","requirements","reqs","req","i","deliverables","delivs","deliv","batch","directory","acceptanceCriteria","criteria","criterion","instructions","instrs","instr","join","buildTaskDescription","agentType","context","desc","contextStr","startsWith","endsWith","JSON","parse","e","iteration","mode","priority","parentTaskId","buildEnvironmentContext","env","buildAgentPrompt","definition","name","description","history","historyText","err","console","warn","content","envContext","tools","getAgentId","buildSystemPrompt","type","model"],"mappings":"AAAA;;;;;;;;;CASC,GAED,SAA0BA,kBAAkB,QAAQ,+BAA+B;AACnF,SAASC,oBAAoB,EAAEC,sBAAsB,QAAQ,yBAAyB;AAYtF;;CAEC,GACD,SAASC,qBAAqBC,MAAc,EAAEC,OAAe;IAC3D,OAAO,CAAC;;;;;;;;;;uBAUa,EAAED,OAAO;;;;;;aAMnB,EAAEA,OAAO;;;cAGR,EAAEA,OAAOE,QAAQ,CAAC,eAAe,sBAAsB,IAAI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AE;QACnB,OAAOqC,QAAQrC,OAAO;IACxB;IACA,OAAO,GAAGoD,WAAWC,IAAI,CAAC,CAAC,EAAEhB,QAAQQ,SAAS,IAAI,GAAG;AACvD;AAEA;;CAEC,GACD,OAAO,SAASmB,kBAAkBZ,UAA2B;IAC3D,OAAO,CAAC,QAAQ,EAAEA,WAAWC,IAAI,CAAC;;MAE9B,EAAED,WAAWa,IAAI,IAAI,aAAa;OACjC,EAAEb,WAAWc,KAAK,CAAC;OACnB,EAAEd,WAAWU,KAAK,CAAC5B,IAAI,CAAC,MAAM;;mFAE8C,CAAC;AACpF"}
@@ -36,6 +36,9 @@
36
36
  const key = optionArgs[i];
37
37
  const value = optionArgs[i + 1];
38
38
  switch(key){
39
+ case '--agent-id':
40
+ options.agentId = value;
41
+ break;
39
42
  case '--task-id':
40
43
  options.taskId = value;
41
44
  break;
@@ -67,8 +70,9 @@
67
70
  * This is a wrapper/alias for the existing claude-flow-novice agent spawning mechanism
68
71
  * Provides the cfn-spawn naming pattern while delegating to the working implementation
69
72
  */ async function spawnAgent(options) {
70
- const { agentType, taskId, iteration, context, mode, priority, parentTaskId } = options;
73
+ const { agentType, agentId, taskId, iteration, context, mode, priority, parentTaskId } = options;
71
74
  console.log(`[cfn-spawn] Spawning agent: ${agentType}`);
75
+ if (agentId) console.log(`[cfn-spawn] Agent ID: ${agentId}`);
72
76
  if (taskId) console.log(`[cfn-spawn] Task ID: ${taskId}`);
73
77
  if (iteration) console.log(`[cfn-spawn] Iteration: ${iteration}`);
74
78
  if (context) console.log(`[cfn-spawn] Context: ${context}`);
@@ -80,6 +84,9 @@
80
84
  agentType
81
85
  ];
82
86
  // Add optional parameters
87
+ if (agentId) {
88
+ claudeArgs.push('--agent-id', agentId);
89
+ }
83
90
  if (taskId) {
84
91
  claudeArgs.push('--task-id', taskId);
85
92
  }
@@ -207,6 +214,7 @@ Usage:
207
214
  cfn-spawn <type> [options] (agent is implied)
208
215
 
209
216
  Options:
217
+ --agent-id <id> Explicit agent identifier (overrides auto-generation)
210
218
  --task-id <id> Task identifier
211
219
  --iteration <n> Iteration number
212
220
  --context <text> Context description
@@ -218,6 +226,7 @@ Examples:
218
226
  cfn-spawn agent researcher --task-id task-123 --iteration 1
219
227
  cfn-spawn coder --task-id auth-impl --context "Implement JWT auth"
220
228
  cfn-spawn reviewer --task-id auth-impl --iteration 2 --mode cli
229
+ cfn-spawn tester --agent-id tester-1-1 --task-id test-phase --iteration 1
221
230
  `);
222
231
  return;
223
232
  }