claude-flow-novice 2.10.5 → 2.10.6

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 (679) hide show
  1. package/claude-assets/agents/AGENT_LIFECYCLE.md +530 -0
  2. package/claude-assets/agents/README-VALIDATION.md +243 -0
  3. package/claude-assets/agents/custom/claude-code-expert.md +144 -0
  4. package/claude-assets/agents/custom/test-mcp-access.md +26 -0
  5. package/claude-assets/agents/project-only-agents/npm-package-specialist.md +347 -0
  6. package/claude-assets/agents/validate-agent.js +841 -0
  7. package/claude-assets/commands/agents/README.md +10 -0
  8. package/claude-assets/commands/agents/agent-capabilities.md +21 -0
  9. package/claude-assets/commands/agents/agent-coordination.md +28 -0
  10. package/claude-assets/commands/agents/agent-spawning.md +28 -0
  11. package/claude-assets/commands/agents/agent-types.md +26 -0
  12. package/claude-assets/commands/analysis/COMMAND_COMPLIANCE_REPORT.md +54 -0
  13. package/claude-assets/commands/analysis/README.md +9 -0
  14. package/claude-assets/commands/analysis/bottleneck-detect.md +162 -0
  15. package/claude-assets/commands/analysis/performance-bottlenecks.md +59 -0
  16. package/claude-assets/commands/analysis/performance-report.md +25 -0
  17. package/claude-assets/commands/analysis/token-efficiency.md +45 -0
  18. package/claude-assets/commands/analysis/token-usage.md +25 -0
  19. package/claude-assets/commands/automation/README.md +9 -0
  20. package/claude-assets/commands/automation/auto-agent.md +122 -0
  21. package/claude-assets/commands/automation/self-healing.md +106 -0
  22. package/claude-assets/commands/automation/session-memory.md +90 -0
  23. package/claude-assets/commands/automation/smart-agents.md +73 -0
  24. package/claude-assets/commands/automation/smart-spawn.md +25 -0
  25. package/claude-assets/commands/automation/workflow-select.md +25 -0
  26. package/claude-assets/commands/cfn/CFN_COORDINATOR_PARAMETERS.md +660 -0
  27. package/claude-assets/commands/cfn/CFN_LOOP_FRONTEND.md +741 -0
  28. package/claude-assets/commands/cfn/CFN_LOOP_TASK_MODE.md +353 -0
  29. package/claude-assets/commands/cfn/README.md +157 -0
  30. package/claude-assets/commands/cfn/auto-compact.md +80 -0
  31. package/claude-assets/commands/cfn/cfn-claude-sync.md +303 -0
  32. package/claude-assets/commands/cfn/cfn-loop-document.md +480 -0
  33. package/claude-assets/commands/cfn/cfn-loop-epic.md +478 -0
  34. package/claude-assets/commands/cfn/cfn-loop-frontend.md +555 -0
  35. package/claude-assets/commands/cfn/cfn-loop-single.md +256 -0
  36. package/claude-assets/commands/cfn/cfn-loop-sprints.md +396 -0
  37. package/claude-assets/commands/cfn/cfn-loop.md +517 -0
  38. package/claude-assets/commands/cfn/cfn-mode.md +20 -0
  39. package/claude-assets/commands/cfn/cfn-optimize-agents.md +103 -0
  40. package/claude-assets/commands/cfn/claude-md.md +64 -0
  41. package/claude-assets/commands/cfn/claude-soul.md +22 -0
  42. package/claude-assets/commands/cfn/context-curate.md +211 -0
  43. package/claude-assets/commands/cfn/context-inject.md +262 -0
  44. package/claude-assets/commands/cfn/context-query.md +215 -0
  45. package/claude-assets/commands/cfn/context-reflect.md +165 -0
  46. package/claude-assets/commands/cfn/context-stats.md +294 -0
  47. package/claude-assets/commands/cfn/cost-savings-off.md +35 -0
  48. package/claude-assets/commands/cfn/cost-savings-on.md +35 -0
  49. package/claude-assets/commands/cfn/cost-savings-status.md +34 -0
  50. package/claude-assets/commands/cfn/custom-routing-activate.md +55 -0
  51. package/claude-assets/commands/cfn/custom-routing-deactivate.md +46 -0
  52. package/claude-assets/commands/cfn/dependency-recommendations.md +171 -0
  53. package/claude-assets/commands/cfn/fullstack.md +179 -0
  54. package/claude-assets/commands/cfn/github-commit.md +289 -0
  55. package/claude-assets/commands/cfn/github.md +221 -0
  56. package/claude-assets/commands/cfn/hello-world-tests.md +381 -0
  57. package/claude-assets/commands/cfn/hooks.md +38 -0
  58. package/claude-assets/commands/cfn/launch-web-dashboard.md +295 -0
  59. package/claude-assets/commands/cfn/list-agents-rebuild.md +205 -0
  60. package/claude-assets/commands/cfn/metrics-summary.md +58 -0
  61. package/claude-assets/commands/cfn/neural.md +39 -0
  62. package/claude-assets/commands/cfn/parse-epic.md +357 -0
  63. package/claude-assets/commands/cfn/performance.md +41 -0
  64. package/claude-assets/commands/cfn/sparc.md +46 -0
  65. package/claude-assets/commands/cfn/suggest-improvements.md +95 -0
  66. package/claude-assets/commands/cfn/suggest-templates.md +147 -0
  67. package/claude-assets/commands/cfn/swarm.md +24 -0
  68. package/claude-assets/commands/cfn/switch-api.md +53 -0
  69. package/claude-assets/commands/cfn/workflow.md +295 -0
  70. package/claude-assets/commands/cfn/write-plan.md +104 -0
  71. package/claude-assets/commands/claude-md.js +237 -0
  72. package/claude-assets/commands/claude-soul.js +28 -0
  73. package/claude-assets/commands/cli-integration.js +216 -0
  74. package/claude-assets/commands/coordination/README.md +9 -0
  75. package/claude-assets/commands/coordination/agent-spawn.md +25 -0
  76. package/claude-assets/commands/coordination/coordination-system.md +88 -0
  77. package/claude-assets/commands/coordination/init.md +44 -0
  78. package/claude-assets/commands/coordination/orchestrate.md +43 -0
  79. package/claude-assets/commands/coordination/spawn.md +45 -0
  80. package/claude-assets/commands/coordination/swarm-init.md +85 -0
  81. package/claude-assets/commands/coordination/task-orchestrate.md +25 -0
  82. package/claude-assets/commands/github/README.md +11 -0
  83. package/claude-assets/commands/github/code-review-swarm.md +514 -0
  84. package/claude-assets/commands/github/code-review.md +25 -0
  85. package/claude-assets/commands/github/github-modes.md +147 -0
  86. package/claude-assets/commands/github/github-swarm.md +121 -0
  87. package/claude-assets/commands/github/issue-tracker.md +292 -0
  88. package/claude-assets/commands/github/issue-triage.md +25 -0
  89. package/claude-assets/commands/github/multi-repo-swarm.md +519 -0
  90. package/claude-assets/commands/github/pr-enhance.md +26 -0
  91. package/claude-assets/commands/github/pr-manager.md +170 -0
  92. package/claude-assets/commands/github/project-board-sync.md +471 -0
  93. package/claude-assets/commands/github/release-manager.md +338 -0
  94. package/claude-assets/commands/github/release-swarm.md +544 -0
  95. package/claude-assets/commands/github/repo-analyze.md +25 -0
  96. package/claude-assets/commands/github/repo-architect.md +367 -0
  97. package/claude-assets/commands/github/swarm-issue.md +482 -0
  98. package/claude-assets/commands/github/swarm-pr.md +285 -0
  99. package/claude-assets/commands/github/sync-coordinator.md +301 -0
  100. package/claude-assets/commands/github/workflow-automation.md +442 -0
  101. package/claude-assets/commands/github.js +638 -0
  102. package/claude-assets/commands/hive-mind/README.md +17 -0
  103. package/claude-assets/commands/hive-mind/hive-mind-consensus.md +8 -0
  104. package/claude-assets/commands/hive-mind/hive-mind-init.md +18 -0
  105. package/claude-assets/commands/hive-mind/hive-mind-memory.md +8 -0
  106. package/claude-assets/commands/hive-mind/hive-mind-metrics.md +8 -0
  107. package/claude-assets/commands/hive-mind/hive-mind-resume.md +8 -0
  108. package/claude-assets/commands/hive-mind/hive-mind-sessions.md +8 -0
  109. package/claude-assets/commands/hive-mind/hive-mind-spawn.md +21 -0
  110. package/claude-assets/commands/hive-mind/hive-mind-status.md +8 -0
  111. package/claude-assets/commands/hive-mind/hive-mind-stop.md +8 -0
  112. package/claude-assets/commands/hive-mind/hive-mind-wizard.md +8 -0
  113. package/claude-assets/commands/hive-mind/hive-mind.md +27 -0
  114. package/claude-assets/commands/hooks/README.md +11 -0
  115. package/claude-assets/commands/hooks/overview.md +58 -0
  116. package/claude-assets/commands/hooks/post-edit.md +117 -0
  117. package/claude-assets/commands/hooks/post-task.md +112 -0
  118. package/claude-assets/commands/hooks/pre-edit.md +113 -0
  119. package/claude-assets/commands/hooks/pre-task.md +111 -0
  120. package/claude-assets/commands/hooks/session-end.md +118 -0
  121. package/claude-assets/commands/hooks/session-start.md +9 -0
  122. package/claude-assets/commands/hooks/setup.md +103 -0
  123. package/claude-assets/commands/hooks.js +651 -0
  124. package/claude-assets/commands/index.js +119 -0
  125. package/claude-assets/commands/memory/README.md +9 -0
  126. package/claude-assets/commands/memory/memory-bank.md +58 -0
  127. package/claude-assets/commands/memory/memory-persist.md +25 -0
  128. package/claude-assets/commands/memory/memory-search.md +25 -0
  129. package/claude-assets/commands/memory/memory-usage.md +25 -0
  130. package/claude-assets/commands/memory/neural.md +47 -0
  131. package/claude-assets/commands/memory/usage.md +46 -0
  132. package/claude-assets/commands/monitoring/README.md +9 -0
  133. package/claude-assets/commands/monitoring/agent-metrics.md +25 -0
  134. package/claude-assets/commands/monitoring/agents.md +44 -0
  135. package/claude-assets/commands/monitoring/real-time-view.md +25 -0
  136. package/claude-assets/commands/monitoring/status.md +46 -0
  137. package/claude-assets/commands/monitoring/swarm-monitor.md +25 -0
  138. package/claude-assets/commands/neural.js +572 -0
  139. package/claude-assets/commands/optimization/README.md +9 -0
  140. package/claude-assets/commands/optimization/auto-topology.md +62 -0
  141. package/claude-assets/commands/optimization/cache-manage.md +25 -0
  142. package/claude-assets/commands/optimization/parallel-execute.md +25 -0
  143. package/claude-assets/commands/optimization/parallel-execution.md +50 -0
  144. package/claude-assets/commands/optimization/topology-optimize.md +25 -0
  145. package/claude-assets/commands/pair/README.md +261 -0
  146. package/claude-assets/commands/pair/commands.md +546 -0
  147. package/claude-assets/commands/pair/config.md +510 -0
  148. package/claude-assets/commands/pair/examples.md +512 -0
  149. package/claude-assets/commands/pair/modes.md +348 -0
  150. package/claude-assets/commands/pair/session.md +407 -0
  151. package/claude-assets/commands/pair/start.md +209 -0
  152. package/claude-assets/commands/parse-epic.js +180 -0
  153. package/claude-assets/commands/performance.js +582 -0
  154. package/claude-assets/commands/register-all-commands.js +320 -0
  155. package/claude-assets/commands/register-claude-md.js +82 -0
  156. package/claude-assets/commands/register-claude-soul.js +80 -0
  157. package/claude-assets/commands/sparc/analyzer.md +52 -0
  158. package/claude-assets/commands/sparc/architect.md +53 -0
  159. package/claude-assets/commands/sparc/batch-executor.md +54 -0
  160. package/claude-assets/commands/sparc/coder.md +54 -0
  161. package/claude-assets/commands/sparc/debugger.md +54 -0
  162. package/claude-assets/commands/sparc/designer.md +53 -0
  163. package/claude-assets/commands/sparc/documenter.md +54 -0
  164. package/claude-assets/commands/sparc/innovator.md +54 -0
  165. package/claude-assets/commands/sparc/memory-manager.md +54 -0
  166. package/claude-assets/commands/sparc/optimizer.md +54 -0
  167. package/claude-assets/commands/sparc/orchestrator.md +132 -0
  168. package/claude-assets/commands/sparc/researcher.md +54 -0
  169. package/claude-assets/commands/sparc/reviewer.md +54 -0
  170. package/claude-assets/commands/sparc/sparc-modes.md +174 -0
  171. package/claude-assets/commands/sparc/swarm-coordinator.md +54 -0
  172. package/claude-assets/commands/sparc/tdd.md +54 -0
  173. package/claude-assets/commands/sparc/tester.md +54 -0
  174. package/claude-assets/commands/sparc/workflow-manager.md +54 -0
  175. package/claude-assets/commands/sparc.js +110 -0
  176. package/claude-assets/commands/stream-chain/pipeline.md +121 -0
  177. package/claude-assets/commands/stream-chain/run.md +70 -0
  178. package/claude-assets/commands/swarm/README.md +15 -0
  179. package/claude-assets/commands/swarm/analysis.md +95 -0
  180. package/claude-assets/commands/swarm/development.md +96 -0
  181. package/claude-assets/commands/swarm/examples.md +168 -0
  182. package/claude-assets/commands/swarm/maintenance.md +102 -0
  183. package/claude-assets/commands/swarm/optimization.md +117 -0
  184. package/claude-assets/commands/swarm/research.md +136 -0
  185. package/claude-assets/commands/swarm/swarm-analysis.md +8 -0
  186. package/claude-assets/commands/swarm/swarm-background.md +8 -0
  187. package/claude-assets/commands/swarm/swarm-init.md +19 -0
  188. package/claude-assets/commands/swarm/swarm-modes.md +8 -0
  189. package/claude-assets/commands/swarm/swarm-monitor.md +8 -0
  190. package/claude-assets/commands/swarm/swarm-spawn.md +19 -0
  191. package/claude-assets/commands/swarm/swarm-status.md +8 -0
  192. package/claude-assets/commands/swarm/swarm-strategies.md +8 -0
  193. package/claude-assets/commands/swarm/swarm.md +27 -0
  194. package/claude-assets/commands/swarm/testing.md +131 -0
  195. package/claude-assets/commands/swarm.js +423 -0
  196. package/claude-assets/commands/testing/playwright-e2e.md +288 -0
  197. package/claude-assets/commands/training/README.md +9 -0
  198. package/claude-assets/commands/training/model-update.md +25 -0
  199. package/claude-assets/commands/training/neural-patterns.md +74 -0
  200. package/claude-assets/commands/training/neural-train.md +25 -0
  201. package/claude-assets/commands/training/pattern-learn.md +25 -0
  202. package/claude-assets/commands/training/specialization.md +63 -0
  203. package/claude-assets/commands/truth/start.md +143 -0
  204. package/claude-assets/commands/validate-commands.js +223 -0
  205. package/claude-assets/commands/verify/check.md +50 -0
  206. package/claude-assets/commands/verify/start.md +128 -0
  207. package/claude-assets/commands/workflow.js +606 -0
  208. package/claude-assets/commands/workflows/README.md +9 -0
  209. package/claude-assets/commands/workflows/development.md +78 -0
  210. package/claude-assets/commands/workflows/research.md +63 -0
  211. package/claude-assets/commands/workflows/workflow-create.md +25 -0
  212. package/claude-assets/commands/workflows/workflow-execute.md +25 -0
  213. package/claude-assets/commands/workflows/workflow-export.md +25 -0
  214. package/claude-assets/hooks/cfn-BACKUP_USAGE.md +243 -0
  215. package/claude-assets/hooks/cfn-invoke-post-edit.sh +87 -0
  216. package/claude-assets/hooks/cfn-post-edit-cfn-retrospective.sh +79 -0
  217. package/claude-assets/hooks/cfn-post-edit.config.json +37 -0
  218. package/claude-assets/hooks/cfn-post-edit.sh +21 -0
  219. package/claude-assets/hooks/cfn-pre-edit-backup.sh +71 -0
  220. package/claude-assets/hooks/cfn-restore-from-backup.sh +37 -0
  221. package/claude-assets/hooks/post-edit.config.json +12 -0
  222. package/claude-assets/root-claude-distribute/CFN-CLAUDE.md +796 -0
  223. package/claude-assets/skills/CFN-LOOP-VALIDATION.md +202 -0
  224. package/claude-assets/skills/REDIS-COORDINATION.md +187 -0
  225. package/claude-assets/skills/SKILL.md +229 -0
  226. package/claude-assets/skills/agent-discovery/agents-registry.json +484 -0
  227. package/claude-assets/skills/cfn-ace-system/SKILL.md +364 -0
  228. package/claude-assets/skills/cfn-ace-system/add-bullet.sh +145 -0
  229. package/claude-assets/skills/cfn-ace-system/analyze-anti-pattern-effectiveness.sh +56 -0
  230. package/claude-assets/skills/cfn-ace-system/classify-task.sh +18 -0
  231. package/claude-assets/skills/cfn-ace-system/export-ace-metrics.sh +48 -0
  232. package/claude-assets/skills/cfn-ace-system/extract-tags.sh +385 -0
  233. package/claude-assets/skills/cfn-ace-system/format-negative-context.sh +180 -0
  234. package/claude-assets/skills/cfn-ace-system/init-indexes.sql +160 -0
  235. package/claude-assets/skills/cfn-ace-system/invoke-context-curate.sh +192 -0
  236. package/claude-assets/skills/cfn-ace-system/invoke-context-inject.sh +361 -0
  237. package/claude-assets/skills/cfn-ace-system/invoke-context-query.sh +139 -0
  238. package/claude-assets/skills/cfn-ace-system/invoke-context-reflect.sh +343 -0
  239. package/claude-assets/skills/cfn-ace-system/invoke-context-stats.sh +227 -0
  240. package/claude-assets/skills/cfn-ace-system/log-merge.sh +67 -0
  241. package/claude-assets/skills/cfn-ace-system/monitor-injection-performance.sh +138 -0
  242. package/claude-assets/skills/cfn-ace-system/optimize-injection-pipeline.sh +169 -0
  243. package/claude-assets/skills/cfn-ace-system/query-anti-patterns.sh +276 -0
  244. package/claude-assets/skills/cfn-ace-system/query-contexts.sh +150 -0
  245. package/claude-assets/skills/cfn-ace-system/query-reflections.sh +35 -0
  246. package/claude-assets/skills/cfn-ace-system/schema/001-create-context-reflections.sql +237 -0
  247. package/claude-assets/skills/cfn-ace-system/schema/README.md +723 -0
  248. package/claude-assets/skills/cfn-ace-system/schema/SCHEMA_DESIGN_SUMMARY.md +564 -0
  249. package/claude-assets/skills/cfn-ace-system/schema/populate-test-data-simple.sh +62 -0
  250. package/claude-assets/skills/cfn-ace-system/schema/populate-test-data.sh +247 -0
  251. package/claude-assets/skills/cfn-ace-system/schema/run-migration.sh +231 -0
  252. package/claude-assets/skills/cfn-ace-system/schema/validate-schema.sql +280 -0
  253. package/claude-assets/skills/cfn-ace-system/score-relevance-adapter.sh +138 -0
  254. package/claude-assets/skills/cfn-ace-system/score-relevance.sh +253 -0
  255. package/claude-assets/skills/cfn-ace-system/sprint-7-lessons.json +46 -0
  256. package/claude-assets/skills/cfn-ace-system/store-reflection.sh +46 -0
  257. package/claude-assets/skills/cfn-ace-system/test-ace-skill.sh +312 -0
  258. package/claude-assets/skills/cfn-ace-system/track-ab-test.sh +42 -0
  259. package/claude-assets/skills/cfn-ace-system/update-reflection.sh +41 -0
  260. package/claude-assets/skills/cfn-agent-discovery/SKILL.md +40 -0
  261. package/claude-assets/skills/cfn-agent-discovery/agents-registry-clean.json +0 -0
  262. package/claude-assets/skills/cfn-agent-discovery/agents-registry-fixed.json +19 -0
  263. package/claude-assets/skills/cfn-agent-discovery/agents-registry.json +718 -0
  264. package/claude-assets/skills/cfn-agent-discovery/discover-agents.py +184 -0
  265. package/claude-assets/skills/cfn-agent-discovery/discover-agents.sh +87 -0
  266. package/claude-assets/skills/cfn-agent-discovery/invoke-registry.sh +11 -0
  267. package/claude-assets/skills/cfn-agent-discovery/temp_script.py +0 -0
  268. package/claude-assets/skills/cfn-agent-execution/execute-agent.sh +126 -0
  269. package/claude-assets/skills/cfn-agent-output-processing/SKILL.md +359 -0
  270. package/claude-assets/skills/cfn-agent-selector/SKILL.md +90 -0
  271. package/claude-assets/skills/cfn-agent-selector/select-agents.sh +112 -0
  272. package/claude-assets/skills/cfn-agent-spawning/README.md +140 -0
  273. package/claude-assets/skills/cfn-agent-spawning/SKILL.md +135 -0
  274. package/claude-assets/skills/cfn-agent-spawning/agent-selection-guide.md +814 -0
  275. package/claude-assets/skills/cfn-agent-spawning/check-dependencies.sh +30 -0
  276. package/claude-assets/skills/cfn-agent-spawning/spawn-agent.sh +263 -0
  277. package/claude-assets/skills/cfn-agent-spawning/spawn-templates.sh +613 -0
  278. package/claude-assets/skills/cfn-agent-swap/SKILL.md +36 -0
  279. package/claude-assets/skills/cfn-agent-swap/recommend-swap.sh +60 -0
  280. package/claude-assets/skills/cfn-analytics/README.md +58 -0
  281. package/claude-assets/skills/cfn-analytics/description-refinement-guide.md +164 -0
  282. package/claude-assets/skills/cfn-analytics/log-skill-invocation.js +122 -0
  283. package/claude-assets/skills/cfn-analytics/run-production-criteria-tests.sh +126 -0
  284. package/claude-assets/skills/cfn-analytics/skill-analytics-dashboard.js +113 -0
  285. package/claude-assets/skills/cfn-analytics/skill-invocation-hook.sh +28 -0
  286. package/claude-assets/skills/cfn-analytics/skill-invocations.sql +58 -0
  287. package/claude-assets/skills/cfn-analytics/test-corpus.json +32 -0
  288. package/claude-assets/skills/cfn-analytics/test-data-generator.js +115 -0
  289. package/claude-assets/skills/cfn-analytics/test-manual-override-rate.js +285 -0
  290. package/claude-assets/skills/cfn-analytics/validate-skill-selection.js +188 -0
  291. package/claude-assets/skills/cfn-api-validation/test-endpoints.sh +54 -0
  292. package/claude-assets/skills/cfn-automatic-memory-persistence/SKILL.md +73 -0
  293. package/claude-assets/skills/cfn-automatic-memory-persistence/persist-agent-output.sh +49 -0
  294. package/claude-assets/skills/cfn-automatic-memory-persistence/query-agent-history.sh +35 -0
  295. package/claude-assets/skills/cfn-automatic-memory-persistence/test-memory-persistence.sh +235 -0
  296. package/claude-assets/skills/cfn-complexity-estimator/SKILL.md +96 -0
  297. package/claude-assets/skills/cfn-complexity-estimator/estimate-complexity.sh +144 -0
  298. package/claude-assets/skills/cfn-config-management/README.md +42 -0
  299. package/claude-assets/skills/cfn-config-management/SKILL.md +34 -0
  300. package/claude-assets/skills/cfn-config-management/check-dependencies.sh +56 -0
  301. package/claude-assets/skills/cfn-config-management/config.json +32 -0
  302. package/claude-assets/skills/cfn-config-management/manage-config.sh +113 -0
  303. package/claude-assets/skills/cfn-context-pruner/SKILL.md +75 -0
  304. package/claude-assets/skills/cfn-context-pruner/prune-context.sh +73 -0
  305. package/claude-assets/skills/cfn-defense-in-depth/SKILL.md +133 -0
  306. package/claude-assets/skills/cfn-dependency-extractor/SKILL.md +35 -0
  307. package/claude-assets/skills/cfn-dependency-extractor/extract-dependencies.sh +66 -0
  308. package/claude-assets/skills/cfn-epic-decomposer/SKILL.md +44 -0
  309. package/claude-assets/skills/cfn-epic-decomposer/decompose-epic.sh +104 -0
  310. package/claude-assets/skills/cfn-event-bus/README.md +299 -0
  311. package/claude-assets/skills/cfn-event-bus/SKILL.md +412 -0
  312. package/claude-assets/skills/cfn-event-bus/config.json +111 -0
  313. package/claude-assets/skills/cfn-event-bus/eventbus-wrapper.cjs +69 -0
  314. package/claude-assets/skills/cfn-event-bus/invoke-event-publish.sh +147 -0
  315. package/claude-assets/skills/cfn-event-bus/invoke-event-subscribe.sh +171 -0
  316. package/claude-assets/skills/cfn-event-bus/invoke-lifecycle-track.sh +201 -0
  317. package/claude-assets/skills/cfn-event-bus/test-event-bus.sh +280 -0
  318. package/claude-assets/skills/cfn-fleet-manager/README.md +74 -0
  319. package/claude-assets/skills/cfn-fleet-manager/SKILL.md +412 -0
  320. package/claude-assets/skills/cfn-fleet-manager/config.json +60 -0
  321. package/claude-assets/skills/cfn-fleet-manager/invoke-fleet-allocate.sh +182 -0
  322. package/claude-assets/skills/cfn-fleet-manager/invoke-fleet-balance.sh +239 -0
  323. package/claude-assets/skills/cfn-fleet-manager/invoke-fleet-metrics.sh +193 -0
  324. package/claude-assets/skills/cfn-fleet-manager/invoke-fleet-register.sh +124 -0
  325. package/claude-assets/skills/cfn-fleet-manager/test-fleet-manager.sh +345 -0
  326. package/claude-assets/skills/cfn-hook-pipeline/README.md +74 -0
  327. package/claude-assets/skills/cfn-hook-pipeline/SKILL.md +148 -0
  328. package/claude-assets/skills/cfn-hook-pipeline/auto-resolve.sh +66 -0
  329. package/claude-assets/skills/cfn-hook-pipeline/check-dependencies.sh +40 -0
  330. package/claude-assets/skills/cfn-hook-pipeline/feedback-resolver.sh +452 -0
  331. package/claude-assets/skills/cfn-hook-pipeline/post-edit-handler.sh +154 -0
  332. package/claude-assets/skills/cfn-hook-pipeline/security-scan.json +60 -0
  333. package/claude-assets/skills/cfn-hook-pipeline/security-scanner.sh +121 -0
  334. package/claude-assets/skills/cfn-hook-pipeline/test-root-warning-resolution.sh +148 -0
  335. package/claude-assets/skills/cfn-hybrid-routing/README.md +50 -0
  336. package/claude-assets/skills/cfn-hybrid-routing/SKILL.md +46 -0
  337. package/claude-assets/skills/cfn-hybrid-routing/check-dependencies.sh +52 -0
  338. package/claude-assets/skills/cfn-hybrid-routing/config.json +26 -0
  339. package/claude-assets/skills/cfn-hybrid-routing/spawn-worker.sh +44 -0
  340. package/claude-assets/skills/cfn-improvement-recommender/SKILL.md +33 -0
  341. package/claude-assets/skills/cfn-improvement-recommender/recommend-improvements.sh +92 -0
  342. package/claude-assets/skills/cfn-intervention-detector/SKILL.md +39 -0
  343. package/claude-assets/skills/cfn-intervention-detector/detect-intervention.sh +111 -0
  344. package/claude-assets/skills/cfn-intervention-orchestrator/SKILL.md +43 -0
  345. package/claude-assets/skills/cfn-intervention-orchestrator/execute-intervention.sh +59 -0
  346. package/claude-assets/skills/cfn-loop-orchestration/README.md +41 -0
  347. package/claude-assets/skills/cfn-loop-orchestration/SKILL.md +299 -0
  348. package/claude-assets/skills/cfn-loop-orchestration/helpers/auto-tune-timeouts.sh +228 -0
  349. package/claude-assets/skills/cfn-loop-orchestration/helpers/consensus.sh +84 -0
  350. package/claude-assets/skills/cfn-loop-orchestration/helpers/context-injection.sh +142 -0
  351. package/claude-assets/skills/cfn-loop-orchestration/helpers/context-lookup.sh +359 -0
  352. package/claude-assets/skills/cfn-loop-orchestration/helpers/deliverable-verifier.sh +71 -0
  353. package/claude-assets/skills/cfn-loop-orchestration/helpers/gate-check.sh +90 -0
  354. package/claude-assets/skills/cfn-loop-orchestration/helpers/iteration-manager.sh +87 -0
  355. package/claude-assets/skills/cfn-loop-orchestration/helpers/spawn-agents.sh +271 -0
  356. package/claude-assets/skills/cfn-loop-orchestration/helpers/timeout-calculator.sh +51 -0
  357. package/claude-assets/skills/cfn-loop-orchestration/inject-loop-context.sh +41 -0
  358. package/claude-assets/skills/cfn-loop-orchestration/monitor-execution.sh +156 -0
  359. package/claude-assets/skills/cfn-loop-orchestration/orchestrate.sh +884 -0
  360. package/claude-assets/skills/cfn-loop-orchestration/orchestrate.sh.backup +840 -0
  361. package/claude-assets/skills/cfn-loop-orchestration/security_utils.sh +99 -0
  362. package/claude-assets/skills/cfn-loop-orchestration/test-cfn-orchestration.sh +281 -0
  363. package/claude-assets/skills/cfn-loop-orchestration/test-edge-cases.sh +188 -0
  364. package/claude-assets/skills/cfn-loop-validation/README.md +256 -0
  365. package/claude-assets/skills/cfn-loop-validation/SKILL.md +353 -0
  366. package/claude-assets/skills/cfn-loop-validation/check-dependencies.sh +31 -0
  367. package/claude-assets/skills/cfn-loop-validation/config.json +161 -0
  368. package/claude-assets/skills/cfn-loop-validation/consensus-calculator.js +477 -0
  369. package/claude-assets/skills/cfn-loop-validation/evidence-chain.sql +163 -0
  370. package/claude-assets/skills/cfn-loop-validation/examples/README.md +453 -0
  371. package/claude-assets/skills/cfn-loop-validation/examples/coordinator-full-cfn-loop.sh +234 -0
  372. package/claude-assets/skills/cfn-loop-validation/examples/coordinator-loop2-consensus.sh +132 -0
  373. package/claude-assets/skills/cfn-loop-validation/examples/coordinator-loop3-gate.sh +115 -0
  374. package/claude-assets/skills/cfn-loop-validation/examples/coordinator-redis-integration.sh +186 -0
  375. package/claude-assets/skills/cfn-loop-validation/orchestrate-cfn-loop.sh +252 -0
  376. package/claude-assets/skills/cfn-loop-validation/validate-iteration.sh +134 -0
  377. package/claude-assets/skills/cfn-loop-validation.sh +70 -0
  378. package/claude-assets/skills/cfn-loop2-output-processing/SKILL.md +163 -0
  379. package/claude-assets/skills/cfn-loop2-output-processing/execute-and-extract.sh +77 -0
  380. package/claude-assets/skills/cfn-loop2-output-processing/execute-and-extract.sh.backup +36 -0
  381. package/claude-assets/skills/cfn-loop2-output-processing/parse-feedback.sh +147 -0
  382. package/claude-assets/skills/cfn-loop2-output-processing/process-validator-output.sh +275 -0
  383. package/claude-assets/skills/cfn-loop2-output-processing/test-bug27-fix.sh +200 -0
  384. package/claude-assets/skills/cfn-loop2-output-processing/test-loop2-processing.sh +113 -0
  385. package/claude-assets/skills/cfn-loop3-output-processing/AGENT_COMPLETION_PROTOCOL.md +206 -0
  386. package/claude-assets/skills/cfn-loop3-output-processing/SKILL.md +421 -0
  387. package/claude-assets/skills/cfn-loop3-output-processing/calculate-confidence.sh +28 -0
  388. package/claude-assets/skills/cfn-loop3-output-processing/execute-and-extract.sh +85 -0
  389. package/claude-assets/skills/cfn-loop3-output-processing/parse-confidence.sh +31 -0
  390. package/claude-assets/skills/cfn-loop3-output-processing/test-agent-timeout.sh +327 -0
  391. package/claude-assets/skills/cfn-loop3-output-processing/test-loop3-processing.sh +155 -0
  392. package/claude-assets/skills/cfn-loop3-output-processing/verify-deliverables.sh +42 -0
  393. package/claude-assets/skills/cfn-marketing-ad-campaigns/SKILL.md +392 -0
  394. package/claude-assets/skills/cfn-marketing-ad-campaigns/operations/create-campaign.sh +231 -0
  395. package/claude-assets/skills/cfn-marketing-ad-campaigns/operations/get-campaign-performance.sh +190 -0
  396. package/claude-assets/skills/cfn-marketing-ad-campaigns/operations/pause-campaign.sh +142 -0
  397. package/claude-assets/skills/cfn-marketing-ad-campaigns/operations/set-budget.sh +181 -0
  398. package/claude-assets/skills/cfn-marketing-ad-campaigns/operations/update-bid-strategy.sh +133 -0
  399. package/claude-assets/skills/cfn-marketing-analytics-data/SKILL.md +124 -0
  400. package/claude-assets/skills/cfn-marketing-analytics-data/operations/get-ad-performance.sh +105 -0
  401. package/claude-assets/skills/cfn-marketing-analytics-data/operations/get-conversion-funnel.sh +102 -0
  402. package/claude-assets/skills/cfn-marketing-analytics-data/operations/get-email-performance.sh +105 -0
  403. package/claude-assets/skills/cfn-marketing-analytics-data/operations/get-social-engagement.sh +105 -0
  404. package/claude-assets/skills/cfn-marketing-analytics-data/operations/get-website-traffic.sh +107 -0
  405. package/claude-assets/skills/cfn-marketing-chatbot-conversations/SKILL.md +340 -0
  406. package/claude-assets/skills/cfn-marketing-chatbot-conversations/operations/get-conversation-history.sh +121 -0
  407. package/claude-assets/skills/cfn-marketing-chatbot-conversations/operations/qualify-lead.sh +156 -0
  408. package/claude-assets/skills/cfn-marketing-chatbot-conversations/operations/schedule-demo.sh +181 -0
  409. package/claude-assets/skills/cfn-marketing-chatbot-conversations/operations/send-message.sh +137 -0
  410. package/claude-assets/skills/cfn-marketing-chatbot-conversations/operations/transfer-to-human.sh +179 -0
  411. package/claude-assets/skills/cfn-marketing-competitive-intel/SKILL.md +350 -0
  412. package/claude-assets/skills/cfn-marketing-competitive-intel/operations/get-backlink-profile.sh +154 -0
  413. package/claude-assets/skills/cfn-marketing-competitive-intel/operations/get-keyword-rankings.sh +173 -0
  414. package/claude-assets/skills/cfn-marketing-competitive-intel/operations/get-trending-topics.sh +147 -0
  415. package/claude-assets/skills/cfn-marketing-competitive-intel/operations/monitor-competitor.sh +146 -0
  416. package/claude-assets/skills/cfn-marketing-competitive-intel/operations/search-brand-mentions.sh +167 -0
  417. package/claude-assets/skills/cfn-marketing-crm-contacts/SKILL.md +116 -0
  418. package/claude-assets/skills/cfn-marketing-crm-contacts/operations/add-to-segment.sh +78 -0
  419. package/claude-assets/skills/cfn-marketing-crm-contacts/operations/create-contact.sh +113 -0
  420. package/claude-assets/skills/cfn-marketing-crm-contacts/operations/get-contact.sh +86 -0
  421. package/claude-assets/skills/cfn-marketing-crm-contacts/operations/remove-from-segment.sh +78 -0
  422. package/claude-assets/skills/cfn-marketing-crm-contacts/operations/update-contact.sh +120 -0
  423. package/claude-assets/skills/cfn-marketing-email-campaigns/SKILL.md +106 -0
  424. package/claude-assets/skills/cfn-marketing-email-campaigns/operations/create-campaign.sh +123 -0
  425. package/claude-assets/skills/cfn-marketing-email-campaigns/operations/get-campaign-stats.sh +66 -0
  426. package/claude-assets/skills/cfn-marketing-email-campaigns/operations/list-templates.sh +68 -0
  427. package/claude-assets/skills/cfn-marketing-email-campaigns/operations/schedule-campaign.sh +85 -0
  428. package/claude-assets/skills/cfn-marketing-email-campaigns/operations/send-test-email.sh +81 -0
  429. package/claude-assets/skills/cfn-marketing-landing-pages/SKILL.md +366 -0
  430. package/claude-assets/skills/cfn-marketing-landing-pages/operations/create-ab-test.sh +231 -0
  431. package/claude-assets/skills/cfn-marketing-landing-pages/operations/create-landing-page.sh +190 -0
  432. package/claude-assets/skills/cfn-marketing-landing-pages/operations/get-page-performance.sh +137 -0
  433. package/claude-assets/skills/cfn-marketing-landing-pages/operations/publish-page.sh +120 -0
  434. package/claude-assets/skills/cfn-marketing-landing-pages/operations/unpublish-page.sh +108 -0
  435. package/claude-assets/skills/cfn-marketing-media-monitoring/SKILL.md +202 -0
  436. package/claude-assets/skills/cfn-marketing-media-monitoring/operations/create-crisis-alert.sh +104 -0
  437. package/claude-assets/skills/cfn-marketing-media-monitoring/operations/export-report.sh +92 -0
  438. package/claude-assets/skills/cfn-marketing-media-monitoring/operations/get-sentiment-analysis.sh +85 -0
  439. package/claude-assets/skills/cfn-marketing-media-monitoring/operations/search-mentions.sh +86 -0
  440. package/claude-assets/skills/cfn-marketing-media-outreach/SKILL.md +168 -0
  441. package/claude-assets/skills/cfn-marketing-media-outreach/operations/search-journalists.sh +74 -0
  442. package/claude-assets/skills/cfn-marketing-media-outreach/operations/send-pitch.sh +80 -0
  443. package/claude-assets/skills/cfn-marketing-media-outreach/operations/submit-haro-response.sh +88 -0
  444. package/claude-assets/skills/cfn-marketing-media-outreach/operations/track-pitch-engagement.sh +66 -0
  445. package/claude-assets/skills/cfn-marketing-press-distribution/SKILL.md +159 -0
  446. package/claude-assets/skills/cfn-marketing-press-distribution/operations/distribute-press-release.sh +94 -0
  447. package/claude-assets/skills/cfn-marketing-press-distribution/operations/get-distribution-status.sh +59 -0
  448. package/claude-assets/skills/cfn-marketing-press-distribution/operations/get-pickup-metrics.sh +72 -0
  449. package/claude-assets/skills/cfn-marketing-press-distribution/operations/list-templates.sh +53 -0
  450. package/claude-assets/skills/cfn-marketing-sms-campaigns/SKILL.md +429 -0
  451. package/claude-assets/skills/cfn-marketing-sms-campaigns/operations/create-campaign.sh +183 -0
  452. package/claude-assets/skills/cfn-marketing-sms-campaigns/operations/get-delivery-status.sh +139 -0
  453. package/claude-assets/skills/cfn-marketing-sms-campaigns/operations/opt-out.sh +150 -0
  454. package/claude-assets/skills/cfn-marketing-sms-campaigns/operations/schedule-campaign.sh +187 -0
  455. package/claude-assets/skills/cfn-marketing-sms-campaigns/operations/send-sms.sh +181 -0
  456. package/claude-assets/skills/cfn-marketing-social-publishing/SKILL.md +108 -0
  457. package/claude-assets/skills/cfn-marketing-social-publishing/operations/create-post.sh +104 -0
  458. package/claude-assets/skills/cfn-marketing-social-publishing/operations/delete-post.sh +76 -0
  459. package/claude-assets/skills/cfn-marketing-social-publishing/operations/get-post-stats.sh +66 -0
  460. package/claude-assets/skills/cfn-marketing-social-publishing/operations/schedule-post.sh +85 -0
  461. package/claude-assets/skills/cfn-marketing-social-publishing/operations/upload-media.sh +88 -0
  462. package/claude-assets/skills/cfn-pattern-extraction/SKILL.md +30 -0
  463. package/claude-assets/skills/cfn-pattern-extraction/extract-patterns.sh +80 -0
  464. package/claude-assets/skills/cfn-playbook/SKILL.md +113 -0
  465. package/claude-assets/skills/cfn-playbook/init-playbook.sh +54 -0
  466. package/claude-assets/skills/cfn-playbook/playbook.db +0 -0
  467. package/claude-assets/skills/cfn-playbook/query-playbook.sh +79 -0
  468. package/claude-assets/skills/cfn-playbook/update-playbook.sh +69 -0
  469. package/claude-assets/skills/cfn-playbook-auto-update/SKILL.md +29 -0
  470. package/claude-assets/skills/cfn-playbook-auto-update/auto-update-playbook.sh +86 -0
  471. package/claude-assets/skills/cfn-process-lifecycle/README.md +43 -0
  472. package/claude-assets/skills/cfn-process-lifecycle/SKILL.md +39 -0
  473. package/claude-assets/skills/cfn-process-lifecycle/check-dependencies.sh +58 -0
  474. package/claude-assets/skills/cfn-process-lifecycle/config.json +39 -0
  475. package/claude-assets/skills/cfn-process-lifecycle/process-manager.sh +144 -0
  476. package/claude-assets/skills/cfn-product-owner-decision/SKILL.md +332 -0
  477. package/claude-assets/skills/cfn-product-owner-decision/execute-decision.sh +176 -0
  478. package/claude-assets/skills/cfn-product-owner-decision/parse-decision.sh +66 -0
  479. package/claude-assets/skills/cfn-product-owner-decision/validate-deliverables.sh +82 -0
  480. package/claude-assets/skills/cfn-redis-coordination/AGENT_LOGGING.md +280 -0
  481. package/claude-assets/skills/cfn-redis-coordination/BZPOPMIN_FIX_SUMMARY.md +209 -0
  482. package/claude-assets/skills/cfn-redis-coordination/HEARTBEAT.md +57 -0
  483. package/claude-assets/skills/cfn-redis-coordination/HEARTBEAT_MONITORING.md +267 -0
  484. package/claude-assets/skills/cfn-redis-coordination/LOGGING.md +260 -0
  485. package/claude-assets/skills/cfn-redis-coordination/README.md +65 -0
  486. package/claude-assets/skills/cfn-redis-coordination/SECURITY_REVIEW.md +25 -0
  487. package/claude-assets/skills/cfn-redis-coordination/SHUTDOWN_HANDLING.md +164 -0
  488. package/claude-assets/skills/cfn-redis-coordination/SKILL.md +720 -0
  489. package/claude-assets/skills/cfn-redis-coordination/agent-log.sh +124 -0
  490. package/claude-assets/skills/cfn-redis-coordination/agent-recovery.sh +75 -0
  491. package/claude-assets/skills/cfn-redis-coordination/analyze-task-complexity.sh +277 -0
  492. package/claude-assets/skills/cfn-redis-coordination/cancel-swarm.sh +221 -0
  493. package/claude-assets/skills/cfn-redis-coordination/cfn-loop-exec.sh +468 -0
  494. package/claude-assets/skills/cfn-redis-coordination/cfn-loop-relaunch.sh +29 -0
  495. package/claude-assets/skills/cfn-redis-coordination/check-dependencies.sh +32 -0
  496. package/claude-assets/skills/cfn-redis-coordination/collect-confidence-scores.sh +179 -0
  497. package/claude-assets/skills/cfn-redis-coordination/collect-results.sh +75 -0
  498. package/claude-assets/skills/cfn-redis-coordination/complete-swarm.sh +75 -0
  499. package/claude-assets/skills/cfn-redis-coordination/config.json +61 -0
  500. package/claude-assets/skills/cfn-redis-coordination/data/cfn-loop.db +0 -0
  501. package/claude-assets/skills/cfn-redis-coordination/demos/phase4-wake-queue-test-report.md +82 -0
  502. package/claude-assets/skills/cfn-redis-coordination/demos/test-bzpopmin-fix.sh +274 -0
  503. package/claude-assets/skills/cfn-redis-coordination/demos/test-cancel-swarm.sh +276 -0
  504. package/claude-assets/skills/cfn-redis-coordination/demos/test-dlq.sh +129 -0
  505. package/claude-assets/skills/cfn-redis-coordination/demos/test-iteration-feedback.sh +320 -0
  506. package/claude-assets/skills/cfn-redis-coordination/demos/test-orchestrator.sh +249 -0
  507. package/claude-assets/skills/cfn-redis-coordination/demos/test-priority-wake-phase4-unix.sh +148 -0
  508. package/claude-assets/skills/cfn-redis-coordination/demos/test-priority-wake-phase4.sh +163 -0
  509. package/claude-assets/skills/cfn-redis-coordination/demos/test-priority-wake.sh +138 -0
  510. package/claude-assets/skills/cfn-redis-coordination/demos/test-quick-fix.sh +81 -0
  511. package/claude-assets/skills/cfn-redis-coordination/demos/test-quorum-absolute.sh +45 -0
  512. package/claude-assets/skills/cfn-redis-coordination/demos/test-quorum-fallback.sh +68 -0
  513. package/claude-assets/skills/cfn-redis-coordination/demos/test-quorum-percentage.sh +56 -0
  514. package/claude-assets/skills/cfn-redis-coordination/demos/test-quorum-with-retry.sh +81 -0
  515. package/claude-assets/skills/cfn-redis-coordination/demos/test-quorum.sh +57 -0
  516. package/claude-assets/skills/cfn-redis-coordination/demos/test-shutdown-handling.sh +187 -0
  517. package/claude-assets/skills/cfn-redis-coordination/demos/test-shutdown.sh +160 -0
  518. package/claude-assets/skills/cfn-redis-coordination/demos/test-utils-unix.sh +97 -0
  519. package/claude-assets/skills/cfn-redis-coordination/demos/test-utils.sh +97 -0
  520. package/claude-assets/skills/cfn-redis-coordination/demos/test-waiting-mode.sh +59 -0
  521. package/claude-assets/skills/cfn-redis-coordination/examples/README.md +73 -0
  522. package/claude-assets/skills/cfn-redis-coordination/examples/grafana-dashboard.json +352 -0
  523. package/claude-assets/skills/cfn-redis-coordination/examples/hierarchical-pattern.sh +127 -0
  524. package/claude-assets/skills/cfn-redis-coordination/examples/mesh-pattern.sh +171 -0
  525. package/claude-assets/skills/cfn-redis-coordination/examples/timeout-handling.sh +227 -0
  526. package/claude-assets/skills/cfn-redis-coordination/examples/waiting-mode-pattern.sh +239 -0
  527. package/claude-assets/skills/cfn-redis-coordination/execute-product-owner-decision.sh +258 -0
  528. package/claude-assets/skills/cfn-redis-coordination/get-agent-timeout.sh +177 -0
  529. package/claude-assets/skills/cfn-redis-coordination/heartbeat-functions.sh +137 -0
  530. package/claude-assets/skills/cfn-redis-coordination/heartbeat-protocol.md +106 -0
  531. package/claude-assets/skills/cfn-redis-coordination/heartbeat.sh +126 -0
  532. package/claude-assets/skills/cfn-redis-coordination/init-swarm.sh +148 -0
  533. package/claude-assets/skills/cfn-redis-coordination/invoke-redis-pattern.sh +220 -0
  534. package/claude-assets/skills/cfn-redis-coordination/invoke-waiting-mode.sh +283 -0
  535. package/claude-assets/skills/cfn-redis-coordination/invoke-waiting-mode.sh.backup-p7 +423 -0
  536. package/claude-assets/skills/cfn-redis-coordination/list-active-swarms.sh +147 -0
  537. package/claude-assets/skills/cfn-redis-coordination/log-event.sh +109 -0
  538. package/claude-assets/skills/cfn-redis-coordination/metrics-export.sh +674 -0
  539. package/claude-assets/skills/cfn-redis-coordination/metrics-schema.json +66 -0
  540. package/claude-assets/skills/cfn-redis-coordination/metrics-storage.md +31 -0
  541. package/claude-assets/skills/cfn-redis-coordination/monitor-cfn-violations.sh +391 -0
  542. package/claude-assets/skills/cfn-redis-coordination/monitor-heartbeats.sh +101 -0
  543. package/claude-assets/skills/cfn-redis-coordination/orchestrate-cfn-loop-v3.sh +141 -0
  544. package/claude-assets/skills/cfn-redis-coordination/orchestrate-cfn-loop.sh +31 -0
  545. package/claude-assets/skills/cfn-redis-coordination/orchestrate-cfn-loop.sh.backup +38 -0
  546. package/claude-assets/skills/cfn-redis-coordination/orchestrate-cfn-loop.sh.backup-1761167675 +1672 -0
  547. package/claude-assets/skills/cfn-redis-coordination/orchestrate-cfn-loop.sh.backup-p5 +1604 -0
  548. package/claude-assets/skills/cfn-redis-coordination/orchestrate-cfn-loop.sh.backup-phase1 +1550 -0
  549. package/claude-assets/skills/cfn-redis-coordination/orchestrate-cfn-loop.sh.backup-phase2 +1621 -0
  550. package/claude-assets/skills/cfn-redis-coordination/orchestrate-cfn-loop.sh.backup-phase3 +1621 -0
  551. package/claude-assets/skills/cfn-redis-coordination/orchestrate-cfn-loop.sh.bak +0 -0
  552. package/claude-assets/skills/cfn-redis-coordination/orchestrate-cfn-loop.sh.broken +1627 -0
  553. package/claude-assets/skills/cfn-redis-coordination/orchestrate-cfn-loop.sh.corrupted +80 -0
  554. package/claude-assets/skills/cfn-redis-coordination/orchestrate-cfn-loop.sh.deprecated +1864 -0
  555. package/claude-assets/skills/cfn-redis-coordination/priority-wake-mechanism.md +75 -0
  556. package/claude-assets/skills/cfn-redis-coordination/priority_wake.py +134 -0
  557. package/claude-assets/skills/cfn-redis-coordination/query-dlq.sh +162 -0
  558. package/claude-assets/skills/cfn-redis-coordination/query-logs.sh +103 -0
  559. package/claude-assets/skills/cfn-redis-coordination/redis-pattern.sh +619 -0
  560. package/claude-assets/skills/cfn-redis-coordination/retrieve-context.sh +58 -0
  561. package/claude-assets/skills/cfn-redis-coordination/select-specialist-agent.sh +371 -0
  562. package/claude-assets/skills/cfn-redis-coordination/semantic-match-tfidf.py +252 -0
  563. package/claude-assets/skills/cfn-redis-coordination/send-heartbeat.sh +165 -0
  564. package/claude-assets/skills/cfn-redis-coordination/signal.sh +38 -0
  565. package/claude-assets/skills/cfn-redis-coordination/store-context.sh +86 -0
  566. package/claude-assets/skills/cfn-redis-coordination/store-epic-context.sh +123 -0
  567. package/claude-assets/skills/cfn-redis-coordination/test-context-injection.sh +354 -0
  568. package/claude-assets/skills/cfn-redis-coordination/test-timeout-enforcement.sh +513 -0
  569. package/claude-assets/skills/cfn-redis-coordination/tests/convert-line-endings.sh +15 -0
  570. package/claude-assets/skills/cfn-redis-coordination/tests/dlq-functionality-test.sh +102 -0
  571. package/claude-assets/skills/cfn-redis-coordination/tests/edge-cases-test.sh +99 -0
  572. package/claude-assets/skills/cfn-redis-coordination/tests/integration-test.sh +170 -0
  573. package/claude-assets/skills/cfn-redis-coordination/tests/retry-mechanism-test.sh +82 -0
  574. package/claude-assets/skills/cfn-redis-coordination/tests/run-test-suite.sh +92 -0
  575. package/claude-assets/skills/cfn-redis-coordination/tests/run-tests.sh +4 -0
  576. package/claude-assets/skills/cfn-redis-coordination/tests/test-heartbeat-monitoring.sh +418 -0
  577. package/claude-assets/skills/cfn-redis-coordination/tests/test-heartbeat-simple.sh +124 -0
  578. package/claude-assets/skills/cfn-redis-coordination/tests/test-primitives.sh +166 -0
  579. package/claude-assets/skills/cfn-redis-coordination/tests/test-utils.sh +54 -0
  580. package/claude-assets/skills/cfn-redis-coordination/tests/test_coordination_primitives.sh.deprecated +20 -0
  581. package/claude-assets/skills/cfn-redis-coordination/tests/test_utils.sh +49 -0
  582. package/claude-assets/skills/cfn-redis-coordination/v2_modularization/core_orchestration.sh +76 -0
  583. package/claude-assets/skills/cfn-redis-coordination/validate-parameters.sh +492 -0
  584. package/claude-assets/skills/cfn-retrospective-report/SKILL.md +31 -0
  585. package/claude-assets/skills/cfn-retrospective-report/generate-report.sh +101 -0
  586. package/claude-assets/skills/cfn-scope-simplifier/SKILL.md +37 -0
  587. package/claude-assets/skills/cfn-scope-simplifier/simplify-scope.sh +68 -0
  588. package/claude-assets/skills/cfn-simplified-agent-lifecycle/COST_ANALYSIS.md +49 -0
  589. package/claude-assets/skills/cfn-simplified-agent-lifecycle/DESIGN.md +98 -0
  590. package/claude-assets/skills/cfn-simplified-agent-lifecycle/MIGRATION_PLAN.md +74 -0
  591. package/claude-assets/skills/cfn-skill-builder/SKILL.md +910 -0
  592. package/claude-assets/skills/cfn-specialist-injection/SKILL.md +41 -0
  593. package/claude-assets/skills/cfn-specialist-injection/recommend-specialist.sh +57 -0
  594. package/claude-assets/skills/cfn-sprint-execution/SKILL.md +27 -0
  595. package/claude-assets/skills/cfn-sprint-execution/execute-sprint-task.sh +59 -0
  596. package/claude-assets/skills/cfn-sprint-execution/execute-sprint.sh +65 -0
  597. package/claude-assets/skills/cfn-sprint-planner/SKILL.md +37 -0
  598. package/claude-assets/skills/cfn-sprint-planner/plan-sprint.sh +85 -0
  599. package/claude-assets/skills/cfn-sqlite-memory/IMPLEMENTATION_REPORT.md +393 -0
  600. package/claude-assets/skills/cfn-sqlite-memory/QUICK_REFERENCE.md +204 -0
  601. package/claude-assets/skills/cfn-sqlite-memory/README.md +65 -0
  602. package/claude-assets/skills/cfn-sqlite-memory/SKILL.md +415 -0
  603. package/claude-assets/skills/cfn-sqlite-memory/acl-queries.sql +452 -0
  604. package/claude-assets/skills/cfn-sqlite-memory/check-dependencies.sh +36 -0
  605. package/claude-assets/skills/cfn-sqlite-memory/config.json +45 -0
  606. package/claude-assets/skills/cfn-sqlite-memory/memory-cli.sh +88 -0
  607. package/claude-assets/skills/cfn-sqlite-memory/test-state-persistence.js +187 -0
  608. package/claude-assets/skills/cfn-sqlite-memory/ttl-cleanup.sh +274 -0
  609. package/claude-assets/skills/cfn-standardized-error-handling/SKILL.md +56 -0
  610. package/claude-assets/skills/cfn-standardized-error-handling/capture-agent-error.sh +87 -0
  611. package/claude-assets/skills/cfn-standardized-error-handling/test-error-handling.sh +166 -0
  612. package/claude-assets/skills/cfn-task-classifier/SKILL.md +94 -0
  613. package/claude-assets/skills/cfn-task-classifier/USAGE.md +248 -0
  614. package/claude-assets/skills/cfn-task-classifier/classify-task.sh +291 -0
  615. package/claude-assets/skills/cfn-test-execution/README.md +129 -0
  616. package/claude-assets/skills/cfn-test-execution/SKILL.md +128 -0
  617. package/claude-assets/skills/cfn-test-execution/check-dependencies.sh +36 -0
  618. package/claude-assets/skills/cfn-test-execution/test-cache-reader.sh +134 -0
  619. package/claude-assets/skills/cfn-test-execution/test-concurrent-conflicts.sh +115 -0
  620. package/claude-assets/skills/cfn-test-execution/test-coordinator-pattern.sh +109 -0
  621. package/claude-assets/skills/cfn-transparency-middleware/Cargo.toml +18 -0
  622. package/claude-assets/skills/cfn-transparency-middleware/README.md +74 -0
  623. package/claude-assets/skills/cfn-transparency-middleware/SECURITY.md +41 -0
  624. package/claude-assets/skills/cfn-transparency-middleware/SKILL.md +91 -0
  625. package/claude-assets/skills/cfn-transparency-middleware/TEST_RESULTS.md +174 -0
  626. package/claude-assets/skills/cfn-transparency-middleware/config.json +31 -0
  627. package/claude-assets/skills/cfn-transparency-middleware/examples/basic-usage.ts +39 -0
  628. package/claude-assets/skills/cfn-transparency-middleware/examples/batch-processing.ts +52 -0
  629. package/claude-assets/skills/cfn-transparency-middleware/examples/custom-filtering.ts +61 -0
  630. package/claude-assets/skills/cfn-transparency-middleware/invoke-transparency-filter.sh +98 -0
  631. package/claude-assets/skills/cfn-transparency-middleware/invoke-transparency-init.sh +224 -0
  632. package/claude-assets/skills/cfn-transparency-middleware/invoke-transparency-level.sh +333 -0
  633. package/claude-assets/skills/cfn-transparency-middleware/invoke-transparency-metrics.sh +345 -0
  634. package/claude-assets/skills/cfn-transparency-middleware/invoke-transparency-observe.sh +140 -0
  635. package/claude-assets/skills/cfn-transparency-middleware/invoke-transparency-stop.sh +235 -0
  636. package/claude-assets/skills/cfn-transparency-middleware/memory_query.rs +85 -0
  637. package/claude-assets/skills/cfn-transparency-middleware/memory_repository.rs +140 -0
  638. package/claude-assets/skills/cfn-transparency-middleware/memory_schema.rs +64 -0
  639. package/claude-assets/skills/cfn-transparency-middleware/middleware-config.sh +29 -0
  640. package/claude-assets/skills/cfn-transparency-middleware/performance-benchmark.sh +79 -0
  641. package/claude-assets/skills/cfn-transparency-middleware/test-e2e.sh +406 -0
  642. package/claude-assets/skills/cfn-transparency-middleware/test-integration.sh +162 -0
  643. package/claude-assets/skills/cfn-transparency-middleware/test-transparency-skill.sh +368 -0
  644. package/claude-assets/skills/cfn-transparency-middleware/test-transparency-skill.sh.unix +126 -0
  645. package/claude-assets/skills/cfn-transparency-middleware/tests/input-validation.sh +93 -0
  646. package/claude-assets/skills/cfn-transparency-middleware/wrap-agent.sh +132 -0
  647. package/claude-assets/skills/cfn-validation-templates/SKILL.md +47 -0
  648. package/claude-assets/skills/cfn-validation-templates/content.json +38 -0
  649. package/claude-assets/skills/cfn-validation-templates/data.json +38 -0
  650. package/claude-assets/skills/cfn-validation-templates/design.json +38 -0
  651. package/claude-assets/skills/cfn-validation-templates/infrastructure.json +38 -0
  652. package/claude-assets/skills/cfn-validation-templates/research.json +38 -0
  653. package/claude-assets/skills/cfn-validation-templates/software.json +38 -0
  654. package/claude-assets/skills/cfn-web-portal/DESIGN.md +117 -0
  655. package/claude-assets/skills/cfn-web-portal/SKILL.md +679 -0
  656. package/claude-assets/skills/cfn-web-portal/invoke-portal-agents.sh +129 -0
  657. package/claude-assets/skills/cfn-web-portal/invoke-portal-dashboard.sh +85 -0
  658. package/claude-assets/skills/cfn-web-portal/invoke-portal-events.sh +125 -0
  659. package/claude-assets/skills/cfn-web-portal/invoke-portal-metrics.sh +112 -0
  660. package/claude-assets/skills/cfn-web-portal/invoke-portal-start.sh +135 -0
  661. package/claude-assets/skills/cfn-web-portal/invoke-portal-stop.sh +121 -0
  662. package/claude-assets/skills/cfn-web-portal/test-web-portal-skill.sh +51 -0
  663. package/claude-assets/skills/cfn-web-portal/validate-deployment.sh +85 -0
  664. package/claude-assets/skills/cfn-webapp-testing/README.md +142 -0
  665. package/claude-assets/skills/cfn-webapp-testing/SCREENSHOT_NAMING_CONVENTION.md +547 -0
  666. package/claude-assets/skills/cfn-webapp-testing/SKILL.md +877 -0
  667. package/claude-assets/skills/cfn-webapp-testing/capture-screenshot.sh +238 -0
  668. package/claude-assets/skills/cfn-webapp-testing/cfn-loop-integration.sh +265 -0
  669. package/claude-assets/skills/cfn-webapp-testing/compare-screenshots.sh +199 -0
  670. package/claude-assets/skills/cfn-webapp-testing/init-storage.sh +150 -0
  671. package/claude-assets/skills/cfn-webapp-testing/set-baseline.sh +196 -0
  672. package/claude-assets/skills/cfn-webapp-testing/test-webapp-testing.sh +233 -0
  673. package/claude-assets/skills/consensus-calculator.js +45 -0
  674. package/claude-assets/skills/evidence-chain.sql +66 -0
  675. package/claude-assets/skills/run-all-skill-tests.sh +124 -0
  676. package/claude-assets/skills/test-execution-coordinator-pattern.md +228 -0
  677. package/dist/agents/agent-loader.js.map +1 -1
  678. package/package.json +3 -3
  679. package/scripts/init-project.js +7 -7
@@ -0,0 +1,1864 @@
1
+ #!/usr/bin/env bash
2
+
3
+ ##############################################################################
4
+ # CFN Loop Orchestration v2.1.0 - Stateless Architecture
5
+ # Manages multi-loop CFN execution with dependency tracking and consensus
6
+ #
7
+ # Usage:
8
+ # ./orchestrate-cfn-loop.sh --task-id <id> \
9
+ # --mode <mvp|standard|enterprise> \
10
+ # --loop3-agents <agent1,agent2,...> \
11
+ # --loop2-agents <agent1,agent2,...> \
12
+ # --product-owner <agent-id> \
13
+ # [--max-iterations <n>] \
14
+ # [--min-quorum-loop3 <n|n%|0.n>] \
15
+ # [--min-quorum-loop2 <n|n%|0.n>] \
16
+ # [--epic-context <json>] \
17
+ # [--phase-context <json>] \
18
+ # [--success-criteria <json>]
19
+ #
20
+ # CFN Loop Structure:
21
+ # Loop 3 (Primary Swarm - Self Validation)
22
+ # ↓
23
+ # IF Loop 3 self-validation gate FAILS → RELAUNCH Loop 3 (skip Loop 2)
24
+ # IF Loop 3 self-validation gate PASSES → Proceed to Loop 2
25
+ # ↓
26
+ # Loop 2 (Consensus Validators)
27
+ # ↓
28
+ # Product Owner Decision
29
+ #
30
+ # Stateless Architecture (v2.1.0):
31
+ # - Agents spawn via CLI, execute work, report confidence, and EXIT
32
+ # - NO waiting mode (agents do not block for iterations)
33
+ # - Orchestrator stores iteration feedback in Redis
34
+ # - Next iteration spawns fresh agents with feedback injected
35
+ # - Uses collect-confidence-scores.sh for stateless consensus
36
+ #
37
+ # Dependency Enforcement:
38
+ # - Loop 3 agents self-validate via confidence scores
39
+ # - Gate check determines if Loop 2 validators should be engaged
40
+ # - Loop 2 agents receive Loop 3 deliverables in context
41
+ # - Product Owner receives Loop 2 feedback for decision
42
+ # - Agents communicate via Redis but do not wait
43
+ #
44
+ # Quorum Configuration:
45
+ # - Absolute: --min-quorum-loop3 3 (requires exactly 3 agents)
46
+ # - Percentage: --min-quorum-loop3 85% (requires 85% of agents)
47
+ # - Decimal: --min-quorum-loop3 0.66 (requires 66% of agents)
48
+ # - Default: 0.66 (2/3 majority) if not specified
49
+ #
50
+ # Agent Protocol (Stateless):
51
+ # Loop 3 (Implementers):
52
+ # 1. Receive context with deliverables, acceptance criteria, feedback
53
+ # 2. Complete work (create files, modify code)
54
+ # 3. Self-report confidence based on deliverable completion
55
+ # 4. EXIT (orchestrator handles iterations)
56
+ #
57
+ # Loop 2 (Validators):
58
+ # 1. Receive context with Loop 3 deliverables to review
59
+ # 2. Perform validation against acceptance criteria
60
+ # 3. Report consensus score and structured feedback
61
+ # 4. EXIT (orchestrator makes iteration decision)
62
+ ##############################################################################
63
+ set -euo pipefail
64
+
65
+ # Configuration
66
+ TASK_ID=""
67
+ MODE="standard"
68
+ LOOP3_AGENTS=""
69
+ LOOP2_AGENTS=""
70
+ PRODUCT_OWNER=""
71
+ MAX_ITERATIONS=10
72
+ TIMEOUT=3600 # 60 minute default timeout for agent completion
73
+ RETRY_COUNT=3
74
+ RETRY_DELAY=5000 # Base delay in milliseconds
75
+ MIN_QUORUM_LOOP3="" # Minimum agents required for Loop 3 (absolute or percentage)
76
+ MIN_QUORUM_LOOP2="" # Minimum agents required for Loop 2 (absolute or percentage)
77
+ ORCHESTRATOR_PID=$$
78
+ SHUTDOWN_MONITOR_PID=""
79
+ SHUTDOWN_REQUESTED=0
80
+ LOOP3_HEARTBEAT_MONITOR_PID=""
81
+ LOOP2_HEARTBEAT_MONITOR_PID=""
82
+
83
+ # Epic Context (optional - for agent system prompts)
84
+ EPIC_CONTEXT=""
85
+ PHASE_CONTEXT=""
86
+ SUCCESS_CRITERIA=""
87
+ EXPECTED_FILES="" # BUG #12 FIX: Explicit file verification
88
+ PHASE_ID="" # BUG #16 FIX: Phase identifier for timeout configuration
89
+
90
+ # Thresholds by mode
91
+ declare -A GATE_THRESHOLD=(
92
+ [mvp]=0.70
93
+ [standard]=0.75
94
+ [enterprise]=0.75
95
+ )
96
+
97
+ declare -A CONSENSUS_THRESHOLD=(
98
+ [mvp]=0.80
99
+ [standard]=0.90
100
+ [enterprise]=0.95
101
+ )
102
+
103
+ # Parse arguments
104
+ while [[ $# -gt 0 ]]; do
105
+ case $1 in
106
+ --task-id)
107
+ TASK_ID="$2"
108
+ shift 2
109
+ ;;
110
+ --mode)
111
+ MODE="$2"
112
+ shift 2
113
+ ;;
114
+ --loop3-agents)
115
+ LOOP3_AGENTS="$2"
116
+ shift 2
117
+ ;;
118
+ --loop2-agents)
119
+ LOOP2_AGENTS="$2"
120
+ shift 2
121
+ ;;
122
+ --product-owner)
123
+ PRODUCT_OWNER="$2"
124
+ shift 2
125
+ ;;
126
+ --max-iterations)
127
+ MAX_ITERATIONS="$2"
128
+ shift 2
129
+ ;;
130
+ --retry-count)
131
+ RETRY_COUNT="$2"
132
+ shift 2
133
+ ;;
134
+ --retry-delay)
135
+ RETRY_DELAY="$2"
136
+ shift 2
137
+ ;;
138
+ --timeout)
139
+ TIMEOUT="$2"
140
+ shift 2
141
+ ;;
142
+ --min-quorum-loop3)
143
+ MIN_QUORUM_LOOP3="$2"
144
+ shift 2
145
+ ;;
146
+ --min-quorum-loop2)
147
+ MIN_QUORUM_LOOP2="$2"
148
+ shift 2
149
+ ;;
150
+ --epic-context)
151
+ EPIC_CONTEXT="$2"
152
+ shift 2
153
+ ;;
154
+ --phase-context)
155
+ PHASE_CONTEXT="$2"
156
+ shift 2
157
+ ;;
158
+ --success-criteria)
159
+ SUCCESS_CRITERIA="$2"
160
+ shift 2
161
+ ;;
162
+ --expected-files)
163
+ EXPECTED_FILES="$2"
164
+ shift 2
165
+ ;;
166
+ --phase-id)
167
+ PHASE_ID="$2"
168
+ shift 2
169
+ ;;
170
+ *)
171
+ echo "Unknown option: $1"
172
+ exit 1
173
+ ;;
174
+ esac
175
+ done
176
+
177
+ # Validation
178
+ if [ -z "$TASK_ID" ] || [ -z "$LOOP3_AGENTS" ] || [ -z "$LOOP2_AGENTS" ] || [ -z "$PRODUCT_OWNER" ]; then
179
+ echo "Error: Required parameters missing"
180
+ echo "Usage: $0 --task-id <id> --mode <mode> --loop3-agents <agents> --loop2-agents <agents> --product-owner <agent>"
181
+ exit 1
182
+ fi
183
+
184
+ GATE=${GATE_THRESHOLD[$MODE]}
185
+ CONSENSUS=${CONSENSUS_THRESHOLD[$MODE]}
186
+
187
+ # Set default quorum values if not specified (66% = 2/3 majority)
188
+ MIN_QUORUM_LOOP3=${MIN_QUORUM_LOOP3:-0.66}
189
+ MIN_QUORUM_LOOP2=${MIN_QUORUM_LOOP2:-0.66}
190
+
191
+ ##############################################################################
192
+ # Shutdown Handling Functions
193
+ ##############################################################################
194
+ function cleanup_and_exit() {
195
+ local exit_code="${1:-130}"
196
+ local reason="${2:-user_interrupt}"
197
+
198
+ # Set shutdown flag to stop any ongoing operations
199
+ SHUTDOWN_REQUESTED=1
200
+
201
+ echo ""
202
+ echo "=============================================="
203
+ echo "🛑 Orchestrator shutting down gracefully..."
204
+ echo "=============================================="
205
+ echo "Reason: $reason"
206
+ echo "Exit Code: $exit_code"
207
+
208
+ # Kill shutdown monitor if running
209
+ if [ -n "$SHUTDOWN_MONITOR_PID" ] && kill -0 "$SHUTDOWN_MONITOR_PID" 2>/dev/null; then
210
+ kill "$SHUTDOWN_MONITOR_PID" 2>/dev/null || true
211
+ wait "$SHUTDOWN_MONITOR_PID" 2>/dev/null || true
212
+ fi
213
+
214
+ # Stop heartbeat monitors if running
215
+ if [ -n "${LOOP3_HEARTBEAT_MONITOR_PID:-}" ]; then
216
+ echo "Stopping Loop 3 heartbeat monitor..."
217
+ stop_heartbeat_monitor "$TASK_ID" "loop3" "$LOOP3_HEARTBEAT_MONITOR_PID"
218
+ fi
219
+ if [ -n "${LOOP2_HEARTBEAT_MONITOR_PID:-}" ]; then
220
+ echo "Stopping Loop 2 heartbeat monitor..."
221
+ stop_heartbeat_monitor "$TASK_ID" "loop2" "$LOOP2_HEARTBEAT_MONITOR_PID"
222
+ fi
223
+
224
+ # Mark swarm as cancelled if initialized
225
+ if [ -n "$TASK_ID" ] && [ -n "${SWARM_ID:-}" ]; then
226
+ echo "Marking swarm as cancelled..."
227
+ ./.claude/skills/redis-coordination/complete-swarm.sh \
228
+ --swarm-id "$SWARM_ID" \
229
+ --final-metric "status=cancelled" \
230
+ --final-metric "shutdown_reason=$reason" 2>/dev/null || echo " ⚠️ Failed to mark swarm as cancelled"
231
+ fi
232
+
233
+ # Clean up Redis keys
234
+ if [ -n "$TASK_ID" ]; then
235
+ echo "Cleaning up Redis keys..."
236
+ local keys_deleted=$(redis-cli --scan --pattern "swarm:${TASK_ID}:*" | xargs -r redis-cli DEL 2>/dev/null || echo "0")
237
+ echo " Deleted $keys_deleted Redis keys"
238
+ fi
239
+
240
+ # Clean up heartbeat monitor marker files
241
+ rm -f /tmp/heartbeat-monitor-${TASK_ID}-*.active 2>/dev/null || true
242
+
243
+ echo "=============================================="
244
+ echo "Shutdown complete"
245
+ echo "=============================================="
246
+
247
+ exit "$exit_code"
248
+ }
249
+
250
+ # Trap SIGTERM and SIGINT for graceful shutdown
251
+ trap 'echo "[TRAP] Caught SIGINT" >&2; cleanup_and_exit 130 "SIGINT_received"' SIGINT
252
+ trap 'echo "[TRAP] Caught SIGTERM" >&2; cleanup_and_exit 143 "SIGTERM_received"' SIGTERM
253
+
254
+ ##############################################################################
255
+ # Start Shutdown Monitor (Background Process)
256
+ ##############################################################################
257
+ function start_shutdown_monitor() {
258
+ local task_id="$1"
259
+
260
+ (
261
+ # Block on shutdown channel (zero-token waiting)
262
+ SHUTDOWN_KEY="swarm:${task_id}:shutdown"
263
+ SHUTDOWN_RESULT=$(redis-cli BLPOP "$SHUTDOWN_KEY" 0 2>/dev/null || echo "")
264
+
265
+ if [ -n "$SHUTDOWN_RESULT" ]; then
266
+ # Extract shutdown payload (format: key value)
267
+ SHUTDOWN_PAYLOAD=$(echo "$SHUTDOWN_RESULT" | tail -1)
268
+ REASON=$(echo "$SHUTDOWN_PAYLOAD" | jq -r '.reason // "external_shutdown"' 2>/dev/null || echo "external_shutdown")
269
+
270
+ echo ""
271
+ echo "🛑 Shutdown signal received from Redis channel: $REASON"
272
+ echo " Sending SIGTERM to orchestrator PID: $ORCHESTRATOR_PID"
273
+
274
+ # Send SIGTERM to main orchestrator process
275
+ if kill -TERM "$ORCHESTRATOR_PID" 2>/dev/null; then
276
+ echo " ✅ SIGTERM sent successfully"
277
+ else
278
+ echo " ❌ Failed to send SIGTERM (process may have already exited)"
279
+ exit 0
280
+ fi
281
+ fi
282
+ ) &
283
+
284
+ SHUTDOWN_MONITOR_PID=$!
285
+ echo "Shutdown monitor started (PID: $SHUTDOWN_MONITOR_PID)"
286
+ }
287
+
288
+ ##############################################################################
289
+ # Feedback Accumulation Function (PHASE 1 - BUG #23 FIX)
290
+ ##############################################################################
291
+ # Accumulates feedback across iterations to enable learning
292
+ # Usage: accumulate_feedback <task_id> <iteration> <source> <feedback_message>
293
+ function accumulate_feedback() {
294
+ local task_id="$1"
295
+ local iteration="$2"
296
+ local source="$3"
297
+ local feedback_message="$4"
298
+
299
+ local feedback_key="swarm:${task_id}:feedback:history"
300
+
301
+ # Retrieve existing feedback history
302
+ local feedback_history
303
+ feedback_history=$(redis-cli GET "$feedback_key" 2>/dev/null)
304
+ # Normalize empty/nil to valid JSON array
305
+ if [ -z "$feedback_history" ] || [ "$feedback_history" = "(nil)" ]; then
306
+ feedback_history="[]"
307
+ fi
308
+
309
+ # Append new feedback with metadata
310
+ local new_feedback
311
+ new_feedback=$(jq -nc \
312
+ --argjson history "$feedback_history" \
313
+ --arg iteration "$iteration" \
314
+ --arg source "$source" \
315
+ --arg feedback "$feedback_message" \
316
+ --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
317
+ '$history + [{
318
+ iteration: ($iteration | tonumber),
319
+ source: $source,
320
+ feedback: $feedback,
321
+ timestamp: $timestamp
322
+ }]')
323
+
324
+ # Store accumulated history
325
+ echo "$new_feedback" | redis-cli -x SET "$feedback_key" EX 86400 >/dev/null
326
+
327
+ echo "[Feedback] ✅ Accumulated feedback for iteration $iteration (source: $source)"
328
+ }
329
+
330
+ ##############################################################################
331
+ # Quorum Calculation Function
332
+ ##############################################################################
333
+ function calculate_quorum() {
334
+ local quorum_spec="$1"
335
+ local total_agents="$2"
336
+
337
+ # If no quorum specified, require all agents
338
+ if [ -z "$quorum_spec" ]; then
339
+ echo "$total_agents"
340
+ return 0
341
+ fi
342
+
343
+ # Check if percentage format (e.g., "85%")
344
+ if [[ "$quorum_spec" =~ %$ ]]; then
345
+ # Extract percentage value (remove % suffix)
346
+ local pct="${quorum_spec%\%}"
347
+ # Calculate: ceil(total_agents * pct / 100)
348
+ echo "scale=0; ($total_agents * $pct + 50) / 100" | bc
349
+ # Check if decimal (0.0-1.0), treat as fraction
350
+ elif [[ "$quorum_spec" =~ ^0?\.[0-9]+$ ]]; then
351
+ # Calculate: ceil(total_agents * fraction)
352
+ echo "scale=0; ($quorum_spec * $total_agents + 0.5) / 1" | bc
353
+ else
354
+ # Absolute number - validate it doesn't exceed total
355
+ if [ "$quorum_spec" -gt "$total_agents" ]; then
356
+ echo "Error: Quorum ($quorum_spec) exceeds total agents ($total_agents)" >&2
357
+ return 1
358
+ fi
359
+ echo "$quorum_spec"
360
+ fi
361
+ }
362
+
363
+ ##############################################################################
364
+ # Dead Letter Queue (DLQ) Functions
365
+ ##############################################################################
366
+ function write_to_dlq() {
367
+ local agent="$1"
368
+ local reason="$2"
369
+ local retry_count="$3"
370
+
371
+ DLQ_KEY="swarm:${TASK_ID}:dlq:${agent}"
372
+ DLQ_ENTRY=$(jq -n \
373
+ --arg reason "$reason" \
374
+ --arg retries "$retry_count" \
375
+ --arg ts "$(date +%s)" \
376
+ '{reason: $reason, retry_count: ($retries | tonumber), timestamp: ($ts | tonumber)}')
377
+
378
+ echo "$DLQ_ENTRY" | redis-cli -x LPUSH "$DLQ_KEY" >/dev/null
379
+ redis-cli EXPIRE "$DLQ_KEY" 604800 >/dev/null # 7 days TTL
380
+
381
+ echo " ❌ $agent → DLQ (reason: $reason, retries: $retry_count)"
382
+ }
383
+
384
+ ##############################################################################
385
+ # Exponential Backoff Retry Function
386
+ ##############################################################################
387
+ function retry_with_backoff() {
388
+ local agent="$1"
389
+ local attempt="$2"
390
+ local max_retries="$3"
391
+ local base_delay="$4"
392
+
393
+ # Check for shutdown before sleeping
394
+ if [ "$SHUTDOWN_REQUESTED" -eq 1 ]; then
395
+ echo " [SHUTDOWN] Skipping backoff delay for $agent" >&2
396
+ return 0
397
+ fi
398
+
399
+ # Exponential backoff: delay = base_delay * (2 ^ attempt)
400
+ local delay=$(echo "$base_delay * (2 ^ $attempt)" | bc)
401
+ local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
402
+
403
+ echo " [$timestamp] [Retry $attempt/$max_retries] Waiting ${delay}ms before retry for $agent..."
404
+
405
+ # Use interruptible sleep - sleep in small increments and check for shutdown
406
+ local delay_sec=$(echo "scale=3; $delay / 1000" | bc)
407
+ local elapsed=0
408
+ while (( $(echo "$elapsed < $delay_sec" | bc -l) )); do
409
+ # Sleep for 0.5s increments (or remaining time if less)
410
+ local remaining=$(echo "$delay_sec - $elapsed" | bc)
411
+ local sleep_time=$(echo "if ($remaining < 0.5) $remaining else 0.5" | bc)
412
+
413
+ sleep "$sleep_time" &
414
+ wait $! 2>/dev/null || return 0 # If wait is interrupted (SIGTERM), return immediately
415
+
416
+ elapsed=$(echo "$elapsed + $sleep_time" | bc)
417
+
418
+ # Check for shutdown after each sleep increment
419
+ if [ "$SHUTDOWN_REQUESTED" -eq 1 ]; then
420
+ echo " [SHUTDOWN] Interrupted backoff delay for $agent" >&2
421
+ return 0
422
+ fi
423
+ done
424
+ }
425
+
426
+ ##############################################################################
427
+ # Heartbeat Monitoring Functions
428
+ ##############################################################################
429
+ declare -A MISSED_HEARTBEATS # Track missed heartbeats per agent
430
+
431
+ function check_agent_heartbeat() {
432
+ local agent="$1"
433
+ local task_id="$2"
434
+ local iteration="$3"
435
+
436
+ # Agents create heartbeat as: swarm:${task_id}:agent:${agent_id} (HASH with heartbeat field)
437
+ # Agent ID includes iteration suffix: react-frontend-engineer-1
438
+ HB_KEY="swarm:${task_id}:agent:${agent}-${iteration}"
439
+ HB_DATA=$(redis-cli HGET "$HB_KEY" heartbeat 2>/dev/null || echo "")
440
+
441
+ if [ -z "$HB_DATA" ] || [ "$HB_DATA" = "(nil)" ]; then
442
+ return 1 # Dead
443
+ else
444
+ return 0 # Alive
445
+ fi
446
+ }
447
+
448
+ function check_heartbeats_loop() {
449
+ local task_id="$1"
450
+ local loop_name="$2"
451
+ local iteration="$3"
452
+ shift 3
453
+ local agents=("$@")
454
+
455
+ for AGENT in "${agents[@]}"; do
456
+ # Skip agents already marked as failed
457
+ if [[ " ${LOOP3_FAILED_AGENTS[@]} ${LOOP2_FAILED_AGENTS[@]} " =~ " ${AGENT} " ]]; then
458
+ continue
459
+ fi
460
+
461
+ if ! check_agent_heartbeat "$AGENT" "$task_id" "$iteration"; then
462
+ MISSED_HEARTBEATS["$AGENT"]=$((${MISSED_HEARTBEATS["$AGENT"]:-0} + 1))
463
+
464
+ if [ ${MISSED_HEARTBEATS["$AGENT"]} -ge 2 ]; then
465
+ local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
466
+ echo " [$timestamp] [$loop_name] ⚠️ $AGENT appears hung (no heartbeat for 60s)" >&2
467
+
468
+ # Determine which loop this agent belongs to and check quorum
469
+ if [[ " ${LOOP3_AGENTS} " =~ " ${AGENT} " ]]; then
470
+ REMAINING=$((${#LOOP3_COMPLETED_AGENTS[@]}))
471
+ REQUIRED=$(calculate_quorum "$MIN_QUORUM_LOOP3" "$LOOP3_TOTAL")
472
+ elif [[ " ${LOOP2_AGENTS} " =~ " ${AGENT} " ]]; then
473
+ # Safety check: Skip if Loop 2 hasn't been initialized yet
474
+ if [ -z "${LOOP2_COMPLETED_AGENTS+x}" ]; then
475
+ continue
476
+ fi
477
+ REMAINING=$((${#LOOP2_COMPLETED_AGENTS[@]}))
478
+ REQUIRED=$(calculate_quorum "$MIN_QUORUM_LOOP2" "$LOOP2_TOTAL")
479
+ else
480
+ continue
481
+ fi
482
+
483
+ if [ $REMAINING -ge $REQUIRED ]; then
484
+ echo " [$timestamp] [$loop_name] ℹ️ Continuing with quorum (${REMAINING}/${REQUIRED} agents)" >&2
485
+ else
486
+ echo " [$timestamp] [$loop_name] ⚠️ Cannot meet quorum without $AGENT (${REMAINING}/${REQUIRED})" >&2
487
+ fi
488
+ fi
489
+ else
490
+ MISSED_HEARTBEATS["$AGENT"]=0 # Reset counter
491
+ fi
492
+ done
493
+ }
494
+
495
+ function start_heartbeat_monitor() {
496
+ local task_id="$1"
497
+ local loop_name="$2"
498
+ local iteration="$3"
499
+ shift 3
500
+ local agents=("$@")
501
+
502
+ # Create marker file for this monitor
503
+ local monitor_marker="/tmp/heartbeat-monitor-${task_id}-${loop_name}.active"
504
+ touch "$monitor_marker"
505
+
506
+ # [BUG #7 FIX] Spawn background process and let caller capture $!
507
+ (
508
+ while [ -f "$monitor_marker" ]; do
509
+ # Check for shutdown
510
+ if [ "$SHUTDOWN_REQUESTED" -eq 1 ]; then
511
+ break
512
+ fi
513
+
514
+ check_heartbeats_loop "$task_id" "$loop_name" "$iteration" "${agents[@]}"
515
+ sleep 30
516
+ done
517
+ ) &
518
+
519
+ # No echo - caller will use $! to get PID
520
+ }
521
+
522
+ function stop_heartbeat_monitor() {
523
+ local task_id="$1"
524
+ local loop_name="$2"
525
+ local monitor_pid="$3"
526
+
527
+ # Remove marker file to stop the monitor loop
528
+ rm -f "/tmp/heartbeat-monitor-${task_id}-${loop_name}.active"
529
+
530
+ # Kill monitor process if still running
531
+ if [ -n "$monitor_pid" ] && kill -0 "$monitor_pid" 2>/dev/null; then
532
+ kill "$monitor_pid" 2>/dev/null || true
533
+ wait "$monitor_pid" 2>/dev/null || true
534
+ fi
535
+ }
536
+
537
+ ##############################################################################
538
+ # Get Agent-Specific Timeout
539
+ ##############################################################################
540
+ function get_agent_timeout() {
541
+ local agent="$1"
542
+ local task_id="$2"
543
+
544
+ # Use get-agent-timeout.sh helper script
545
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
546
+ AGENT_TIMEOUT=$("$SCRIPT_DIR/get-agent-timeout.sh" --task-id "$task_id" --agent-id "$agent" 2>/dev/null || echo "$TIMEOUT")
547
+
548
+ echo "$AGENT_TIMEOUT"
549
+ }
550
+
551
+ ##############################################################################
552
+ # Process-Based Completion Monitoring
553
+ ##############################################################################
554
+ function monitor_agent_process() {
555
+ local agent_id="$1"
556
+ local agent_pid="$2"
557
+ local task_id="$3"
558
+ local done_key="$4"
559
+
560
+ # Monitor agent process in background
561
+ (
562
+ # Wait for process to exit
563
+ wait "$agent_pid" 2>/dev/null
564
+ EXIT_CODE=$?
565
+
566
+ # Check if done signal already sent (agent may have signaled normally)
567
+ DONE_COUNT=$(redis-cli LLEN "$done_key" 2>/dev/null || echo "0")
568
+ if [ "$DONE_COUNT" -gt 0 ]; then
569
+ # Agent signaled normally - nothing to do
570
+ exit 0
571
+ fi
572
+
573
+ # Process exited without signaling - auto-complete
574
+ if [ $EXIT_CODE -eq 0 ]; then
575
+ echo " [Process Monitor] $agent_id exited successfully (code 0) - auto-signaling completion" >&2
576
+ redis-cli LPUSH "$done_key" "auto-completed-success" >/dev/null
577
+ else
578
+ echo " [Process Monitor] $agent_id exited with error (code $EXIT_CODE) - auto-signaling failure" >&2
579
+ redis-cli LPUSH "$done_key" "auto-completed-error:$EXIT_CODE" >/dev/null
580
+
581
+ # METRICS: Increment error counter
582
+ redis-cli INCR "swarm:${task_id}:metrics:agent_errors" >/dev/null
583
+ fi
584
+ ) &
585
+ }
586
+
587
+ ##############################################################################
588
+ # BLPOP with Retry Logic + Process Monitoring
589
+ ##############################################################################
590
+ function blpop_with_retry() {
591
+ local agent="$1"
592
+ local done_key="$2"
593
+ local timeout="$3"
594
+ local retry_count="$4"
595
+ local retry_delay="$5"
596
+ local agent_pid="${6:-}" # Optional: PID for process monitoring
597
+
598
+ for ATTEMPT in $(seq 1 $retry_count); do
599
+ # Check for shutdown before attempting BLPOP
600
+ if [ "$SHUTDOWN_REQUESTED" -eq 1 ]; then
601
+ echo " [SHUTDOWN] Aborting BLPOP for $agent" >&2
602
+ return 1
603
+ fi
604
+
605
+ # Use Redis's native BLPOP timeout instead of shell timeout command
606
+ # This allows SIGTERM to properly interrupt the process
607
+ RESULT=$(redis-cli blpop "$done_key" "$timeout" 2>/dev/null || echo "")
608
+
609
+ if [ -n "$RESULT" ]; then
610
+ echo "$RESULT"
611
+ return 0 # Success
612
+ fi
613
+
614
+ # BLPOP timeout - check if process is still alive
615
+ if [ -n "$agent_pid" ]; then
616
+ if ! kill -0 "$agent_pid" 2>/dev/null; then
617
+ echo " [Process Check] Agent process $agent_pid no longer running" >&2
618
+
619
+ # Process exited - check if done signal was auto-generated
620
+ RESULT=$(redis-cli LPOP "$done_key" 2>/dev/null || echo "")
621
+ if [ -n "$RESULT" ]; then
622
+ echo " [Auto-Complete] Retrieved: $RESULT" >&2
623
+ echo "$RESULT"
624
+ return 0
625
+ fi
626
+ fi
627
+ fi
628
+
629
+ # Check for shutdown after BLPOP timeout
630
+ if [ "$SHUTDOWN_REQUESTED" -eq 1 ]; then
631
+ echo " [SHUTDOWN] Aborting retry for $agent" >&2
632
+ return 1
633
+ fi
634
+
635
+ # Check heartbeat status
636
+ HEARTBEAT_KEY="swarm:${TASK_ID}:${agent}:heartbeat"
637
+ HEARTBEAT_EXISTS=$(redis-cli EXISTS "$HEARTBEAT_KEY" 2>/dev/null || echo "0")
638
+
639
+ if [ "$HEARTBEAT_EXISTS" -eq 0 ]; then
640
+ echo " ⚠️ No heartbeat from $agent - agent may be stuck or crashed" >&2
641
+
642
+ # If we have PID and process is stuck, kill it
643
+ if [ -n "$agent_pid" ] && kill -0 "$agent_pid" 2>/dev/null; then
644
+ echo " [Timeout Kill] Terminating stuck process $agent_pid" >&2
645
+ kill "$agent_pid" 2>/dev/null || true
646
+ sleep 2
647
+
648
+ # Force kill if still alive
649
+ if kill -0 "$agent_pid" 2>/dev/null; then
650
+ kill -9 "$agent_pid" 2>/dev/null || true
651
+ fi
652
+
653
+ # METRICS: Increment timeout counter
654
+ redis-cli INCR "swarm:${TASK_ID}:metrics:agent_killed" >/dev/null
655
+ fi
656
+ fi
657
+
658
+ # Log retry attempt (to stderr so it's visible during command substitution)
659
+ local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
660
+ echo " [$timestamp] ⚠️ BLPOP attempt $ATTEMPT/$retry_count failed for $agent" >&2
661
+
662
+ if [ $ATTEMPT -lt $retry_count ]; then
663
+ # METRICS: Increment retry counter
664
+ redis-cli INCR "swarm:${TASK_ID}:metrics:retry_count" >/dev/null
665
+
666
+ retry_with_backoff "$agent" "$ATTEMPT" "$retry_count" "$retry_delay" >&2
667
+ else
668
+ # Final failure - write to DLQ
669
+ echo " [$timestamp] ❌ FINAL FAILURE: $agent after $retry_count attempts" >&2
670
+ write_to_dlq "$agent" "timeout_after_retries" "$retry_count"
671
+ return 1
672
+ fi
673
+ done
674
+
675
+ return 1
676
+ }
677
+
678
+ echo "=== CFN Loop Orchestration ==="
679
+ echo "Task ID: $TASK_ID"
680
+ echo "Mode: $MODE (Gate: $GATE, Consensus: $CONSENSUS)"
681
+ echo "Max Iterations: $MAX_ITERATIONS"
682
+ echo ""
683
+
684
+ # Initialize swarm using general Redis coordination primitive
685
+ SWARM_ID="swarm-${TASK_ID}"
686
+ ALL_AGENTS="${LOOP3_AGENTS},${LOOP2_AGENTS},${PRODUCT_OWNER}"
687
+
688
+ # LOG: Swarm initialization
689
+ ./.claude/skills/redis-coordination/log-event.sh \
690
+ --task-id "$TASK_ID" \
691
+ --event-type "swarm_init" \
692
+ --details "{\"mode\": \"$MODE\", \"loop3_agents\": \"$LOOP3_AGENTS\", \"loop2_agents\": \"$LOOP2_AGENTS\", \"product_owner\": \"$PRODUCT_OWNER\", \"max_iterations\": $MAX_ITERATIONS, \"gate_threshold\": $GATE, \"consensus_threshold\": $CONSENSUS}" \
693
+ --level "INFO" 2>/dev/null || true
694
+
695
+ # Build CFN-specific metadata
696
+ CFN_METADATA=$(cat <<EOF
697
+ {
698
+ "mode": "$MODE",
699
+ "loop3_agents": "$LOOP3_AGENTS",
700
+ "loop2_agents": "$LOOP2_AGENTS",
701
+ "product_owner": "$PRODUCT_OWNER",
702
+ "workflow_type": "cfn_loop"
703
+ }
704
+ EOF
705
+ )
706
+
707
+ # Use general init-swarm primitive
708
+ ./.claude/skills/redis-coordination/init-swarm.sh \
709
+ --swarm-id "$SWARM_ID" \
710
+ --agents "$ALL_AGENTS" \
711
+ --task-id "$TASK_ID" \
712
+ --topology "hierarchical" \
713
+ --metadata "$CFN_METADATA" > /dev/null
714
+
715
+ # Start shutdown monitor in background
716
+ start_shutdown_monitor "$TASK_ID"
717
+
718
+ # Store epic context in Redis (if provided)
719
+ if [ -n "$EPIC_CONTEXT" ]; then
720
+ echo "📋 Storing epic context in Redis..."
721
+ # Escape single quotes for Redis
722
+ EPIC_ESCAPED="${EPIC_CONTEXT//\'/\'\\\'\'}"
723
+ redis-cli setex "swarm:${TASK_ID}:epic-context" 604800 "$EPIC_ESCAPED" >/dev/null
724
+ echo " ✅ Epic context stored (TTL: 7 days)"
725
+ fi
726
+
727
+ if [ -n "$PHASE_CONTEXT" ]; then
728
+ echo "📋 Storing phase context in Redis..."
729
+ PHASE_ESCAPED="${PHASE_CONTEXT//\'/\'\\\'\'}"
730
+ redis-cli setex "swarm:${TASK_ID}:phase-context" 604800 "$PHASE_ESCAPED" >/dev/null
731
+ echo " ✅ Phase context stored (TTL: 7 days)"
732
+ fi
733
+
734
+ if [ -n "$SUCCESS_CRITERIA" ]; then
735
+ echo "📋 Storing success criteria in Redis..."
736
+ CRITERIA_ESCAPED="${SUCCESS_CRITERIA//\'/\'\\\'\'}"
737
+ redis-cli setex "swarm:${TASK_ID}:success-criteria" 604800 "$CRITERIA_ESCAPED" >/dev/null
738
+ echo " ✅ Success criteria stored (TTL: 7 days)"
739
+ fi
740
+
741
+ echo ""
742
+
743
+ # [BUG #15 FIX] REMOVED: Early Product Owner spawn at iteration 0
744
+ # Product Owner now only spawned after Loop 2 completes (see line 1283)
745
+ # This prevents timeout issues with waiting mode initialization
746
+ echo "[Product Owner] Will spawn after Loop 2 consensus (just-in-time pattern)"
747
+ echo ""
748
+
749
+ # Iteration loop
750
+ for ITERATION in $(seq 1 $MAX_ITERATIONS); do
751
+ echo "=== Iteration $ITERATION/$MAX_ITERATIONS ==="
752
+
753
+ # METRICS: Iteration start timestamp
754
+ ITERATION_START=$(date +%s%N | cut -b1-13) # milliseconds
755
+ redis-cli LPUSH "swarm:${TASK_ID}:metrics:iteration_start" "$ITERATION_START" >/dev/null
756
+
757
+ # Step 1: Build detailed agent context from Redis (BUG #20 FIX - Option 2)
758
+ echo "[Loop 3] Building agent context from Redis..."
759
+
760
+ # Retrieve stored context
761
+ EPIC_CTX=$(redis-cli get "swarm:${TASK_ID}:epic-context" 2>/dev/null || echo "{}")
762
+ PHASE_CTX=$(redis-cli get "swarm:${TASK_ID}:phase-context" 2>/dev/null || echo "{}")
763
+ SUCCESS_CTX=$(redis-cli get "swarm:${TASK_ID}:success-criteria" 2>/dev/null || echo "{}")
764
+
765
+ # Extract key fields with jq (safe parsing)
766
+ EPIC_GOAL=$(echo "$EPIC_CTX" | jq -r '.epicGoal // "No epic goal specified"')
767
+ IN_SCOPE=$(echo "$EPIC_CTX" | jq -r '.inScope[]? // empty' | sed 's/^/- /' || echo "- (not specified)")
768
+ OUT_SCOPE=$(echo "$EPIC_CTX" | jq -r '.outOfScope[]? // empty' | sed 's/^/- /' || echo "- (not specified)")
769
+ DELIVERABLES=$(echo "$PHASE_CTX" | jq -r '.deliverables[]? // empty' | sed 's/^/- /' || echo "- (not specified)")
770
+ DIRECTORY=$(echo "$PHASE_CTX" | jq -r '.directory // ""')
771
+ ACCEPTANCE=$(echo "$SUCCESS_CTX" | jq -r '.acceptanceCriteria[]? // empty' | sed 's/^/- /' || echo "- (not specified)")
772
+
773
+ # Build structured agent context
774
+ # Build JSON context for Loop 3 (v2.10.0 - bidirectional JSON)
775
+ # Extract arrays with safe defaults to prevent empty string errors
776
+ IN_SCOPE_ARRAY=$(echo "$EPIC_CTX" | jq -c '.inScope // []')
777
+ OUT_SCOPE_ARRAY=$(echo "$EPIC_CTX" | jq -c '.outOfScope // []')
778
+ DELIVERABLES_ARRAY=$(echo "$PHASE_CTX" | jq -c '.deliverables // []')
779
+ ACCEPTANCE_ARRAY=$(echo "$SUCCESS_CTX" | jq -c '.acceptanceCriteria // []')
780
+
781
+ # Safe defaults to prevent empty string errors in jq --argjson
782
+ SAFE_IN_SCOPE="${IN_SCOPE_ARRAY:-[]}"
783
+ SAFE_OUT_SCOPE="${OUT_SCOPE_ARRAY:-[]}"
784
+ SAFE_DELIVERABLES="${DELIVERABLES_ARRAY:-[]}"
785
+ SAFE_ACCEPTANCE="${ACCEPTANCE_ARRAY:-[]}"
786
+
787
+ # Use ITERATION variable or default to 1
788
+ ITERATION_NUM="${ITERATION:-1}"
789
+
790
+ LOOP3_AGENT_CONTEXT=$(jq -n \
791
+ --arg task "Loop 3 implementation for iteration $ITERATION_NUM" \
792
+ --arg epicGoal "$EPIC_GOAL" \
793
+ --arg phaseId "${PHASE_ID:-}" \
794
+ --argjson inScope "$SAFE_IN_SCOPE" \
795
+ --argjson outOfScope "$SAFE_OUT_SCOPE" \
796
+ --argjson deliverables "$SAFE_DELIVERABLES" \
797
+ --argjson acceptanceCriteria "$SAFE_ACCEPTANCE" \
798
+ --arg directory "${DIRECTORY:-}" \
799
+ --arg taskId "$TASK_ID" \
800
+ --arg iteration "$ITERATION_NUM" \
801
+ --argjson instructions '["Use Write tool to create each deliverable file", "Verify files created with ls -la after each Write", "All deliverables must exist for validation to pass", "Report confidence score based on actual file creation"]' \
802
+ '{
803
+ loop: "loop3",
804
+ iteration: ($iteration | tonumber),
805
+ task: $task,
806
+ epicGoal: $epicGoal,
807
+ phaseId: (if $phaseId == "" then null else $phaseId end),
808
+ inScope: $inScope,
809
+ outOfScope: $outOfScope,
810
+ deliverables: $deliverables,
811
+ directory: (if $directory == "" then null else $directory end),
812
+ acceptanceCriteria: $acceptanceCriteria,
813
+ instructions: $instructions,
814
+ taskId: $taskId
815
+ }')
816
+
817
+ # Validate JSON was built successfully
818
+ if ! echo "$LOOP3_AGENT_CONTEXT" | jq empty >/dev/null 2>&1; then
819
+ echo "[ERROR] Failed to build Loop 3 JSON context"
820
+ exit 1
821
+ fi
822
+
823
+ echo " ✅ Loop 3 JSON context built successfully"
824
+
825
+ # Split agents for input context storage
826
+ IFS=',' read -ra AGENTS <<< "$LOOP3_AGENTS"
827
+
828
+ # NEW: Add real-time file checklist (STRAT-025: Explicit Deliverable Tracking)
829
+ # Extract deliverable file paths from phase context
830
+ DELIVERABLE_FILES=$(echo "$PHASE_CTX" | jq -r '.deliverables[]? // empty' 2>/dev/null)
831
+
832
+ if [ -n "$DELIVERABLE_FILES" ]; then
833
+ DELIVERABLE_CHECKLIST="\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
834
+ DELIVERABLE CHECKLIST (verify BEFORE reporting confidence)
835
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
836
+
837
+ MISSING_COUNT=0
838
+ COMPLETE_COUNT=0
839
+
840
+ # Check each deliverable file
841
+ while IFS= read -r file; do
842
+ # Skip empty lines
843
+ [ -z "$file" ] && continue
844
+
845
+ # Convert relative paths to absolute if needed
846
+ if [[ "$file" != /* ]]; then
847
+ # If DIRECTORY is set, prepend it
848
+ if [ -n "$DIRECTORY" ]; then
849
+ file="${DIRECTORY}/${file}"
850
+ fi
851
+ fi
852
+
853
+ if [ -f "$file" ]; then
854
+ DELIVERABLE_CHECKLIST="${DELIVERABLE_CHECKLIST}✅ COMPLETE: $file\n"
855
+ COMPLETE_COUNT=$((COMPLETE_COUNT + 1))
856
+ else
857
+ DELIVERABLE_CHECKLIST="${DELIVERABLE_CHECKLIST}❌ MISSING: $file (YOU MUST CREATE THIS)\n"
858
+ MISSING_COUNT=$((MISSING_COUNT + 1))
859
+ fi
860
+ done <<< "$DELIVERABLE_FILES"
861
+
862
+ # Add status summary
863
+ DELIVERABLE_CHECKLIST="${DELIVERABLE_CHECKLIST}\nStatus: ${COMPLETE_COUNT} complete, ${MISSING_COUNT} missing\n"
864
+
865
+ if [ "$MISSING_COUNT" -gt 0 ]; then
866
+ DELIVERABLE_CHECKLIST="${DELIVERABLE_CHECKLIST}\n⚠️ CRITICAL: ${MISSING_COUNT} file(s) marked ❌ MISSING above.
867
+ Your confidence should be LOW (<0.50) until ALL files are created.
868
+ Create ALL missing files before reporting high confidence.\n"
869
+ else
870
+ DELIVERABLE_CHECKLIST="${DELIVERABLE_CHECKLIST}\n✅ All deliverables complete! You may report high confidence if quality requirements met.\n"
871
+ fi
872
+
873
+ # Append checklist to agent context
874
+ LOOP3_AGENT_CONTEXT="${LOOP3_AGENT_CONTEXT}${DELIVERABLE_CHECKLIST}"
875
+
876
+ echo " 📋 Deliverable checklist: ${COMPLETE_COUNT} complete, ${MISSING_COUNT} missing"
877
+ fi
878
+
879
+ # PHASE 1 (BUG #23): Inject feedback history for iterative learning
880
+ if [ "$ITERATION" -gt 1 ]; then
881
+ FEEDBACK_HISTORY=$(redis-cli GET "swarm:${TASK_ID}:feedback:history" 2>/dev/null)
882
+ # Normalize empty/nil to valid JSON array
883
+ if [ -z "$FEEDBACK_HISTORY" ] || [ "$FEEDBACK_HISTORY" = "(nil)" ]; then
884
+ FEEDBACK_HISTORY="[]"
885
+ fi
886
+
887
+ if [ "$FEEDBACK_HISTORY" != "[]" ]; then
888
+ # Inject feedback array into JSON context
889
+ LOOP3_AGENT_CONTEXT=$(echo "$LOOP3_AGENT_CONTEXT" | jq \
890
+ --argjson feedback "$FEEDBACK_HISTORY" \
891
+ '. + {feedbackHistory: $feedback}')
892
+
893
+ echo " 📝 Injected feedback history ($(echo "$FEEDBACK_HISTORY" | jq '. | length') items)"
894
+ fi
895
+ fi
896
+
897
+ # Store Loop 3 input context in Redis (v2.10.0 - bidirectional JSON)
898
+ # This enables swarm recovery and provides audit trail
899
+ for i in "${!AGENTS[@]}"; do
900
+ AGENT="${AGENTS[$i]}"
901
+ # Generate agent ID for storage (will be calculated again in spawn loop)
902
+ if [ -z "${AGENT_INSTANCE_COUNTS[$AGENT]}" ]; then
903
+ AGENT_INSTANCE_COUNTS[$AGENT]=1
904
+ else
905
+ AGENT_INSTANCE_COUNTS[$AGENT]=$((AGENT_INSTANCE_COUNTS[$AGENT] + 1))
906
+ fi
907
+ AGENT_ID="${AGENT}-${AGENT_INSTANCE_COUNTS[$AGENT]}-${ITERATION}"
908
+
909
+ # Store input context
910
+ redis-cli SETEX "cfn_loop:task:${TASK_ID}:loop3:input:${AGENT_ID}" 86400 "$LOOP3_AGENT_CONTEXT" >/dev/null 2>&1
911
+
912
+ # Log to message history
913
+ MESSAGE_LOG=$(jq -n \
914
+ --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
915
+ --arg direction "input" \
916
+ --arg loop "loop3" \
917
+ --arg agent_id "$AGENT_ID" \
918
+ --argjson context "$LOOP3_AGENT_CONTEXT" \
919
+ '{
920
+ timestamp: $timestamp,
921
+ direction: $direction,
922
+ loop: $loop,
923
+ agent_id: $agent_id,
924
+ context: $context
925
+ }')
926
+ redis-cli LPUSH "cfn_loop:task:${TASK_ID}:messages" "$MESSAGE_LOG" >/dev/null 2>&1
927
+ done
928
+
929
+ # Reset instance counts for actual spawn loop
930
+ unset AGENT_INSTANCE_COUNTS
931
+ declare -A AGENT_INSTANCE_COUNTS
932
+
933
+ echo " ✅ Agent context built ($(echo "$LOOP3_AGENT_CONTEXT" | wc -c) characters)"
934
+ echo " ✅ Stored input context in Redis for ${#AGENTS[@]} agents"
935
+ echo ""
936
+
937
+ # Step 2: Spawn Loop 3 agents via CLI
938
+ echo "[Loop 3] Spawning implementers via CLI..."
939
+
940
+ # Track instance counts to generate unique agent IDs for duplicate agent types
941
+ declare -A AGENT_INSTANCE_COUNTS
942
+ declare -A AGENT_IDS # Map from array index to unique agent ID
943
+
944
+ # Pre-calculate unique agent IDs
945
+ for i in "${!AGENTS[@]}"; do
946
+ AGENT="${AGENTS[$i]}"
947
+
948
+ # Increment instance counter for this agent type
949
+ AGENT_INSTANCE_COUNTS["$AGENT"]=$((${AGENT_INSTANCE_COUNTS["$AGENT"]:-0} + 1))
950
+ INSTANCE_NUM="${AGENT_INSTANCE_COUNTS["$AGENT"]}"
951
+
952
+ # Generate unique agent ID: agent-type-iteration-instance
953
+ UNIQUE_AGENT_ID="${AGENT}-${ITERATION}-${INSTANCE_NUM}"
954
+ AGENT_IDS["$i"]="$UNIQUE_AGENT_ID"
955
+
956
+ echo " [Instance Tracking] ${AGENT} #${INSTANCE_NUM} → ${UNIQUE_AGENT_ID}"
957
+ done
958
+
959
+ echo ""
960
+
961
+ # [PHASE 1 INTEGRATION] Loop 3 Skill-Based Output Processing (Parallel)
962
+ # Uses .claude/skills/loop3-output-processing/ for guaranteed confidence extraction
963
+ echo "[Loop 3] Using skill-based output processing (parallel execution)"
964
+
965
+ LOOP3_TOTAL=${#AGENTS[@]}
966
+ LOOP3_REQUIRED=$(calculate_quorum "$MIN_QUORUM_LOOP3" "$LOOP3_TOTAL")
967
+ LOOP3_COMPLETED_AGENTS=()
968
+ LOOP3_FAILED_AGENTS=()
969
+
970
+ echo "[Loop 3] Quorum: $LOOP3_REQUIRED/$LOOP3_TOTAL agents required"
971
+ echo ""
972
+
973
+ # Step 2a: Spawn all agents in parallel (background processes)
974
+ declare -A AGENT_PIDS
975
+ declare -A AGENT_OUTPUT_FILES
976
+
977
+ for i in "${!AGENTS[@]}"; do
978
+ AGENT="${AGENTS[$i]}"
979
+ UNIQUE_AGENT_ID="${AGENT_IDS[$i]}"
980
+
981
+ # Get agent-specific timeout
982
+ AGENT_TIMEOUT=$(get_agent_timeout "$AGENT" "$TASK_ID")
983
+
984
+ # Create temp file for agent output
985
+ OUTPUT_FILE="/tmp/loop3-${TASK_ID}-${UNIQUE_AGENT_ID}.json"
986
+ AGENT_OUTPUT_FILES["$UNIQUE_AGENT_ID"]="$OUTPUT_FILE"
987
+
988
+ echo " Spawning $AGENT (ID: $UNIQUE_AGENT_ID, timeout: ${AGENT_TIMEOUT}s)"
989
+
990
+ # LOG: Loop 3 agent spawn
991
+ ./.claude/skills/redis-coordination/log-event.sh \
992
+ --task-id "$TASK_ID" \
993
+ --event-type "agent_spawn" \
994
+ --loop "loop3" \
995
+ --agent-id "$UNIQUE_AGENT_ID" \
996
+ --iteration "$ITERATION" \
997
+ --details "{\"agent_type\": \"$AGENT\", \"timeout\": $AGENT_TIMEOUT}" \
998
+ --level "INFO" 2>/dev/null || true
999
+
1000
+ # Execute agent via Loop 3 skill in background
1001
+ (
1002
+ # Record start time
1003
+ START_TIME=$(date +%s%N | cut -b1-13)
1004
+
1005
+ # Execute skill (BUG #20 FIX - inject detailed context)
1006
+ if SKILL_RESULT=$(./.claude/skills/loop3-output-processing/execute-and-extract.sh \
1007
+ --agent-type "$AGENT" \
1008
+ --task-id "$TASK_ID" \
1009
+ --agent-id "$UNIQUE_AGENT_ID" \
1010
+ --context "$LOOP3_AGENT_CONTEXT" \
1011
+ --iteration "$ITERATION" \
1012
+ --timeout "$AGENT_TIMEOUT" 2>&1); then
1013
+
1014
+ # Record end time
1015
+ END_TIME=$(date +%s%N | cut -b1-13)
1016
+ LATENCY=$((END_TIME - START_TIME))
1017
+
1018
+ # Add latency to result
1019
+ RESULT_WITH_LATENCY=$(echo "$SKILL_RESULT" | jq --arg latency "$LATENCY" '. + {latency_ms: ($latency | tonumber)}')
1020
+
1021
+ # Save to temp file
1022
+ echo "$RESULT_WITH_LATENCY" > "$OUTPUT_FILE"
1023
+
1024
+ # Store result in Redis (legacy key for backward compatibility)
1025
+ echo "$RESULT_WITH_LATENCY" | redis-cli -x LPUSH "swarm:${TASK_ID}:${UNIQUE_AGENT_ID}:result" >/dev/null
1026
+ redis-cli LPUSH "swarm:${TASK_ID}:${UNIQUE_AGENT_ID}:done" "complete" >/dev/null
1027
+
1028
+ # Store Loop 3 output context in Redis (v2.10.0 - bidirectional JSON)
1029
+ redis-cli SETEX "cfn_loop:task:${TASK_ID}:loop3:output:${UNIQUE_AGENT_ID}" 86400 "$RESULT_WITH_LATENCY" >/dev/null 2>&1
1030
+
1031
+ # Log to message history
1032
+ MESSAGE_LOG=$(jq -n \
1033
+ --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
1034
+ --arg direction "output" \
1035
+ --arg loop "loop3" \
1036
+ --arg agent_id "$UNIQUE_AGENT_ID" \
1037
+ --argjson output "$RESULT_WITH_LATENCY" \
1038
+ '{
1039
+ timestamp: $timestamp,
1040
+ direction: $direction,
1041
+ loop: $loop,
1042
+ agent_id: $agent_id,
1043
+ output: $output
1044
+ }')
1045
+ redis-cli LPUSH "cfn_loop:task:${TASK_ID}:messages" "$MESSAGE_LOG" >/dev/null 2>&1
1046
+
1047
+ exit 0
1048
+ else
1049
+ # Skill failed - save error
1050
+ echo "{\"error\": true, \"output\": \"$SKILL_RESULT\"}" > "$OUTPUT_FILE"
1051
+ exit 1
1052
+ fi
1053
+ ) &
1054
+
1055
+ AGENT_PIDS["$UNIQUE_AGENT_ID"]=$!
1056
+ echo " ✅ Spawned $UNIQUE_AGENT_ID (PID: ${AGENT_PIDS[$UNIQUE_AGENT_ID]})"
1057
+ done
1058
+
1059
+ echo ""
1060
+ echo "[Loop 3] All agents spawned, waiting for completion..."
1061
+ echo ""
1062
+
1063
+ # Step 2b: Wait for all agents to complete
1064
+ for i in "${!AGENTS[@]}"; do
1065
+ AGENT="${AGENTS[$i]}"
1066
+ UNIQUE_AGENT_ID="${AGENT_IDS[$i]}"
1067
+ AGENT_PID="${AGENT_PIDS[$UNIQUE_AGENT_ID]}"
1068
+ OUTPUT_FILE="${AGENT_OUTPUT_FILES[$UNIQUE_AGENT_ID]}"
1069
+
1070
+ echo " Waiting for $UNIQUE_AGENT_ID (PID: $AGENT_PID)..."
1071
+
1072
+ # Wait for specific agent process
1073
+ if wait "$AGENT_PID" 2>/dev/null; then
1074
+ # Success - read result from temp file
1075
+ if [ -f "$OUTPUT_FILE" ]; then
1076
+ SKILL_RESULT=$(cat "$OUTPUT_FILE")
1077
+
1078
+ # Check if result has error flag
1079
+ HAS_ERROR=$(echo "$SKILL_RESULT" | jq -r '.error // false')
1080
+
1081
+ if [ "$HAS_ERROR" = "false" ]; then
1082
+ # Extract metrics
1083
+ CONFIDENCE=$(echo "$SKILL_RESULT" | jq -r '.confidence')
1084
+ FILES_CHANGED=$(echo "$SKILL_RESULT" | jq -r '.files_changed')
1085
+ CONFIDENCE_SOURCE=$(echo "$SKILL_RESULT" | jq -r '.confidence_source')
1086
+ LATENCY=$(echo "$SKILL_RESULT" | jq -r '.latency_ms')
1087
+
1088
+ echo " ✅ $UNIQUE_AGENT_ID complete (${LATENCY}ms, confidence: $CONFIDENCE [$CONFIDENCE_SOURCE], files: $FILES_CHANGED)"
1089
+
1090
+ # BUGFIX #21: Store confidence in Redis for consensus collection
1091
+ # The skill script extracts confidence but doesn't store it where invoke-waiting-mode.sh collect expects
1092
+ ./.claude/skills/redis-coordination/invoke-waiting-mode.sh report \
1093
+ --task-id "$TASK_ID" \
1094
+ --agent-id "$UNIQUE_AGENT_ID" \
1095
+ --confidence "$CONFIDENCE" \
1096
+ --iteration "$ITERATION" >/dev/null
1097
+
1098
+ # LOG: Loop 3 agent completion
1099
+ ./.claude/skills/redis-coordination/log-event.sh \
1100
+ --task-id "$TASK_ID" \
1101
+ --event-type "agent_complete" \
1102
+ --loop "loop3" \
1103
+ --agent-id "$UNIQUE_AGENT_ID" \
1104
+ --iteration "$ITERATION" \
1105
+ --details "{\"confidence\": $CONFIDENCE, \"confidence_source\": \"$CONFIDENCE_SOURCE\", \"files_changed\": $FILES_CHANGED, \"latency_ms\": $LATENCY}" \
1106
+ --level "INFO" 2>/dev/null || true
1107
+
1108
+ # Store latency metric
1109
+ METRIC=$(jq -nc \
1110
+ --arg agent "$UNIQUE_AGENT_ID" \
1111
+ --arg latency "$LATENCY" \
1112
+ --arg loop "loop3" \
1113
+ --arg iteration "$ITERATION" \
1114
+ '{agent: $agent, latency_ms: ($latency | tonumber), loop: $loop, iteration: ($iteration | tonumber)}')
1115
+ echo "$METRIC" | redis-cli -x LPUSH "swarm:${TASK_ID}:metrics:agent_latency" >/dev/null
1116
+
1117
+ LOOP3_COMPLETED_AGENTS+=("$UNIQUE_AGENT_ID")
1118
+ else
1119
+ ERROR_OUTPUT=$(echo "$SKILL_RESULT" | jq -r '.output')
1120
+ echo " ❌ $UNIQUE_AGENT_ID failed (skill execution error)"
1121
+ echo " Error: $ERROR_OUTPUT"
1122
+
1123
+ # LOG: Loop 3 agent failure
1124
+ ./.claude/skills/redis-coordination/log-event.sh \
1125
+ --task-id "$TASK_ID" \
1126
+ --event-type "agent_failure" \
1127
+ --loop "loop3" \
1128
+ --agent-id "$UNIQUE_AGENT_ID" \
1129
+ --iteration "$ITERATION" \
1130
+ --details "{\"error\": \"skill_execution_error\", \"output\": \"$ERROR_OUTPUT\"}" \
1131
+ --level "ERROR" 2>/dev/null || true
1132
+
1133
+ LOOP3_FAILED_AGENTS+=("$AGENT")
1134
+ redis-cli INCR "swarm:${TASK_ID}:metrics:agent_failure_count" >/dev/null
1135
+ fi
1136
+
1137
+ # Cleanup temp file
1138
+ rm -f "$OUTPUT_FILE"
1139
+ else
1140
+ echo " ❌ $UNIQUE_AGENT_ID failed (no output file)"
1141
+ LOOP3_FAILED_AGENTS+=("$AGENT")
1142
+ redis-cli INCR "swarm:${TASK_ID}:metrics:agent_failure_count" >/dev/null
1143
+ fi
1144
+ else
1145
+ echo " ❌ $UNIQUE_AGENT_ID failed (process error)"
1146
+ LOOP3_FAILED_AGENTS+=("$AGENT")
1147
+ redis-cli INCR "swarm:${TASK_ID}:metrics:agent_failure_count" >/dev/null
1148
+ rm -f "$OUTPUT_FILE"
1149
+ fi
1150
+
1151
+ echo ""
1152
+ done
1153
+
1154
+ # Validate quorum
1155
+ if [ ${#LOOP3_COMPLETED_AGENTS[@]} -ge "$LOOP3_REQUIRED" ]; then
1156
+ echo "[Loop 3] ✅ Quorum met: ${#LOOP3_COMPLETED_AGENTS[@]}/$LOOP3_REQUIRED agents completed"
1157
+ if [ ${#LOOP3_FAILED_AGENTS[@]} -gt 0 ]; then
1158
+ echo "[Loop 3] ⚠️ Failed agents (continuing with quorum): ${LOOP3_FAILED_AGENTS[*]}"
1159
+
1160
+ # METRICS: Increment quorum fallback counter
1161
+ redis-cli INCR "swarm:${TASK_ID}:metrics:quorum_fallback" >/dev/null
1162
+ fi
1163
+ else
1164
+ echo "[Loop 3] ❌ Quorum FAILED: ${#LOOP3_COMPLETED_AGENTS[@]} < $LOOP3_REQUIRED"
1165
+ echo "[Loop 3] Failed agents: ${LOOP3_FAILED_AGENTS[*]}"
1166
+ exit 1
1167
+ fi
1168
+ echo ""
1169
+
1170
+ # Step 2: Collect Loop 3 confidence scores (only from completed agents)
1171
+ echo "[Loop 3] Collecting confidence scores from ${#LOOP3_COMPLETED_AGENTS[@]} agents..."
1172
+ LOOP3_COMPLETED_IDS=$(IFS=','; echo "${LOOP3_COMPLETED_AGENTS[*]}")
1173
+ LOOP3_CONSENSUS=$(./.claude/skills/redis-coordination/collect-confidence-scores.sh \
1174
+ --task-id "$TASK_ID" \
1175
+ --agent-ids "$LOOP3_COMPLETED_IDS" | tail -1)
1176
+
1177
+ echo "[Loop 3] Average confidence: $LOOP3_CONSENSUS (from ${#LOOP3_COMPLETED_AGENTS[@]}/${LOOP3_TOTAL} agents)"
1178
+
1179
+ # METRICS: Store Loop 3 consensus score
1180
+ LOOP3_METRIC=$(jq -nc \
1181
+ --arg consensus "$LOOP3_CONSENSUS" \
1182
+ --arg iteration "$ITERATION" \
1183
+ '{consensus: ($consensus | tonumber), iteration: ($iteration | tonumber)}')
1184
+ echo "$LOOP3_METRIC" | redis-cli -x LPUSH "swarm:${TASK_ID}:metrics:loop3_consensus" >/dev/null
1185
+
1186
+ # BUG #12 FIX: Deliverable Verification with explicit file checking
1187
+ echo "[Deliverable Check] Verifying implementation artifacts..."
1188
+
1189
+ # Use enhanced validate-deliverables.sh skill
1190
+ DELIVERABLE_ARGS="--task-id $TASK_ID"
1191
+ if [ -n "$EXPECTED_FILES" ]; then
1192
+ DELIVERABLE_ARGS="$DELIVERABLE_ARGS --expected-files $EXPECTED_FILES"
1193
+ echo " Expected files: $EXPECTED_FILES"
1194
+ fi
1195
+
1196
+ DELIVERABLE_STATUS=$(./.claude/skills/product-owner-decision/validate-deliverables.sh $DELIVERABLE_ARGS)
1197
+
1198
+ if [ "$DELIVERABLE_STATUS" = "FAILED" ]; then
1199
+ # Retrieve missing files from Redis (if available)
1200
+ MISSING_FILES_JSON=$(redis-cli get "swarm:${TASK_ID}:missing-files" 2>/dev/null || echo "[]")
1201
+ MISSING_FILES_LIST=$(echo "$MISSING_FILES_JSON" | jq -r '.[]' | tr '\n' ', ' | sed 's/,$//')
1202
+
1203
+ if [ -n "$MISSING_FILES_LIST" ]; then
1204
+ echo "❌ DELIVERABLE VERIFICATION FAILED: Missing files"
1205
+ echo " Expected but not found: $MISSING_FILES_LIST"
1206
+ else
1207
+ echo "❌ DELIVERABLE VERIFICATION FAILED: No files created or modified"
1208
+ fi
1209
+
1210
+ echo " This prevents 'consensus on vapor' - validators approving nothing"
1211
+ echo ""
1212
+ echo "Decision: RELAUNCH iteration $((ITERATION + 1)) (skip Loop 2 validation)"
1213
+ echo ""
1214
+
1215
+ # METRICS: Increment deliverable failure counter
1216
+ redis-cli INCR "swarm:${TASK_ID}:metrics:deliverable_failures" >/dev/null
1217
+
1218
+ # Override all Loop 3 confidence scores to 0.0 (prevent gate pass)
1219
+ for AGENT in "${LOOP3_COMPLETED_AGENTS[@]}"; do
1220
+ redis-cli DEL "swarm:${TASK_ID}:${AGENT}:result" >/dev/null
1221
+ redis-cli LPUSH "swarm:${TASK_ID}:${AGENT}:result" "0.0" >/dev/null
1222
+ echo " [Override] ${AGENT} confidence: 1.0 → 0.0 (no deliverables)"
1223
+ done
1224
+
1225
+ # Recalculate consensus (should be 0.0 now)
1226
+ LOOP3_CONSENSUS=$(./.claude/skills/redis-coordination/collect-confidence-scores.sh \
1227
+ --task-id "$TASK_ID" \
1228
+ --agent-ids "$LOOP3_COMPLETED_IDS" | tail -1)
1229
+
1230
+ echo ""
1231
+ echo "[Loop 3] Recalculated confidence after override: $LOOP3_CONSENSUS"
1232
+ echo ""
1233
+
1234
+ # Build specific feedback with missing files
1235
+ if [ -n "$MISSING_FILES_LIST" ]; then
1236
+ FEEDBACK="CRITICAL: Create these missing files: $MISSING_FILES_LIST
1237
+
1238
+ Use the Write tool for each file. Verify with 'ls -la' after each Write operation."
1239
+ else
1240
+ FEEDBACK="CRITICAL: You must create or modify files. No deliverables were produced in iteration $ITERATION."
1241
+ fi
1242
+
1243
+ # PHASE 1 (BUG #23): Accumulate feedback across iterations for learning
1244
+ # BUGFIX #22: Store feedback in Redis for next iteration (agents will be re-spawned, not woken)
1245
+ # Per P3 agent lifecycle: agents exit cleanly, orchestrator spawns fresh agents
1246
+ accumulate_feedback "$TASK_ID" "$ITERATION" "deliverable_check" "$FEEDBACK"
1247
+ echo " Reason: no_deliverables"
1248
+ echo " Priority: 40 (HIGH)"
1249
+
1250
+ continue # Next iteration (skip gate check and Loop 2)
1251
+ fi
1252
+
1253
+ echo "[Deliverable Check] ✅ Deliverables verified - proceeding to gate check"
1254
+ echo ""
1255
+
1256
+ # Gate check
1257
+ if (( $(echo "$LOOP3_CONSENSUS < $GATE" | bc -l) )); then
1258
+ echo "❌ Gate FAILED ($LOOP3_CONSENSUS < $GATE)"
1259
+ echo "Decision: RELAUNCH iteration $((ITERATION + 1))"
1260
+
1261
+ # LOG: Gate check failure
1262
+ ./.claude/skills/redis-coordination/log-event.sh \
1263
+ --task-id "$TASK_ID" \
1264
+ --event-type "gate_check" \
1265
+ --iteration "$ITERATION" \
1266
+ --details "{\"consensus\": $LOOP3_CONSENSUS, \"threshold\": $GATE, \"result\": \"FAIL\", \"decision\": \"RELAUNCH\"}" \
1267
+ --level "WARN" 2>/dev/null || true
1268
+
1269
+ # METRICS: Increment gate failure counter
1270
+ redis-cli INCR "swarm:${TASK_ID}:metrics:gate_failures" >/dev/null
1271
+
1272
+ # PHASE 1 (BUG #23): Accumulate feedback across iterations for learning
1273
+ # BUGFIX #22: Store feedback in Redis for next iteration (agents will be re-spawned, not woken)
1274
+ # Per P3 agent lifecycle: agents exit cleanly, orchestrator spawns fresh agents
1275
+ FEEDBACK_MSG="Improve confidence from $LOOP3_CONSENSUS to >$GATE"
1276
+ accumulate_feedback "$TASK_ID" "$ITERATION" "gate_check" "$FEEDBACK_MSG"
1277
+ echo " Reason: gate_failed"
1278
+ echo " Priority: 30 (MEDIUM)"
1279
+
1280
+ continue # Next iteration
1281
+ fi
1282
+
1283
+ echo "✅ Gate PASSED ($LOOP3_CONSENSUS >= $GATE)"
1284
+
1285
+ # LOG: Gate check success
1286
+ ./.claude/skills/redis-coordination/log-event.sh \
1287
+ --task-id "$TASK_ID" \
1288
+ --event-type "gate_check" \
1289
+ --iteration "$ITERATION" \
1290
+ --details "{\"consensus\": $LOOP3_CONSENSUS, \"threshold\": $GATE, \"result\": \"PASS\"}" \
1291
+ --level "INFO" 2>/dev/null || true
1292
+
1293
+ echo ""
1294
+
1295
+ # Signal Loop 2 validators that gate has passed (they can start work)
1296
+ GATE_PASS_KEY="swarm:${TASK_ID}:gate-passed"
1297
+ redis-cli lpush "$GATE_PASS_KEY" "{\"iteration\": $ITERATION, \"loop3_confidence\": $LOOP3_CONSENSUS}" > /dev/null
1298
+ echo "[Loop 3] Gate pass signal sent to Loop 2 validators"
1299
+ echo ""
1300
+
1301
+ # Step 3: Build Loop 2 validator context (v2.10.0 - bidirectional JSON)
1302
+ # Reuse safe array variables from Loop 3
1303
+ LOOP2_VALIDATOR_CONTEXT=$(jq -n \
1304
+ --arg task "Loop 2 validation for iteration $ITERATION_NUM" \
1305
+ --arg epicGoal "$EPIC_GOAL" \
1306
+ --arg phaseId "${PHASE_ID:-}" \
1307
+ --argjson deliverables "$SAFE_DELIVERABLES" \
1308
+ --argjson acceptanceCriteria "$SAFE_ACCEPTANCE" \
1309
+ --arg directory "${DIRECTORY:-}" \
1310
+ --arg taskId "$TASK_ID" \
1311
+ --arg iteration "$ITERATION_NUM" \
1312
+ --argjson validationTasks '["Verify all deliverable files exist in correct directory", "Check files contain actual implementation (not placeholders)", "Validate against acceptance criteria", "Provide structured feedback (critical/warnings/suggestions)", "Report confidence score based on deliverable completeness"]' \
1313
+ '{
1314
+ loop: "loop2",
1315
+ iteration: ($iteration | tonumber),
1316
+ task: $task,
1317
+ epicGoal: $epicGoal,
1318
+ phaseId: (if $phaseId == "" then null else $phaseId end),
1319
+ deliverables: $deliverables,
1320
+ directory: (if $directory == "" then null else $directory end),
1321
+ acceptanceCriteria: $acceptanceCriteria,
1322
+ validationTasks: $validationTasks,
1323
+ taskId: $taskId
1324
+ }')
1325
+
1326
+ # Validate JSON was built successfully
1327
+ if ! echo "$LOOP2_VALIDATOR_CONTEXT" | jq empty >/dev/null 2>&1; then
1328
+ echo "[ERROR] Failed to build Loop 2 JSON context"
1329
+ exit 1
1330
+ fi
1331
+
1332
+ echo "[Loop 2] ✅ Validator JSON context built successfully"
1333
+ echo ""
1334
+
1335
+ # Step 4: Spawn Loop 2 validators using skill-based output processing (parallel execution)
1336
+ echo "[Loop 2] Using skill-based output processing (parallel execution)"
1337
+ IFS=',' read -ra VALIDATORS <<< "$LOOP2_AGENTS"
1338
+
1339
+ # Track instance counts to generate unique validator IDs for duplicate validator types
1340
+ declare -A VALIDATOR_INSTANCE_COUNTS
1341
+ declare -A VALIDATOR_IDS # Map from array index to unique validator ID
1342
+
1343
+ # Pre-calculate unique validator IDs
1344
+ for i in "${!VALIDATORS[@]}"; do
1345
+ VALIDATOR="${VALIDATORS[$i]}"
1346
+
1347
+ # Increment instance counter for this validator type
1348
+ VALIDATOR_INSTANCE_COUNTS["$VALIDATOR"]=$((${VALIDATOR_INSTANCE_COUNTS["$VALIDATOR"]:-0} + 1))
1349
+ INSTANCE_NUM="${VALIDATOR_INSTANCE_COUNTS["$VALIDATOR"]}"
1350
+
1351
+ # Generate unique validator ID: validator-type-iteration-instance
1352
+ UNIQUE_VALIDATOR_ID="${VALIDATOR}-${ITERATION}-${INSTANCE_NUM}"
1353
+ VALIDATOR_IDS["$i"]="$UNIQUE_VALIDATOR_ID"
1354
+
1355
+ echo " [Instance Tracking] ${VALIDATOR} #${INSTANCE_NUM} → ${UNIQUE_VALIDATOR_ID}"
1356
+ done
1357
+
1358
+ # Store Loop 2 input context in Redis (v2.10.0 - bidirectional JSON)
1359
+ for i in "${!VALIDATORS[@]}"; do
1360
+ UNIQUE_VALIDATOR_ID="${VALIDATOR_IDS[$i]}"
1361
+
1362
+ # Store input context
1363
+ redis-cli SETEX "cfn_loop:task:${TASK_ID}:loop2:input:${UNIQUE_VALIDATOR_ID}" 86400 "$LOOP2_VALIDATOR_CONTEXT" >/dev/null 2>&1
1364
+
1365
+ # Log to message history
1366
+ MESSAGE_LOG=$(jq -n \
1367
+ --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
1368
+ --arg direction "input" \
1369
+ --arg loop "loop2" \
1370
+ --arg agent_id "$UNIQUE_VALIDATOR_ID" \
1371
+ --argjson context "$LOOP2_VALIDATOR_CONTEXT" \
1372
+ '{
1373
+ timestamp: $timestamp,
1374
+ direction: $direction,
1375
+ loop: $loop,
1376
+ agent_id: $agent_id,
1377
+ context: $context
1378
+ }')
1379
+ redis-cli LPUSH "cfn_loop:task:${TASK_ID}:messages" "$MESSAGE_LOG" >/dev/null 2>&1
1380
+ done
1381
+
1382
+ echo " ✅ Stored input context in Redis for ${#VALIDATORS[@]} validators"
1383
+ echo ""
1384
+
1385
+ # Step 3a: Spawn all validators in parallel using skill
1386
+ echo "[Loop 2] Spawning validators in parallel..."
1387
+ declare -A VALIDATOR_PIDS # Map from validator ID to background PID
1388
+ declare -A VALIDATOR_OUTPUT_FILES # Map from validator ID to temp output file
1389
+
1390
+ LOOP2_TOTAL=${#VALIDATORS[@]}
1391
+ LOOP2_REQUIRED=$(calculate_quorum "$MIN_QUORUM_LOOP2" "$LOOP2_TOTAL")
1392
+
1393
+ echo "[Loop 2] Quorum: $LOOP2_REQUIRED/$LOOP2_TOTAL validators required"
1394
+ echo ""
1395
+
1396
+ for i in "${!VALIDATORS[@]}"; do
1397
+ VALIDATOR="${VALIDATORS[$i]}"
1398
+ UNIQUE_VALIDATOR_ID="${VALIDATOR_IDS[$i]}"
1399
+
1400
+ # Get agent-specific timeout (use base validator type, not unique ID)
1401
+ AGENT_TIMEOUT=$(get_agent_timeout "$VALIDATOR" "$TASK_ID")
1402
+
1403
+ # Create temp output file for this validator
1404
+ OUTPUT_FILE="/tmp/loop2-${TASK_ID}-${UNIQUE_VALIDATOR_ID}.json"
1405
+ VALIDATOR_OUTPUT_FILES["$UNIQUE_VALIDATOR_ID"]="$OUTPUT_FILE"
1406
+
1407
+ echo " Spawning: $VALIDATOR (ID: $UNIQUE_VALIDATOR_ID, timeout: ${AGENT_TIMEOUT}s)"
1408
+
1409
+ # Execute skill in background - captures agent output and extracts structured data
1410
+ (
1411
+ # METRICS: Agent latency start
1412
+ AGENT_START=$(date +%s%N | cut -b1-13)
1413
+
1414
+ # Execute skill to spawn validator and extract feedback (BUG #20 FIX - inject detailed context)
1415
+ SKILL_RESULT=$(./.claude/skills/loop2-output-processing/execute-and-extract.sh \
1416
+ --agent-type "$VALIDATOR" \
1417
+ --task-id "$TASK_ID" \
1418
+ --agent-id "$UNIQUE_VALIDATOR_ID" \
1419
+ --context "$LOOP2_VALIDATOR_CONTEXT" \
1420
+ --iteration "$ITERATION" \
1421
+ --timeout "$AGENT_TIMEOUT" 2>&1)
1422
+
1423
+ # METRICS: Agent latency end
1424
+ AGENT_END=$(date +%s%N | cut -b1-13)
1425
+ LATENCY=$((AGENT_END - AGENT_START))
1426
+
1427
+ # Inject latency into result JSON
1428
+ SKILL_RESULT_WITH_LATENCY=$(echo "$SKILL_RESULT" | jq --arg latency "$LATENCY" '. + {latency_ms: ($latency | tonumber)}')
1429
+
1430
+ # Write result to temp file
1431
+ echo "$SKILL_RESULT_WITH_LATENCY" > "$OUTPUT_FILE"
1432
+
1433
+ # Also push to Redis for compatibility with existing tools (legacy key)
1434
+ echo "$SKILL_RESULT_WITH_LATENCY" | redis-cli -x LPUSH "swarm:${TASK_ID}:${UNIQUE_VALIDATOR_ID}:result" >/dev/null
1435
+
1436
+ # Store Loop 2 output context in Redis (v2.10.0 - bidirectional JSON)
1437
+ redis-cli SETEX "cfn_loop:task:${TASK_ID}:loop2:output:${UNIQUE_VALIDATOR_ID}" 86400 "$SKILL_RESULT_WITH_LATENCY" >/dev/null 2>&1
1438
+
1439
+ # Log to message history
1440
+ MESSAGE_LOG=$(jq -n \
1441
+ --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
1442
+ --arg direction "output" \
1443
+ --arg loop "loop2" \
1444
+ --arg agent_id "$UNIQUE_VALIDATOR_ID" \
1445
+ --argjson output "$SKILL_RESULT_WITH_LATENCY" \
1446
+ '{
1447
+ timestamp: $timestamp,
1448
+ direction: $direction,
1449
+ loop: $loop,
1450
+ agent_id: $agent_id,
1451
+ output: $output
1452
+ }')
1453
+ redis-cli LPUSH "cfn_loop:task:${TASK_ID}:messages" "$MESSAGE_LOG" >/dev/null 2>&1
1454
+
1455
+ # Signal completion
1456
+ redis-cli LPUSH "swarm:${TASK_ID}:${UNIQUE_VALIDATOR_ID}:done" "complete" >/dev/null
1457
+ ) &
1458
+
1459
+ # Track background PID
1460
+ VALIDATOR_PIDS["$UNIQUE_VALIDATOR_ID"]=$!
1461
+ echo " ✅ Spawned $UNIQUE_VALIDATOR_ID (PID: ${VALIDATOR_PIDS[$UNIQUE_VALIDATOR_ID]})"
1462
+ done
1463
+
1464
+ echo ""
1465
+ echo "[Loop 2] All validators spawned, waiting for completion..."
1466
+ echo ""
1467
+
1468
+ # Step 3b: Wait for all validators to complete and collect results
1469
+ LOOP2_COMPLETED_AGENTS=()
1470
+ LOOP2_FAILED_AGENTS=()
1471
+ declare -A LOOP2_CONFIDENCES # Map from validator ID to confidence score
1472
+
1473
+ for i in "${!VALIDATORS[@]}"; do
1474
+ VALIDATOR="${VALIDATORS[$i]}"
1475
+ UNIQUE_VALIDATOR_ID="${VALIDATOR_IDS[$i]}"
1476
+ VALIDATOR_PID="${VALIDATOR_PIDS[$UNIQUE_VALIDATOR_ID]}"
1477
+ OUTPUT_FILE="${VALIDATOR_OUTPUT_FILES[$UNIQUE_VALIDATOR_ID]}"
1478
+
1479
+ echo " Waiting for $UNIQUE_VALIDATOR_ID (PID: $VALIDATOR_PID)..."
1480
+
1481
+ # Wait for background process to complete
1482
+ if wait "$VALIDATOR_PID" 2>/dev/null; then
1483
+ # Process completed successfully, read result from temp file
1484
+ if [ -f "$OUTPUT_FILE" ] && [ -s "$OUTPUT_FILE" ]; then
1485
+ SKILL_RESULT=$(cat "$OUTPUT_FILE")
1486
+
1487
+ # Validate JSON structure
1488
+ if echo "$SKILL_RESULT" | jq empty 2>/dev/null; then
1489
+ # Extract confidence score
1490
+ CONFIDENCE=$(echo "$SKILL_RESULT" | jq -r '.confidence // 0.0')
1491
+ CONFIDENCE_SOURCE=$(echo "$SKILL_RESULT" | jq -r '.confidence_source // "unknown"')
1492
+ FEEDBACK=$(echo "$SKILL_RESULT" | jq -r '.feedback // {}')
1493
+ LATENCY=$(echo "$SKILL_RESULT" | jq -r '.latency_ms // 0')
1494
+
1495
+ # Store confidence for consensus calculation
1496
+ LOOP2_CONFIDENCES["$UNIQUE_VALIDATOR_ID"]="$CONFIDENCE"
1497
+
1498
+ # Store latency metric
1499
+ METRIC=$(jq -nc \
1500
+ --arg agent "$UNIQUE_VALIDATOR_ID" \
1501
+ --arg latency "$LATENCY" \
1502
+ --arg loop "loop2" \
1503
+ --arg iteration "$ITERATION" \
1504
+ '{agent: $agent, latency_ms: ($latency | tonumber), loop: $loop, iteration: ($iteration | tonumber)}')
1505
+ echo "$METRIC" | redis-cli -x LPUSH "swarm:${TASK_ID}:metrics:agent_latency" >/dev/null
1506
+
1507
+ # Count feedback items
1508
+ CRITICAL_COUNT=$(echo "$FEEDBACK" | jq -r '.critical | length')
1509
+ WARNINGS_COUNT=$(echo "$FEEDBACK" | jq -r '.warnings | length')
1510
+ SUGGESTIONS_COUNT=$(echo "$FEEDBACK" | jq -r '.suggestions | length')
1511
+
1512
+ echo " ✅ $UNIQUE_VALIDATOR_ID complete (${LATENCY}ms, confidence: $CONFIDENCE [$CONFIDENCE_SOURCE], feedback: ${CRITICAL_COUNT}C/${WARNINGS_COUNT}W/${SUGGESTIONS_COUNT}S)"
1513
+
1514
+ LOOP2_COMPLETED_AGENTS+=("$UNIQUE_VALIDATOR_ID")
1515
+ else
1516
+ echo " ⚠️ $UNIQUE_VALIDATOR_ID returned invalid JSON, treating as failed"
1517
+ LOOP2_FAILED_AGENTS+=("$VALIDATOR")
1518
+
1519
+ # METRICS: Increment timeout counter
1520
+ redis-cli INCR "swarm:${TASK_ID}:metrics:timeout_count" >/dev/null
1521
+ fi
1522
+ else
1523
+ echo " ⚠️ $UNIQUE_VALIDATOR_ID completed but no output file found"
1524
+ LOOP2_FAILED_AGENTS+=("$VALIDATOR")
1525
+
1526
+ # METRICS: Increment timeout counter
1527
+ redis-cli INCR "swarm:${TASK_ID}:metrics:timeout_count" >/dev/null
1528
+ fi
1529
+ else
1530
+ echo " ❌ $UNIQUE_VALIDATOR_ID failed (process exited with error)"
1531
+ LOOP2_FAILED_AGENTS+=("$VALIDATOR")
1532
+
1533
+ # METRICS: Increment timeout counter
1534
+ redis-cli INCR "swarm:${TASK_ID}:metrics:timeout_count" >/dev/null
1535
+ fi
1536
+
1537
+ # Cleanup temp file
1538
+ rm -f "$OUTPUT_FILE"
1539
+ done
1540
+
1541
+ echo ""
1542
+
1543
+ # Validate quorum
1544
+ if [ ${#LOOP2_COMPLETED_AGENTS[@]} -ge "$LOOP2_REQUIRED" ]; then
1545
+ echo "[Loop 2] ✅ Quorum met: ${#LOOP2_COMPLETED_AGENTS[@]}/$LOOP2_REQUIRED validators completed"
1546
+ if [ ${#LOOP2_FAILED_AGENTS[@]} -gt 0 ]; then
1547
+ echo "[Loop 2] ⚠️ Failed validators (continuing with quorum): ${LOOP2_FAILED_AGENTS[*]}"
1548
+
1549
+ # METRICS: Increment quorum fallback counter
1550
+ redis-cli INCR "swarm:${TASK_ID}:metrics:quorum_fallback" >/dev/null
1551
+ fi
1552
+ else
1553
+ echo "[Loop 2] ❌ Quorum FAILED: ${#LOOP2_COMPLETED_AGENTS[@]} < $LOOP2_REQUIRED"
1554
+ echo "[Loop 2] Failed validators: ${LOOP2_FAILED_AGENTS[*]}"
1555
+ exit 1
1556
+ fi
1557
+ echo ""
1558
+
1559
+ # Step 3c: Calculate Loop 2 consensus from extracted confidence scores
1560
+ echo "[Loop 2] Calculating consensus from ${#LOOP2_COMPLETED_AGENTS[@]} validators..."
1561
+
1562
+ # Calculate average confidence from completed validators
1563
+ LOOP2_TOTAL_CONFIDENCE=0
1564
+ LOOP2_CONFIDENCE_COUNT=0
1565
+
1566
+ for VALIDATOR_ID in "${LOOP2_COMPLETED_AGENTS[@]}"; do
1567
+ CONFIDENCE="${LOOP2_CONFIDENCES[$VALIDATOR_ID]}"
1568
+ if [ -n "$CONFIDENCE" ] && [ "$CONFIDENCE" != "null" ]; then
1569
+ LOOP2_TOTAL_CONFIDENCE=$(echo "$LOOP2_TOTAL_CONFIDENCE + $CONFIDENCE" | bc -l)
1570
+ LOOP2_CONFIDENCE_COUNT=$((LOOP2_CONFIDENCE_COUNT + 1))
1571
+ fi
1572
+ done
1573
+
1574
+ if [ "$LOOP2_CONFIDENCE_COUNT" -gt 0 ]; then
1575
+ LOOP2_CONSENSUS=$(echo "scale=2; $LOOP2_TOTAL_CONFIDENCE / $LOOP2_CONFIDENCE_COUNT" | bc -l)
1576
+ else
1577
+ echo "⚠️ No valid confidence scores found, defaulting to 0.0"
1578
+ LOOP2_CONSENSUS=0.0
1579
+ fi
1580
+
1581
+ echo "[Loop 2] Average consensus: $LOOP2_CONSENSUS (from ${LOOP2_CONFIDENCE_COUNT} validators)"
1582
+
1583
+ # METRICS: Store Loop 2 consensus score
1584
+ LOOP2_METRIC=$(jq -nc \
1585
+ --arg consensus "$LOOP2_CONSENSUS" \
1586
+ --arg iteration "$ITERATION" \
1587
+ '{consensus: ($consensus | tonumber), iteration: ($iteration | tonumber)}')
1588
+ echo "$LOOP2_METRIC" | redis-cli -x LPUSH "swarm:${TASK_ID}:metrics:loop2_consensus" >/dev/null
1589
+
1590
+ # Display consensus status
1591
+ echo ""
1592
+ if (( $(echo "$LOOP2_CONSENSUS >= $CONSENSUS" | bc -l) )); then
1593
+ echo "✅ CONSENSUS REACHED ($LOOP2_CONSENSUS >= $CONSENSUS)"
1594
+ else
1595
+ echo "⚠️ CONSENSUS NOT REACHED ($LOOP2_CONSENSUS < $CONSENSUS)"
1596
+ fi
1597
+ echo ""
1598
+
1599
+ # [BUG #11 FIX] Product Owner decision via output parsing (not Redis wait)
1600
+ echo "[Product Owner] Spawning Product Owner for strategic decision..."
1601
+
1602
+ # BUG #19 FIX: Define PO_UNIQUE_ID BEFORE building context string
1603
+ PO_UNIQUE_ID="${PRODUCT_OWNER}-${ITERATION}-decision"
1604
+
1605
+ # Build Product Owner JSON context (v2.10.0 - bidirectional JSON)
1606
+ PO_CONTEXT=$(jq -n \
1607
+ --arg task "Product Owner strategic decision for iteration $ITERATION_NUM" \
1608
+ --arg epicGoal "$EPIC_GOAL" \
1609
+ --arg phaseId "${PHASE_ID:-}" \
1610
+ --argjson deliverables "$SAFE_DELIVERABLES" \
1611
+ --argjson acceptanceCriteria "$SAFE_ACCEPTANCE" \
1612
+ --arg loop2Consensus "$LOOP2_CONSENSUS" \
1613
+ --arg consensusThreshold "$CONSENSUS" \
1614
+ --arg taskId "$TASK_ID" \
1615
+ --arg agentId "$PO_UNIQUE_ID" \
1616
+ --arg iteration "$ITERATION_NUM" \
1617
+ --arg maxIterations "$MAX_ITERATIONS" \
1618
+ --argjson decisions '["PROCEED", "ITERATE", "ABORT", "DEFER_AND_PROCEED"]' \
1619
+ --argjson framework '[{"decision": "PROCEED", "condition": "Consensus >= threshold AND deliverables verified"}, {"decision": "ITERATE", "condition": "Consensus < threshold AND iteration < max"}, {"decision": "ABORT", "condition": "Max iterations reached without consensus"}, {"decision": "DEFER_AND_PROCEED", "condition": "In-scope work complete, out-of-scope deferred"}]' \
1620
+ '{
1621
+ loop: "product-owner",
1622
+ iteration: ($iteration | tonumber),
1623
+ task: $task,
1624
+ epicGoal: $epicGoal,
1625
+ phaseId: (if $phaseId == "" then null else $phaseId end),
1626
+ deliverables: $deliverables,
1627
+ acceptanceCriteria: $acceptanceCriteria,
1628
+ loop2Consensus: ($loop2Consensus | tonumber),
1629
+ consensusThreshold: ($consensusThreshold | tonumber),
1630
+ maxIterations: ($maxIterations | tonumber),
1631
+ decisions: $decisions,
1632
+ framework: $framework,
1633
+ taskId: $taskId,
1634
+ agentId: $agentId
1635
+ }')
1636
+
1637
+ # Validate JSON was built successfully
1638
+ if ! echo "$PO_CONTEXT" | jq empty >/dev/null 2>&1; then
1639
+ echo "[ERROR] Failed to build Product Owner JSON context"
1640
+ exit 1
1641
+ fi
1642
+
1643
+ echo " ✅ Product Owner JSON context built successfully"
1644
+
1645
+ # Store Product Owner input context in Redis (v2.10.0 - bidirectional JSON)
1646
+ redis-cli SETEX "cfn_loop:task:${TASK_ID}:product-owner:input:${PO_UNIQUE_ID}" 86400 "$PO_CONTEXT" >/dev/null 2>&1
1647
+
1648
+ # Log to message history
1649
+ MESSAGE_LOG=$(jq -n \
1650
+ --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
1651
+ --arg direction "input" \
1652
+ --arg loop "product-owner" \
1653
+ --arg agent_id "$PO_UNIQUE_ID" \
1654
+ --argjson context "$PO_CONTEXT" \
1655
+ '{
1656
+ timestamp: $timestamp,
1657
+ direction: $direction,
1658
+ loop: $loop,
1659
+ agent_id: $agent_id,
1660
+ context: $context
1661
+ }')
1662
+ redis-cli LPUSH "cfn_loop:task:${TASK_ID}:messages" "$MESSAGE_LOG" >/dev/null 2>&1
1663
+
1664
+ echo " ✅ Stored Product Owner input context in Redis"
1665
+
1666
+ # Spawn Product Owner and capture output
1667
+ PO_TIMEOUT=$(get_agent_timeout "$PRODUCT_OWNER" "$TASK_ID")
1668
+ echo "[Product Owner] Spawning with timeout: ${PO_TIMEOUT}s"
1669
+
1670
+ PO_OUTPUT=$(timeout "$PO_TIMEOUT" npx claude-flow-novice agent "$PRODUCT_OWNER" \
1671
+ --task-id "$TASK_ID" \
1672
+ --agent-id "$PO_UNIQUE_ID" \
1673
+ --context "$PO_CONTEXT" 2>&1 || true)
1674
+
1675
+ # Parse structured decision JSON from Redis (created by execute-product-owner-decision.sh)
1676
+ echo "[Product Owner] Retrieving structured decision from Redis..."
1677
+ DECISION=$(redis-cli lindex "swarm:${TASK_ID}:${PO_UNIQUE_ID}:decision" 0)
1678
+
1679
+ if [ -z "$DECISION" ] || [ "$DECISION" = "(nil)" ]; then
1680
+ echo "❌ ERROR: Could not retrieve Product Owner decision from Redis"
1681
+ echo "Expected key: swarm:${TASK_ID}:${PO_UNIQUE_ID}:decision"
1682
+ echo "Product Owner output:"
1683
+ echo "$PO_OUTPUT"
1684
+ exit 1
1685
+ fi
1686
+
1687
+ # Extract fields from structured JSON
1688
+ DECISION_TYPE=$(echo "$DECISION" | jq -r '.decision')
1689
+ DECISION_REASONING=$(echo "$DECISION" | jq -r '.reasoning')
1690
+ DECISION_CONFIDENCE=$(echo "$DECISION" | jq -r '.confidence')
1691
+ IN_SCOPE_CONSENSUS=$(echo "$DECISION" | jq -r '.scope_analysis.in_scope_consensus // 0')
1692
+ BACKLOG_COUNT=$(echo "$DECISION" | jq -r '.backlog_items | length')
1693
+
1694
+ if [ -z "$DECISION_TYPE" ] || [ "$DECISION_TYPE" = "null" ]; then
1695
+ echo "❌ ERROR: Invalid Product Owner decision JSON"
1696
+ echo "Received: $DECISION"
1697
+ exit 1
1698
+ fi
1699
+
1700
+ echo " Decision Type: $DECISION_TYPE"
1701
+ echo " Confidence: $DECISION_CONFIDENCE"
1702
+ echo " In-Scope Consensus: $IN_SCOPE_CONSENSUS"
1703
+ echo " Backlog Items: $BACKLOG_COUNT"
1704
+ echo ""
1705
+
1706
+ # Store Product Owner output context in Redis (v2.10.0 - bidirectional JSON)
1707
+ redis-cli SETEX "cfn_loop:task:${TASK_ID}:product-owner:output:${PO_UNIQUE_ID}" 86400 "$DECISION" >/dev/null 2>&1
1708
+
1709
+ # Log to message history
1710
+ MESSAGE_LOG=$(jq -n \
1711
+ --arg timestamp "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
1712
+ --arg direction "output" \
1713
+ --arg loop "product-owner" \
1714
+ --arg agent_id "$PO_UNIQUE_ID" \
1715
+ --argjson output "$DECISION" \
1716
+ '{
1717
+ timestamp: $timestamp,
1718
+ direction: $direction,
1719
+ loop: $loop,
1720
+ agent_id: $agent_id,
1721
+ output: $output
1722
+ }')
1723
+ redis-cli LPUSH "cfn_loop:task:${TASK_ID}:messages" "$MESSAGE_LOG" >/dev/null 2>&1
1724
+
1725
+ echo " ✅ Stored Product Owner output context in Redis"
1726
+
1727
+ # LOG: Product Owner decision
1728
+ ./.claude/skills/redis-coordination/log-event.sh \
1729
+ --task-id "$TASK_ID" \
1730
+ --event-type "po_decision" \
1731
+ --agent-id "$PO_UNIQUE_ID" \
1732
+ --iteration "$ITERATION" \
1733
+ --details "$DECISION" \
1734
+ --level "INFO" 2>/dev/null || true
1735
+
1736
+ echo "[Product Owner] Decision: $DECISION_TYPE"
1737
+ echo ""
1738
+
1739
+ # Handle Product Owner decision
1740
+ if [ "$DECISION_TYPE" = "PROCEED" ] || [ "$DECISION_TYPE" = "DEFER_AND_PROCEED" ]; then
1741
+ # Handle backlog items if DEFER_AND_PROCEED
1742
+ if [ "$DECISION_TYPE" = "DEFER_AND_PROCEED" ]; then
1743
+ echo "📋 Product Owner Decision: DEFER_AND_PROCEED"
1744
+ echo " In-scope work complete (consensus: $IN_SCOPE_CONSENSUS)"
1745
+ echo " Deferred $BACKLOG_COUNT out-of-scope items to backlog"
1746
+ echo ""
1747
+ fi
1748
+
1749
+ # DELIVERABLE VERIFICATION (Sprint 8 - prevent "consensus on vapor")
1750
+ echo "[Deliverable Verification] Checking success criteria..."
1751
+
1752
+ SUCCESS_CRITERIA_RAW=$(redis-cli GET "swarm:${TASK_ID}:success-criteria" 2>/dev/null)
1753
+ if [ -n "$SUCCESS_CRITERIA_RAW" ]; then
1754
+ # Check if task description includes file/deliverable keywords
1755
+ TASK_DESC=$(redis-cli GET "swarm:${TASK_ID}:task" 2>/dev/null)
1756
+
1757
+ if echo "$TASK_DESC" | grep -qiE "create|build|implement|generate|file|component|module|test"; then
1758
+ echo "[Deliverable Verification] Task involves implementation - checking for file changes..."
1759
+
1760
+ # Count modified/created files since orchestrator started
1761
+ FILES_CREATED=$(git status --short 2>/dev/null | grep -E "^(A|M|\\?\\?)" | wc -l)
1762
+
1763
+ if [ "$FILES_CREATED" -eq 0 ]; then
1764
+ echo "⚠️ DELIVERABLE VERIFICATION FAILED"
1765
+ echo " Task requires implementation but no files were created/modified"
1766
+ echo " Consensus reached on plans without actual deliverables"
1767
+ echo ""
1768
+ echo " Options:"
1769
+ echo " 1. Force ITERATE to create actual implementation"
1770
+ echo " 2. Override verification (--skip-deliverable-check flag)"
1771
+ echo " 3. Manual intervention to verify work was done"
1772
+ echo ""
1773
+ echo " Recommendation: Force ITERATE with explicit deliverable requirement"
1774
+
1775
+ # Store verification failure
1776
+ redis-cli SET "swarm:${TASK_ID}:deliverable_verification" "failed" EX 86400 >/dev/null
1777
+
1778
+ # Optional: Force ITERATE (commented for now - requires flag)
1779
+ # echo "[Forced Override] Changing PROCEED → ITERATE due to missing deliverables"
1780
+ # DECISION_TYPE="ITERATE"
1781
+ # DECISION_REASONING="No deliverables created despite implementation task"
1782
+ else
1783
+ echo "✅ Deliverable verification passed ($FILES_CREATED files created/modified)"
1784
+ redis-cli SET "swarm:${TASK_ID}:deliverable_verification" "passed:$FILES_CREATED" EX 86400 >/dev/null
1785
+ fi
1786
+ else
1787
+ echo "[Deliverable Verification] Task is analysis/planning - skipping file check"
1788
+ fi
1789
+ fi
1790
+
1791
+ echo "🎉 CFN Loop Complete (Product Owner: PROCEED)"
1792
+ echo "Final Consensus: $LOOP2_CONSENSUS (Iteration $ITERATION)"
1793
+
1794
+ # METRICS: Iteration end timestamp and duration
1795
+ ITERATION_END=$(date +%s%N | cut -b1-13)
1796
+ ITERATION_DURATION=$((ITERATION_END - ITERATION_START))
1797
+
1798
+ # Store final iteration duration metric
1799
+ DURATION_METRIC=$(jq -nc \
1800
+ --arg duration "$ITERATION_DURATION" \
1801
+ --arg iteration "$ITERATION" \
1802
+ '{duration_ms: ($duration | tonumber), iteration: ($iteration | tonumber)}')
1803
+ echo "$DURATION_METRIC" | redis-cli -x LPUSH "swarm:${TASK_ID}:metrics:iteration_duration" >/dev/null
1804
+
1805
+ # BUGFIX #22: Agents have already exited (P3 clean-exit pattern), no wake needed
1806
+ # The task is complete, agents were already cleaned up when they reported confidence
1807
+ echo "[Coordinator] Task complete (PROCEED decision)"
1808
+ echo " All agents have already exited cleanly per P3 lifecycle"
1809
+
1810
+ # Use general complete-swarm primitive
1811
+ ./.claude/skills/redis-coordination/complete-swarm.sh \
1812
+ --swarm-id "$SWARM_ID" \
1813
+ --final-metric "final_consensus=$LOOP2_CONSENSUS" \
1814
+ --final-metric "total_iterations=$ITERATION" > /dev/null
1815
+
1816
+ exit 0
1817
+
1818
+ elif [ "$DECISION_TYPE" = "ITERATE" ]; then
1819
+ echo "⚠️ Product Owner Decision: ITERATE (improve quality)"
1820
+
1821
+ # METRICS: Iteration end timestamp and duration
1822
+ ITERATION_END=$(date +%s%N | cut -b1-13)
1823
+ ITERATION_DURATION=$((ITERATION_END - ITERATION_START))
1824
+
1825
+ # Store iteration duration metric
1826
+ DURATION_METRIC=$(jq -nc \
1827
+ --arg duration "$ITERATION_DURATION" \
1828
+ --arg iteration "$ITERATION" \
1829
+ '{duration_ms: ($duration | tonumber), iteration: ($iteration | tonumber)}')
1830
+ echo "$DURATION_METRIC" | redis-cli -x LPUSH "swarm:${TASK_ID}:metrics:iteration_duration" >/dev/null
1831
+
1832
+ # Check max iterations
1833
+ if [ $ITERATION -eq $MAX_ITERATIONS ]; then
1834
+ echo "❌ Maximum iterations ($MAX_ITERATIONS) reached - cannot iterate further"
1835
+ echo " Product Owner wanted ITERATE but max iterations exhausted"
1836
+ exit 1
1837
+ fi
1838
+
1839
+ # PHASE 1 (BUG #23): Accumulate feedback across iterations for learning
1840
+ # BUGFIX #22: Store feedback in Redis for next iteration (agents will be re-spawned, not woken)
1841
+ # Per P3 agent lifecycle: agents exit cleanly, orchestrator spawns fresh agents for next iteration
1842
+ echo "[Coordinator] Storing feedback for iteration $((ITERATION + 1))..."
1843
+
1844
+ FEEDBACK_MSG="Product Owner decision: ITERATE - Improve consensus from $LOOP2_CONSENSUS to >=$CONSENSUS"
1845
+ accumulate_feedback "$TASK_ID" "$ITERATION" "product_owner_iterate" "$FEEDBACK_MSG"
1846
+
1847
+ echo " Reason: cfn_loop_iteration (Product Owner ITERATE decision)"
1848
+ echo " Priority: 30 (MEDIUM - Loop 3), 10 (HIGH - Loop 2)"
1849
+ echo ""
1850
+
1851
+ elif [ "$DECISION_TYPE" = "ABORT" ]; then
1852
+ echo "❌ Product Owner Decision: ABORT (scope too large or out of scope)"
1853
+ echo " Consensus: $LOOP2_CONSENSUS, Iteration: $ITERATION"
1854
+ exit 1
1855
+
1856
+ else
1857
+ echo "❌ ERROR: Unknown Product Owner decision: $DECISION_TYPE"
1858
+ echo " Expected: PROCEED, DEFER_AND_PROCEED, ITERATE, or ABORT"
1859
+ exit 1
1860
+ fi
1861
+ done
1862
+
1863
+ echo "❌ CFN Loop failed after $MAX_ITERATIONS iterations"
1864
+ exit 1