claude-flow-novice 2.15.2 → 2.15.4

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 (533) hide show
  1. package/.claude/cfn-extras/skills/advanced-features/cfn-agent-swap/recommend-swap.sh +59 -59
  2. package/.claude/cfn-extras/skills/analytics/cfn-improvement-recommender/recommend-improvements.sh +91 -91
  3. package/.claude/cfn-extras/skills/analytics/cfn-pattern-extraction/extract-patterns.sh +79 -79
  4. package/.claude/cfn-extras/skills/analytics/cfn-retrospective-report/generate-report.sh +100 -100
  5. package/.claude/cfn-extras/skills/analytics/cfn-telemetry/start-telemetry.sh +110 -110
  6. package/.claude/cfn-extras/skills/deprecated/cfn-ace-system/add-bullet.sh +145 -145
  7. package/.claude/cfn-extras/skills/deprecated/cfn-ace-system/log-merge.sh +67 -67
  8. package/.claude/cfn-extras/skills/deprecated/cfn-ace-system/monitor-injection-performance.sh +137 -137
  9. package/.claude/cfn-extras/skills/deprecated/cfn-ace-system/optimize-injection-pipeline.sh +168 -168
  10. package/.claude/cfn-extras/skills/deprecated/cfn-ace-system/query-reflections.sh +35 -35
  11. package/.claude/cfn-extras/skills/deprecated/cfn-ace-system/store-reflection.sh +45 -45
  12. package/.claude/cfn-extras/skills/deprecated/cfn-ace-system/track-ab-test.sh +41 -41
  13. package/.claude/cfn-extras/skills/deprecated/cfn-ace-system/update-reflection.sh +41 -41
  14. package/.claude/cfn-extras/skills/deprecated/cfn-cli-setup/validate-cli-environment.sh +191 -191
  15. package/.claude/cfn-extras/skills/marketing/cfn-marketing-ad-campaigns/operations/create-campaign.sh +231 -231
  16. package/.claude/cfn-extras/skills/marketing/cfn-marketing-ad-campaigns/operations/get-campaign-performance.sh +190 -190
  17. package/.claude/cfn-extras/skills/marketing/cfn-marketing-ad-campaigns/operations/pause-campaign.sh +142 -142
  18. package/.claude/cfn-extras/skills/marketing/cfn-marketing-ad-campaigns/operations/set-budget.sh +181 -181
  19. package/.claude/cfn-extras/skills/marketing/cfn-marketing-ad-campaigns/operations/update-bid-strategy.sh +133 -133
  20. package/.claude/cfn-extras/skills/marketing/cfn-marketing-chatbot-conversations/operations/get-conversation-history.sh +121 -121
  21. package/.claude/cfn-extras/skills/marketing/cfn-marketing-chatbot-conversations/operations/qualify-lead.sh +156 -156
  22. package/.claude/cfn-extras/skills/marketing/cfn-marketing-chatbot-conversations/operations/schedule-demo.sh +181 -181
  23. package/.claude/cfn-extras/skills/marketing/cfn-marketing-chatbot-conversations/operations/send-message.sh +137 -137
  24. package/.claude/cfn-extras/skills/marketing/cfn-marketing-chatbot-conversations/operations/transfer-to-human.sh +179 -179
  25. package/.claude/cfn-extras/skills/marketing/cfn-marketing-sms-campaigns/operations/create-campaign.sh +183 -183
  26. package/.claude/cfn-extras/skills/marketing/cfn-marketing-sms-campaigns/operations/get-delivery-status.sh +139 -139
  27. package/.claude/cfn-extras/skills/marketing/cfn-marketing-sms-campaigns/operations/opt-out.sh +150 -150
  28. package/.claude/cfn-extras/skills/marketing/cfn-marketing-sms-campaigns/operations/schedule-campaign.sh +187 -187
  29. package/.claude/cfn-extras/skills/marketing/cfn-marketing-sms-campaigns/operations/send-sms.sh +181 -181
  30. package/.claude/cfn-extras/skills/ui-portal/cfn-web-portal/test-web-portal-skill.sh +50 -50
  31. package/.claude/cfn-extras/skills/ui-portal/cfn-web-portal/validate-deployment.sh +84 -84
  32. package/.claude/cfn-extras/skills/utility/cfn-environment-sanitization/sanitize-environment.sh +243 -243
  33. package/.claude/commands/cfn-loop-cli.md +16 -2
  34. package/.claude/commands/switch-api.md +31 -10
  35. package/.claude/hooks/cfn-BACKUP_USAGE.md +243 -243
  36. package/.claude/hooks/cfn-invoke-security-validation.sh +69 -69
  37. package/.claude/hooks/cfn-lint-sql-injection.sh +61 -0
  38. package/.claude/hooks/cfn-post-edit-cfn-retrospective.sh +109 -78
  39. package/.claude/hooks/cfn-post-edit.config.json +44 -44
  40. package/.claude/hooks/cfn-pre-edit-security-warning.sh +40 -0
  41. package/.claude/skills/cfn-agent-spawning/spawn-agent.sh +22 -24
  42. package/.claude/skills/cfn-docker-agent-spawning/SKILL.md +28 -4
  43. package/.claude/skills/cfn-docker-agent-spawning/spawn-agent.sh +3 -1
  44. package/.claude/skills/cfn-docker-loop-orchestration/orchestrate.sh +224 -20
  45. package/.claude/skills/cfn-hybrid-routing/check-dependencies.sh +51 -51
  46. package/.claude/skills/cfn-loop-orchestration/helpers/gate-check.sh +550 -46
  47. package/.claude/skills/cfn-loop-orchestration/helpers/parse-test-results.sh +277 -0
  48. package/.claude/skills/cfn-loop-orchestration/orchestrate.sh +184 -23
  49. package/.claude/skills/cfn-loop-orchestration/security_utils.sh +24 -0
  50. package/.claude/skills/cfn-loop-orchestration/test-iteration-context-injection.sh +366 -0
  51. package/.claude/skills/cfn-loop-validation/orchestrate-cfn-loop.sh +252 -252
  52. package/.claude/skills/cfn-redis-coordination/CENTRALIZED_REDIS_WRAPPER.md +319 -0
  53. package/.claude/skills/cfn-redis-coordination/agent-log.sh +4 -0
  54. package/.claude/skills/cfn-redis-coordination/agent-log.sh.bak +124 -0
  55. package/.claude/skills/cfn-redis-coordination/agent-recovery.sh +74 -74
  56. package/.claude/skills/cfn-redis-coordination/collect-confidence-scores.sh +30 -0
  57. package/.claude/skills/cfn-redis-coordination/get-context.sh +145 -112
  58. package/.claude/skills/cfn-redis-coordination/get-success-criteria.sh +54 -0
  59. package/.claude/skills/cfn-redis-coordination/invoke-waiting-mode.sh +3 -0
  60. package/.claude/skills/cfn-redis-coordination/redis-cli-wrapper.sh +24 -3
  61. package/.claude/skills/cfn-redis-coordination/redis-functions.sh +33 -0
  62. package/.claude/skills/cfn-redis-coordination/report-completion.sh +24 -31
  63. package/.claude/skills/cfn-redis-coordination/store-context.sh +4 -0
  64. package/.claude/skills/cfn-redis-coordination/store-success-criteria.sh +85 -0
  65. package/.claude/skills/cfn-redis-coordination/update-all-scripts.sh +67 -0
  66. package/.claude/skills/cfn-sqlite-memory/ttl-cleanup.sh +17 -25
  67. package/.claude/skills/cfn-transparency-middleware/middleware-config.sh +28 -28
  68. package/.claude/skills/cfn-transparency-middleware/performance-benchmark.sh +78 -78
  69. package/.claude/skills/cfn-transparency-middleware/test-e2e.sh +15 -0
  70. package/.claude/skills/cfn-transparency-middleware/test-integration.sh +161 -161
  71. package/.claude/skills/cfn-transparency-middleware/test-transparency-skill.sh +367 -367
  72. package/.claude/skills/cfn-transparency-middleware/tests/input-validation.sh +107 -92
  73. package/.claude/skills/cfn-transparency-middleware/wrap-agent.sh +131 -131
  74. package/README.md +116 -475
  75. package/claude-assets/agents/cfn-dev-team/README.md +103 -0
  76. package/claude-assets/agents/cfn-dev-team/architecture/goal-planner.md +1 -1
  77. package/claude-assets/agents/cfn-dev-team/coordinators/cfn-frontend-coordinator.md +77 -15
  78. package/claude-assets/agents/cfn-dev-team/coordinators/cfn-v3-coordinator.md +355 -6
  79. package/claude-assets/agents/cfn-dev-team/coordinators/consensus-builder.md +82 -1
  80. package/claude-assets/agents/cfn-dev-team/coordinators/handoff-coordinator.md +82 -1
  81. package/claude-assets/agents/cfn-dev-team/coordinators/multi-sprint-coordinator.md +77 -15
  82. package/claude-assets/agents/cfn-dev-team/dev-ops/docker-specialist.md +99 -12
  83. package/claude-assets/agents/cfn-dev-team/dev-ops/github-commit-agent.md +1 -1
  84. package/claude-assets/agents/cfn-dev-team/dev-ops/kubernetes-specialist.md +97 -0
  85. package/claude-assets/agents/cfn-dev-team/dev-ops/monitoring-specialist.md +20 -1
  86. package/claude-assets/agents/cfn-dev-team/developers/api-gateway-specialist.md +97 -0
  87. package/claude-assets/agents/cfn-dev-team/developers/backend-developer.md +110 -13
  88. package/claude-assets/agents/cfn-dev-team/developers/data/data-engineer.md +106 -15
  89. package/claude-assets/agents/cfn-dev-team/developers/database/database-architect.md +115 -11
  90. package/claude-assets/agents/cfn-dev-team/developers/frontend/mobile-dev.md +94 -7
  91. package/claude-assets/agents/cfn-dev-team/developers/frontend/react-frontend-engineer.md +87 -9
  92. package/claude-assets/agents/cfn-dev-team/developers/frontend/typescript-specialist.md +85 -7
  93. package/claude-assets/agents/cfn-dev-team/developers/frontend/ui-designer.md +160 -28
  94. package/claude-assets/agents/cfn-dev-team/developers/graphql-specialist.md +101 -19
  95. package/claude-assets/agents/cfn-dev-team/developers/rust-developer.md +108 -14
  96. package/claude-assets/agents/cfn-dev-team/reviewers/{reviewer.md → code-reviewer.md} +95 -8
  97. package/claude-assets/agents/cfn-dev-team/reviewers/quality/code-quality-validator.md +107 -7
  98. package/claude-assets/agents/cfn-dev-team/reviewers/quality/perf-analyzer.md +98 -7
  99. package/claude-assets/agents/cfn-dev-team/reviewers/quality/performance-benchmarker.md +95 -7
  100. package/claude-assets/agents/cfn-dev-team/reviewers/quality/security-specialist.md +136 -9
  101. package/claude-assets/agents/cfn-dev-team/testers/api-testing-specialist.md +108 -1
  102. package/claude-assets/agents/cfn-dev-team/testers/chaos-engineering-specialist.md +107 -13
  103. package/claude-assets/agents/cfn-dev-team/testers/contract-tester.md +737 -0
  104. package/claude-assets/agents/cfn-dev-team/testers/e2e/playwright-tester.md +1 -1
  105. package/claude-assets/agents/cfn-dev-team/testers/integration-tester.md +828 -0
  106. package/claude-assets/agents/cfn-dev-team/testers/interaction-tester.md +106 -7
  107. package/claude-assets/agents/cfn-dev-team/testers/load-testing-specialist.md +77 -0
  108. package/claude-assets/agents/cfn-dev-team/testers/mutation-testing-specialist.md +684 -0
  109. package/claude-assets/agents/cfn-dev-team/testers/playwright-tester.md +110 -1
  110. package/claude-assets/agents/cfn-dev-team/testers/tester.md +94 -7
  111. package/claude-assets/agents/cfn-dev-team/utility/code-booster.md +1 -3
  112. package/claude-assets/agents/cfn-dev-team/utility/epic-creator.md +87 -13
  113. package/claude-assets/agents/cfn-dev-team/utility/memory-leak-specialist.md +103 -7
  114. package/claude-assets/agents/cfn-dev-team/utility/researcher.md +1 -3
  115. package/claude-assets/agents/cfn-dev-team/utility/z-ai-specialist.md +94 -7
  116. package/claude-assets/agents/docker-coordinators/cfn-docker-v3-coordinator.md +46 -0
  117. package/claude-assets/agents/project-only-agents/npm-package-specialist.md +1 -1
  118. package/claude-assets/cfn-extras/skills/advanced-features/cfn-agent-swap/recommend-swap.sh +59 -59
  119. package/claude-assets/cfn-extras/skills/analytics/cfn-improvement-recommender/recommend-improvements.sh +91 -91
  120. package/claude-assets/cfn-extras/skills/analytics/cfn-pattern-extraction/extract-patterns.sh +79 -79
  121. package/claude-assets/cfn-extras/skills/analytics/cfn-retrospective-report/generate-report.sh +100 -100
  122. package/claude-assets/cfn-extras/skills/analytics/cfn-telemetry/start-telemetry.sh +110 -110
  123. package/claude-assets/cfn-extras/skills/deprecated/cfn-ace-system/add-bullet.sh +145 -145
  124. package/claude-assets/cfn-extras/skills/deprecated/cfn-ace-system/log-merge.sh +67 -67
  125. package/claude-assets/cfn-extras/skills/deprecated/cfn-ace-system/monitor-injection-performance.sh +137 -137
  126. package/claude-assets/cfn-extras/skills/deprecated/cfn-ace-system/optimize-injection-pipeline.sh +168 -168
  127. package/claude-assets/cfn-extras/skills/deprecated/cfn-ace-system/query-reflections.sh +35 -35
  128. package/claude-assets/cfn-extras/skills/deprecated/cfn-ace-system/store-reflection.sh +45 -45
  129. package/claude-assets/cfn-extras/skills/deprecated/cfn-ace-system/track-ab-test.sh +41 -41
  130. package/claude-assets/cfn-extras/skills/deprecated/cfn-ace-system/update-reflection.sh +41 -41
  131. package/claude-assets/cfn-extras/skills/deprecated/cfn-cli-setup/validate-cli-environment.sh +191 -191
  132. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-ad-campaigns/operations/create-campaign.sh +231 -231
  133. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-ad-campaigns/operations/get-campaign-performance.sh +190 -190
  134. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-ad-campaigns/operations/pause-campaign.sh +142 -142
  135. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-ad-campaigns/operations/set-budget.sh +181 -181
  136. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-ad-campaigns/operations/update-bid-strategy.sh +133 -133
  137. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-chatbot-conversations/operations/get-conversation-history.sh +121 -121
  138. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-chatbot-conversations/operations/qualify-lead.sh +156 -156
  139. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-chatbot-conversations/operations/schedule-demo.sh +181 -181
  140. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-chatbot-conversations/operations/send-message.sh +137 -137
  141. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-chatbot-conversations/operations/transfer-to-human.sh +179 -179
  142. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-sms-campaigns/operations/create-campaign.sh +183 -183
  143. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-sms-campaigns/operations/get-delivery-status.sh +139 -139
  144. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-sms-campaigns/operations/opt-out.sh +150 -150
  145. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-sms-campaigns/operations/schedule-campaign.sh +187 -187
  146. package/claude-assets/cfn-extras/skills/marketing/cfn-marketing-sms-campaigns/operations/send-sms.sh +181 -181
  147. package/claude-assets/cfn-extras/skills/ui-portal/cfn-web-portal/test-web-portal-skill.sh +50 -50
  148. package/claude-assets/cfn-extras/skills/ui-portal/cfn-web-portal/validate-deployment.sh +84 -84
  149. package/claude-assets/cfn-extras/skills/utility/cfn-environment-sanitization/sanitize-environment.sh +243 -243
  150. package/claude-assets/commands/cfn-loop-cli.md +16 -2
  151. package/claude-assets/commands/switch-api.md +31 -10
  152. package/claude-assets/hooks/cfn-BACKUP_USAGE.md +243 -243
  153. package/claude-assets/hooks/cfn-invoke-security-validation.sh +69 -69
  154. package/claude-assets/hooks/cfn-lint-sql-injection.sh +61 -0
  155. package/claude-assets/hooks/cfn-post-edit-cfn-retrospective.sh +109 -78
  156. package/claude-assets/hooks/cfn-post-edit.config.json +44 -44
  157. package/claude-assets/hooks/cfn-post-execution/memory-cleanup.sh +19 -19
  158. package/claude-assets/hooks/cfn-pre-edit-security-warning.sh +40 -0
  159. package/claude-assets/hooks/cfn-pre-execution/memory-check.sh +19 -19
  160. package/claude-assets/hooks/detect-hardcoded-credentials.sh +212 -0
  161. package/claude-assets/skills/SKILL_TEMPLATE.md +774 -0
  162. package/claude-assets/skills/agent-lifecycle/execute-lifecycle-hook.sh +543 -572
  163. package/claude-assets/skills/agent-lifecycle/simple-audit.sh +57 -30
  164. package/claude-assets/skills/agent-template-generator/SKILL.md +440 -0
  165. package/claude-assets/skills/agent-template-generator/generate-agent.sh +405 -0
  166. package/claude-assets/skills/agent-validation-linter/SKILL.md +589 -0
  167. package/claude-assets/skills/agent-validation-linter/lint-agents.sh +271 -0
  168. package/claude-assets/skills/bootstrap/bash-fundamentals.md +786 -0
  169. package/claude-assets/skills/bootstrap/database-connection.md +464 -0
  170. package/claude-assets/skills/bootstrap/error-handling.md +580 -0
  171. package/claude-assets/skills/bootstrap/file-operations.md +699 -0
  172. package/claude-assets/skills/bootstrap/skill-loader.md +616 -0
  173. package/claude-assets/skills/bootstrap/sqlite-params.sh +287 -0
  174. package/claude-assets/skills/cfn-agent-spawning/spawn-agent.sh +22 -24
  175. package/claude-assets/skills/cfn-automatic-memory-persistence/persist-agent-output.sh +48 -48
  176. package/claude-assets/skills/cfn-automatic-memory-persistence/query-agent-history.sh +34 -34
  177. package/claude-assets/skills/cfn-automatic-memory-persistence/test-memory-persistence.sh +17 -16
  178. package/claude-assets/skills/cfn-deliverable-validation/confidence-calculator.sh +261 -261
  179. package/claude-assets/skills/cfn-deployment/SKILL.md +293 -0
  180. package/claude-assets/skills/cfn-deployment/execute.sh +21 -0
  181. package/claude-assets/skills/cfn-docker-agent-spawning/SKILL.md +28 -4
  182. package/claude-assets/skills/cfn-docker-agent-spawning/spawn-agent.sh +3 -1
  183. package/claude-assets/skills/cfn-docker-loop-orchestration/orchestrate.sh +224 -20
  184. package/claude-assets/skills/cfn-environment-sanitization/sanitize-environment.sh +38 -0
  185. package/claude-assets/skills/cfn-error-batching-strategy/lib/core-functions.sh +47 -47
  186. package/claude-assets/skills/cfn-expert-update/update-expert.sh +345 -345
  187. package/claude-assets/skills/cfn-file-operations/SKILL.md +290 -0
  188. package/claude-assets/skills/cfn-file-operations/execute.sh +129 -0
  189. package/claude-assets/skills/cfn-file-operations/lib/atomic-write.sh +294 -0
  190. package/claude-assets/skills/cfn-file-operations/lib/lock.sh +361 -0
  191. package/claude-assets/skills/cfn-file-operations/test.sh +369 -0
  192. package/claude-assets/skills/cfn-hybrid-routing/check-dependencies.sh +51 -51
  193. package/claude-assets/skills/cfn-intervention-detector/detect-intervention.sh +110 -110
  194. package/claude-assets/skills/cfn-intervention-orchestrator/execute-intervention.sh +58 -58
  195. package/claude-assets/skills/cfn-log-operations/SKILL.md +308 -0
  196. package/claude-assets/skills/cfn-log-operations/execute.sh +420 -0
  197. package/claude-assets/skills/cfn-log-operations/lib/rotate.sh +406 -0
  198. package/claude-assets/skills/cfn-log-operations/lib/search.sh +448 -0
  199. package/claude-assets/skills/cfn-log-operations/test.sh +394 -0
  200. package/claude-assets/skills/cfn-loop-orchestration/helpers/gate-check.sh +550 -46
  201. package/claude-assets/skills/cfn-loop-orchestration/helpers/parse-test-results.sh +277 -0
  202. package/claude-assets/skills/cfn-loop-orchestration/orchestrate.sh +184 -23
  203. package/claude-assets/skills/cfn-loop-orchestration/security_utils.sh +24 -0
  204. package/claude-assets/skills/cfn-loop-orchestration/test-iteration-context-injection.sh +366 -0
  205. package/claude-assets/skills/cfn-loop-validation/orchestrate-cfn-loop.sh +252 -252
  206. package/claude-assets/skills/cfn-loop2-output-processing/process-validator-output.sh +275 -275
  207. package/claude-assets/skills/cfn-memory-management/check-memory.sh +159 -159
  208. package/claude-assets/skills/cfn-memory-management/cleanup-memory.sh +196 -196
  209. package/claude-assets/skills/cfn-node-heap-sizer/task-mode-heap-limiter.sh +325 -325
  210. package/claude-assets/skills/cfn-parameterized-queries/SKILL.md +339 -0
  211. package/claude-assets/skills/cfn-playbook/query-playbook.sh +19 -15
  212. package/claude-assets/skills/cfn-playbook/update-playbook.sh +25 -14
  213. package/claude-assets/skills/cfn-playbook-auto-update/auto-update-playbook.sh +85 -85
  214. package/claude-assets/skills/cfn-process-instrumentation/instrument-process.sh +44 -0
  215. package/claude-assets/skills/cfn-promotion/SKILL.md +305 -0
  216. package/claude-assets/skills/cfn-redis-coordination/CENTRALIZED_REDIS_WRAPPER.md +319 -0
  217. package/claude-assets/skills/cfn-redis-coordination/agent-log.sh +4 -0
  218. package/claude-assets/skills/cfn-redis-coordination/agent-log.sh.bak +124 -0
  219. package/claude-assets/skills/cfn-redis-coordination/agent-recovery.sh +74 -74
  220. package/claude-assets/skills/cfn-redis-coordination/collect-confidence-scores.sh +30 -0
  221. package/claude-assets/skills/cfn-redis-coordination/get-context.sh +145 -112
  222. package/claude-assets/skills/cfn-redis-coordination/get-success-criteria.sh +54 -0
  223. package/claude-assets/skills/cfn-redis-coordination/invoke-waiting-mode.sh +3 -0
  224. package/claude-assets/skills/cfn-redis-coordination/redis-cli-wrapper.sh +24 -3
  225. package/claude-assets/skills/cfn-redis-coordination/redis-functions.sh +33 -0
  226. package/claude-assets/skills/cfn-redis-coordination/report-completion.sh +24 -31
  227. package/claude-assets/skills/cfn-redis-coordination/store-context.sh +4 -0
  228. package/claude-assets/skills/cfn-redis-coordination/store-success-criteria.sh +85 -0
  229. package/claude-assets/skills/cfn-redis-coordination/update-all-scripts.sh +67 -0
  230. package/claude-assets/skills/cfn-scope-simplifier/simplify-scope.sh +67 -67
  231. package/claude-assets/skills/cfn-skill-loader/SKILL.md +466 -0
  232. package/claude-assets/skills/cfn-skill-loader/execute.sh +344 -0
  233. package/claude-assets/skills/cfn-specialist-injection/recommend-specialist.sh +56 -56
  234. package/claude-assets/skills/cfn-sqlite-memory/ttl-cleanup.sh +17 -25
  235. package/claude-assets/skills/cfn-standardized-error-handling/capture-agent-error.sh +86 -86
  236. package/claude-assets/skills/cfn-standardized-error-handling/test-error-handling.sh +165 -165
  237. package/claude-assets/skills/cfn-task-audit/get-audit-data.sh +42 -21
  238. package/claude-assets/skills/cfn-task-audit/store-task-audit.sh +17 -10
  239. package/claude-assets/skills/cfn-task-config-init/initialize-config.sh +264 -264
  240. package/claude-assets/skills/cfn-task-decomposition/task-decomposer.sh +278 -278
  241. package/claude-assets/skills/cfn-test-runner/detect-regressions.sh +17 -14
  242. package/claude-assets/skills/cfn-test-runner/detect-regressions.sh.backup-1763392821 +55 -0
  243. package/claude-assets/skills/cfn-test-runner/store-benchmarks.sh +17 -19
  244. package/claude-assets/skills/cfn-transparency-middleware/middleware-config.sh +28 -28
  245. package/claude-assets/skills/cfn-transparency-middleware/performance-benchmark.sh +78 -78
  246. package/claude-assets/skills/cfn-transparency-middleware/test-e2e.sh +15 -0
  247. package/claude-assets/skills/cfn-transparency-middleware/test-integration.sh +161 -161
  248. package/claude-assets/skills/cfn-transparency-middleware/test-transparency-skill.sh +367 -367
  249. package/claude-assets/skills/cfn-transparency-middleware/tests/input-validation.sh +107 -92
  250. package/claude-assets/skills/cfn-transparency-middleware/wrap-agent.sh +131 -131
  251. package/claude-assets/skills/cfn-utilities/SKILL.md +237 -0
  252. package/claude-assets/skills/cfn-utilities/execute.sh +32 -0
  253. package/claude-assets/skills/cfn-utilities/lib/errors.sh +56 -0
  254. package/claude-assets/skills/cfn-utilities/lib/file-ops.sh +164 -0
  255. package/claude-assets/skills/cfn-utilities/lib/logging.sh +77 -0
  256. package/claude-assets/skills/cfn-utilities/lib/retry.sh +127 -0
  257. package/claude-assets/skills/cfn-utilities/test.sh +317 -0
  258. package/claude-assets/skills/docker-build/SKILL.md +96 -203
  259. package/claude-assets/skills/docker-build/build.sh +73 -73
  260. package/claude-assets/skills/integration/agent-handoff.sh +492 -0
  261. package/claude-assets/skills/integration/file-operations.sh +414 -0
  262. package/claude-assets/skills/json-validation/SKILL.md +431 -0
  263. package/claude-assets/skills/json-validation/test-validate-success-criteria.sh +421 -0
  264. package/claude-assets/skills/json-validation/validate-success-criteria.sh +197 -0
  265. package/claude-assets/skills/redis-coordination/validate-parameters.sh +34 -0
  266. package/claude-assets/skills/workflow-codification/APPROVAL_WORKFLOW.md +806 -0
  267. package/claude-assets/skills/workflow-codification/COST_TRACKING.md +637 -0
  268. package/claude-assets/skills/workflow-codification/DEPLOY_QUICK_REFERENCE.md +106 -0
  269. package/claude-assets/skills/workflow-codification/EDGE_CASE_TRACKING.md +404 -0
  270. package/claude-assets/skills/workflow-codification/PROPAGATE_UPDATE_QUICK_REFERENCE.md +366 -0
  271. package/claude-assets/skills/workflow-codification/README_PHASE4.md +457 -0
  272. package/claude-assets/skills/workflow-codification/SKILL.md +110 -0
  273. package/claude-assets/skills/workflow-codification/analyze-patterns.sh +899 -0
  274. package/claude-assets/skills/workflow-codification/approval-workflow.sh +514 -0
  275. package/claude-assets/skills/workflow-codification/deploy-approved-skill.sh +481 -0
  276. package/claude-assets/skills/workflow-codification/deploy-approved-skill.sh.backup-1763392820 +512 -0
  277. package/claude-assets/skills/workflow-codification/generate-skill-update.sh +525 -0
  278. package/claude-assets/skills/workflow-codification/lib/security-utils.sh +204 -0
  279. package/claude-assets/skills/workflow-codification/propagate-skill-update.sh +648 -0
  280. package/claude-assets/skills/workflow-codification/propagate-skill-update.sh.backup-1763392820 +664 -0
  281. package/claude-assets/skills/workflow-codification/review-skill.sh +643 -0
  282. package/claude-assets/skills/workflow-codification/templates/email-notification.txt +114 -0
  283. package/claude-assets/skills/workflow-codification/templates/slack-notification.md +85 -0
  284. package/claude-assets/skills/workflow-codification/test-integration.sh +296 -0
  285. package/claude-assets/skills/workflow-codification/test-metadata-update.sh +350 -0
  286. package/claude-assets/skills/workflow-codification/track-cost-savings.sh +486 -0
  287. package/claude-assets/skills/workflow-codification/track-cost-savings.sh.backup-1763392821 +445 -0
  288. package/claude-assets/skills/workflow-codification/track-edge-case.sh +290 -0
  289. package/claude-assets/skills/workflow-codification/workflow-codification.db +0 -0
  290. package/dist/ace/ace-curator.js +10 -2
  291. package/dist/ace/ace-curator.js.map +1 -1
  292. package/dist/ace/ace-generator.js +4 -0
  293. package/dist/ace/ace-generator.js.map +1 -1
  294. package/dist/ace/ace-reflector.js +1 -1
  295. package/dist/ace/ace-reflector.js.map +1 -1
  296. package/dist/ace/context-injection.js +24 -2
  297. package/dist/ace/context-injection.js.map +1 -1
  298. package/dist/agents/agent-loader.js +146 -165
  299. package/dist/agents/agent-loader.js.map +1 -1
  300. package/dist/agents/task-agent-integration.js +1 -1
  301. package/dist/agents/task-agent-integration.js.map +1 -1
  302. package/dist/api/health-endpoints.js +390 -0
  303. package/dist/api/health-endpoints.js.map +1 -0
  304. package/dist/cli/agent-executor.js +4 -1
  305. package/dist/cli/agent-executor.js.map +1 -1
  306. package/dist/cli/agent-prompt-builder.js +89 -1
  307. package/dist/cli/agent-prompt-builder.js.map +1 -1
  308. package/dist/cli/agent-spawn.js +130 -37
  309. package/dist/cli/agent-spawn.js.map +1 -1
  310. package/dist/cli/config-manager.js +91 -109
  311. package/dist/cli/config-manager.js.map +1 -1
  312. package/dist/cli/skill-cache-validator.js +412 -0
  313. package/dist/cli/skill-cache-validator.js.map +1 -0
  314. package/dist/cli/skill-cli.js +991 -0
  315. package/dist/cli/skill-cli.js.map +1 -0
  316. package/dist/cli/skill-execution-logger.js +284 -0
  317. package/dist/cli/skill-execution-logger.js.map +1 -0
  318. package/dist/cli/skill-loader.js +457 -0
  319. package/dist/cli/skill-loader.js.map +1 -0
  320. package/dist/coordination/event-bus.js +2 -2
  321. package/dist/coordination/event-bus.js.map +1 -1
  322. package/dist/coordination/fleet-manager.js +1 -1
  323. package/dist/coordination/fleet-manager.js.map +1 -1
  324. package/dist/coordination/index.js +23 -9
  325. package/dist/coordination/index.js.map +1 -1
  326. package/dist/coordination/types/fleet-manager.types.js.map +1 -1
  327. package/dist/db/migration-manager.js +483 -0
  328. package/dist/db/migration-manager.js.map +1 -0
  329. package/dist/db/skills-query.js +535 -0
  330. package/dist/db/skills-query.js.map +1 -0
  331. package/dist/integration/DatabaseHandoff.js +507 -0
  332. package/dist/integration/DatabaseHandoff.js.map +1 -0
  333. package/dist/integration/StandardAdapter.js +291 -0
  334. package/dist/integration/StandardAdapter.js.map +1 -0
  335. package/dist/jobs/edge-case-analyzer.js +367 -0
  336. package/dist/jobs/edge-case-analyzer.js.map +1 -0
  337. package/dist/jobs/promotion-sla-enforcer.js +288 -0
  338. package/dist/jobs/promotion-sla-enforcer.js.map +1 -0
  339. package/dist/lib/agent-output-parser.js +518 -0
  340. package/dist/lib/agent-output-parser.js.map +1 -0
  341. package/dist/lib/agent-output-validator.js +950 -0
  342. package/dist/lib/agent-output-validator.js.map +1 -0
  343. package/dist/lib/agent-workspace.js +281 -0
  344. package/dist/lib/agent-workspace.js.map +1 -0
  345. package/dist/lib/artifact-registry.js +443 -0
  346. package/dist/lib/artifact-registry.js.map +1 -0
  347. package/dist/lib/atomic-file-writer.js +377 -0
  348. package/dist/lib/atomic-file-writer.js.map +1 -0
  349. package/dist/lib/backup-manager.js +779 -0
  350. package/dist/lib/backup-manager.js.map +1 -0
  351. package/dist/lib/checkpoint-manager.js +837 -0
  352. package/dist/lib/checkpoint-manager.js.map +1 -0
  353. package/dist/lib/circuit-breaker.js +340 -0
  354. package/dist/lib/circuit-breaker.js.map +1 -0
  355. package/dist/lib/completion-signal-handler.js +243 -0
  356. package/dist/lib/completion-signal-handler.js.map +1 -0
  357. package/dist/lib/config-manager.js +312 -0
  358. package/dist/lib/config-manager.js.map +1 -0
  359. package/dist/lib/config-migrator.js +386 -0
  360. package/dist/lib/config-migrator.js.map +1 -0
  361. package/dist/lib/config-validator.js +687 -0
  362. package/dist/lib/config-validator.js.map +1 -0
  363. package/dist/lib/correlation-cache.js +311 -0
  364. package/dist/lib/correlation-cache.js.map +1 -0
  365. package/dist/lib/correlation.js +263 -0
  366. package/dist/lib/correlation.js.map +1 -0
  367. package/dist/lib/database-service/connection-pool-manager.js +520 -0
  368. package/dist/lib/database-service/connection-pool-manager.js.map +1 -0
  369. package/dist/lib/database-service/correlation.js +329 -0
  370. package/dist/lib/database-service/correlation.js.map +1 -0
  371. package/dist/lib/database-service/errors.js +120 -0
  372. package/dist/lib/database-service/errors.js.map +1 -0
  373. package/dist/lib/database-service/index.js +168 -0
  374. package/dist/lib/database-service/index.js.map +1 -0
  375. package/dist/lib/database-service/postgres-adapter.js +526 -0
  376. package/dist/lib/database-service/postgres-adapter.js.map +1 -0
  377. package/dist/lib/database-service/redis-adapter.js +360 -0
  378. package/dist/lib/database-service/redis-adapter.js.map +1 -0
  379. package/dist/lib/database-service/sqlite-adapter.js +544 -0
  380. package/dist/lib/database-service/sqlite-adapter.js.map +1 -0
  381. package/dist/lib/database-service/transaction-manager.js +773 -0
  382. package/dist/lib/database-service/transaction-manager.js.map +1 -0
  383. package/dist/lib/database-service/types.js +23 -0
  384. package/dist/lib/database-service/types.js.map +1 -0
  385. package/dist/lib/deadlock-resolver.js +292 -0
  386. package/dist/lib/deadlock-resolver.js.map +1 -0
  387. package/dist/lib/distributed-lock.js +451 -0
  388. package/dist/lib/distributed-lock.js.map +1 -0
  389. package/dist/lib/edge-case-deduplicator.js +227 -0
  390. package/dist/lib/edge-case-deduplicator.js.map +1 -0
  391. package/dist/lib/encryption-manager.js +322 -0
  392. package/dist/lib/encryption-manager.js.map +1 -0
  393. package/dist/lib/error-aggregator.js +234 -0
  394. package/dist/lib/error-aggregator.js.map +1 -0
  395. package/dist/lib/errors.js +287 -0
  396. package/dist/lib/errors.js.map +1 -0
  397. package/dist/lib/file-lock-manager.js +578 -0
  398. package/dist/lib/file-lock-manager.js.map +1 -0
  399. package/dist/lib/file-operations.js +367 -0
  400. package/dist/lib/file-operations.js.map +1 -0
  401. package/dist/lib/idempotent-write.js +237 -0
  402. package/dist/lib/idempotent-write.js.map +1 -0
  403. package/dist/lib/integration-schema-validator.js +522 -0
  404. package/dist/lib/integration-schema-validator.js.map +1 -0
  405. package/dist/lib/lock-health-monitor.js +298 -0
  406. package/dist/lib/lock-health-monitor.js.map +1 -0
  407. package/dist/lib/log-shipper.js +422 -0
  408. package/dist/lib/log-shipper.js.map +1 -0
  409. package/dist/lib/logging.js +146 -0
  410. package/dist/lib/logging.js.map +1 -0
  411. package/dist/lib/message-deduplicator.js +439 -0
  412. package/dist/lib/message-deduplicator.js.map +1 -0
  413. package/dist/lib/multi-system-query.js +604 -0
  414. package/dist/lib/multi-system-query.js.map +1 -0
  415. package/dist/lib/orphan-detector.js +332 -0
  416. package/dist/lib/orphan-detector.js.map +1 -0
  417. package/dist/lib/password-generator.js +166 -0
  418. package/dist/lib/password-generator.js.map +1 -0
  419. package/dist/lib/path-validator.js +429 -0
  420. package/dist/lib/path-validator.js.map +1 -0
  421. package/dist/lib/query-translator.js +905 -0
  422. package/dist/lib/query-translator.js.map +1 -0
  423. package/dist/lib/queue-recovery.js +469 -0
  424. package/dist/lib/queue-recovery.js.map +1 -0
  425. package/dist/lib/redis-queue-manager.js +512 -0
  426. package/dist/lib/redis-queue-manager.js.map +1 -0
  427. package/dist/lib/reflection-archiver.js +272 -0
  428. package/dist/lib/reflection-archiver.js.map +1 -0
  429. package/dist/lib/retry-manager.js +453 -0
  430. package/dist/lib/retry-manager.js.map +1 -0
  431. package/dist/lib/retry.js +262 -0
  432. package/dist/lib/retry.js.map +1 -0
  433. package/dist/lib/schema-transform.js +695 -0
  434. package/dist/lib/schema-transform.js.map +1 -0
  435. package/dist/lib/schema-validator.js +491 -0
  436. package/dist/lib/schema-validator.js.map +1 -0
  437. package/dist/lib/skill-cache.js +297 -0
  438. package/dist/lib/skill-cache.js.map +1 -0
  439. package/dist/lib/skill-content-manager.js +337 -0
  440. package/dist/lib/skill-content-manager.js.map +1 -0
  441. package/dist/lib/skill-frontmatter-parser.js +237 -0
  442. package/dist/lib/skill-frontmatter-parser.js.map +1 -0
  443. package/dist/lib/skill-git-integration.js +275 -0
  444. package/dist/lib/skill-git-integration.js.map +1 -0
  445. package/dist/lib/skill-markdown-validator.js +396 -0
  446. package/dist/lib/skill-markdown-validator.js.map +1 -0
  447. package/dist/lib/skill-output-parser.js +312 -0
  448. package/dist/lib/skill-output-parser.js.map +1 -0
  449. package/dist/lib/unified-query-api.js +467 -0
  450. package/dist/lib/unified-query-api.js.map +1 -0
  451. package/dist/middleware/auth-middleware.js +350 -0
  452. package/dist/middleware/auth-middleware.js.map +1 -0
  453. package/dist/middleware/schema-validation.js +347 -0
  454. package/dist/middleware/schema-validation.js.map +1 -0
  455. package/dist/providers/anthropic-provider.js +1 -1
  456. package/dist/providers/anthropic-provider.js.map +1 -1
  457. package/dist/providers/provider-factory.js +2 -2
  458. package/dist/providers/provider-factory.js.map +1 -1
  459. package/dist/services/edge-case-analyzer.js +321 -0
  460. package/dist/services/edge-case-analyzer.js.map +1 -0
  461. package/dist/services/edge-case-deduplicator.js +266 -0
  462. package/dist/services/edge-case-deduplicator.js.map +1 -0
  463. package/dist/services/edge-case-detector.js +337 -0
  464. package/dist/services/edge-case-detector.js.map +1 -0
  465. package/dist/services/edge-case-tracker.js +547 -0
  466. package/dist/services/edge-case-tracker.js.map +1 -0
  467. package/dist/services/health-check-system.js +586 -0
  468. package/dist/services/health-check-system.js.map +1 -0
  469. package/dist/services/metrics-logger.js +412 -0
  470. package/dist/services/metrics-logger.js.map +1 -0
  471. package/dist/services/patch-generator.js +378 -0
  472. package/dist/services/patch-generator.js.map +1 -0
  473. package/dist/services/patch-validator.js +337 -0
  474. package/dist/services/patch-validator.js.map +1 -0
  475. package/dist/services/performance-monitor.js +811 -0
  476. package/dist/services/performance-monitor.js.map +1 -0
  477. package/dist/services/promotion-pipeline.js +918 -0
  478. package/dist/services/promotion-pipeline.js.map +1 -0
  479. package/dist/services/promotion-validator.js +394 -0
  480. package/dist/services/promotion-validator.js.map +1 -0
  481. package/dist/services/reflection-logger.js +388 -0
  482. package/dist/services/reflection-logger.js.map +1 -0
  483. package/dist/services/skill-deployment.js +472 -0
  484. package/dist/services/skill-deployment.js.map +1 -0
  485. package/dist/services/skill-loader.js +427 -0
  486. package/dist/services/skill-loader.js.map +1 -0
  487. package/dist/services/skill-promotion.js +372 -0
  488. package/dist/services/skill-promotion.js.map +1 -0
  489. package/dist/services/skill-validator.js +454 -0
  490. package/dist/services/skill-validator.js.map +1 -0
  491. package/dist/services/skill-versioning.js +244 -0
  492. package/dist/services/skill-versioning.js.map +1 -0
  493. package/dist/services/workspace-supervisor.js +597 -0
  494. package/dist/services/workspace-supervisor.js.map +1 -0
  495. package/dist/types/agent-output.js +44 -0
  496. package/dist/types/agent-output.js.map +1 -0
  497. package/dist/types/config.js +28 -0
  498. package/dist/types/config.js.map +1 -0
  499. package/dist/types/edge-case.js +45 -0
  500. package/dist/types/edge-case.js.map +1 -0
  501. package/package.json +201 -176
  502. package/readme/README.md +19 -4
  503. package/scripts/artifact-cleanup.sh +392 -0
  504. package/scripts/backup-cleanup.sh +627 -0
  505. package/scripts/cleanup-workspaces.sh +412 -0
  506. package/scripts/cleanup-yaml-configs.sh +141 -0
  507. package/scripts/deploy-approved-skills.sh +263 -0
  508. package/scripts/deploy-production.sh +355 -355
  509. package/scripts/docker-playwright-fix.sh +311 -311
  510. package/scripts/docker-rebuild-all-agents.sh +127 -127
  511. package/scripts/health-check.sh +447 -0
  512. package/scripts/log-aggregator.sh +554 -0
  513. package/scripts/log-monitor.sh +629 -0
  514. package/scripts/manage-agent-workspaces.sh +434 -0
  515. package/scripts/memory-leak-prevention.sh +305 -305
  516. package/scripts/migrate-artifacts.sh +563 -0
  517. package/scripts/migrate-schema.sh +533 -0
  518. package/scripts/migrate-yaml-to-json.sh +465 -0
  519. package/scripts/promote-staged-skills.sh +423 -0
  520. package/scripts/run-marketing-tests.sh +42 -42
  521. package/scripts/update_paths.sh +46 -46
  522. package/scripts/verify-no-secrets.sh +88 -35
  523. package/.claude/cfn-extras/agents/deprecated-coordinators/adaptive-coordinator.md.backup +0 -161
  524. package/.claude/cfn-extras/agents/deprecated-coordinators/blocking-coordinator-example.md.backup +0 -728
  525. package/.claude/cfn-extras/agents/deprecated-coordinators/mesh-coordinator.md.backup +0 -131
  526. package/.claude/skills/cfn-agent-spawning/spawn-agent.sh.backup +0 -273
  527. package/.claude/skills/cfn-loop-orchestration/orchestrate.sh.backup +0 -949
  528. package/README.md.backup_before_replace +0 -781
  529. package/claude-assets/cfn-extras/agents/deprecated-coordinators/adaptive-coordinator.md.backup +0 -161
  530. package/claude-assets/cfn-extras/agents/deprecated-coordinators/blocking-coordinator-example.md.backup +0 -728
  531. package/claude-assets/cfn-extras/agents/deprecated-coordinators/mesh-coordinator.md.backup +0 -131
  532. package/claude-assets/skills/cfn-agent-spawning/spawn-agent.sh.backup +0 -273
  533. package/claude-assets/skills/cfn-loop-orchestration/orchestrate.sh.backup +0 -949
@@ -0,0 +1,457 @@
1
+ /**
2
+ * Skill Loader
3
+ *
4
+ * High-performance skill loading system with LRU caching and hash-based validation.
5
+ * Provides contextual skill selection for agent prompt building.
6
+ *
7
+ * Performance targets:
8
+ * - Cold load: <1s
9
+ * - Warm load: <100ms
10
+ * - Cache TTL: 5 minutes
11
+ *
12
+ * @module skill-loader
13
+ */ import * as fs from 'fs';
14
+ import * as path from 'path';
15
+ import { createLogger } from '../lib/logging.js';
16
+ import { SkillsQueryBuilder, BOOTSTRAP_SKILL_IDS } from '../db/skills-query.js';
17
+ import { SkillCacheValidator } from './skill-cache-validator.js';
18
+ /**
19
+ * Skill Loader
20
+ *
21
+ * Manages skill loading with LRU caching and hash-based validation.
22
+ */ export class SkillLoader {
23
+ logger;
24
+ validator;
25
+ cache;
26
+ cacheMaxSize = 100;
27
+ cacheTTLMinutes = 5;
28
+ dbService;
29
+ skillsBasePath;
30
+ constructor(dbService, logger, skillsBasePath){
31
+ this.logger = logger ?? createLogger('skill-loader');
32
+ this.dbService = dbService;
33
+ this.validator = new SkillCacheValidator(this.logger, dbService);
34
+ this.cache = new Map();
35
+ this.skillsBasePath = skillsBasePath ?? path.join(process.cwd(), '.claude/skills');
36
+ }
37
+ /**
38
+ * Load contextual skills for an agent
39
+ *
40
+ * Main entry point for skill loading with caching and validation.
41
+ *
42
+ * @param options - Skill loader options
43
+ * @returns Load result with skills and metadata
44
+ */ async loadContextualSkills(options) {
45
+ const startTime = Date.now();
46
+ const { agentType, taskContext = [], maxSkills = 20, includeBootstrap = true, phase } = options;
47
+ this.logger.info('Loading contextual skills', {
48
+ agentType,
49
+ taskContext,
50
+ maxSkills,
51
+ includeBootstrap,
52
+ phase
53
+ });
54
+ const result = {
55
+ skills: [],
56
+ loadTimeMs: 0,
57
+ cacheHitCount: 0,
58
+ cacheMissCount: 0,
59
+ cacheInvalidationCount: 0,
60
+ totalSkills: 0,
61
+ bootstrapCount: 0
62
+ };
63
+ try {
64
+ // Validate cache integrity with bulk hash check (if database available)
65
+ if (this.dbService && this.cache.size > 0) {
66
+ const cachedEntries = Array.from(this.cache.values()).map((entry)=>entry.data);
67
+ const validation = await this.validator.validateCachedSkills(cachedEntries);
68
+ if (!validation.isValid) {
69
+ // Invalidate cache entries with hash mismatches
70
+ for (const skillId of validation.invalidSkillIds){
71
+ this.cache.delete(skillId);
72
+ result.cacheInvalidationCount++;
73
+ }
74
+ this.logger.warn('Cache invalidated due to hash mismatches', {
75
+ invalidatedCount: validation.invalidCount,
76
+ invalidSkillIds: validation.invalidSkillIds,
77
+ validationDurationMs: validation.durationMs
78
+ });
79
+ } else {
80
+ this.logger.debug('Cache validation passed', {
81
+ validCount: validation.validCount,
82
+ validationDurationMs: validation.durationMs
83
+ });
84
+ }
85
+ }
86
+ // Load bootstrap skills first (always included unless explicitly disabled)
87
+ if (includeBootstrap) {
88
+ const bootstrapSkills = await this.loadBootstrapSkills();
89
+ result.skills.push(...bootstrapSkills);
90
+ result.bootstrapCount = bootstrapSkills.length;
91
+ }
92
+ // Load agent-specific skills from database
93
+ if (this.dbService) {
94
+ const agentSkills = await this.loadAgentSkills(agentType, taskContext, phase, maxSkills - result.skills.length);
95
+ // Track cache hits/misses from agent skill loading
96
+ const { skills, cacheHits, cacheMisses } = agentSkills;
97
+ result.skills.push(...skills);
98
+ result.cacheHitCount = cacheHits;
99
+ result.cacheMissCount = cacheMisses;
100
+ } else {
101
+ this.logger.warn('Database service not configured - loading bootstrap skills only');
102
+ }
103
+ result.totalSkills = result.skills.length;
104
+ result.loadTimeMs = Date.now() - startTime;
105
+ this.logger.info('Skills loaded successfully', {
106
+ totalSkills: result.totalSkills,
107
+ bootstrapSkills: result.bootstrapCount,
108
+ agentSkills: result.totalSkills - result.bootstrapCount,
109
+ cacheHits: result.cacheHitCount,
110
+ cacheMisses: result.cacheMissCount,
111
+ cacheInvalidations: result.cacheInvalidationCount,
112
+ loadTimeMs: result.loadTimeMs
113
+ });
114
+ // Log performance warning if exceeding targets
115
+ if (result.loadTimeMs > 1000) {
116
+ this.logger.warn('Skill loading exceeded 1s target', {
117
+ loadTimeMs: result.loadTimeMs,
118
+ target: 1000
119
+ });
120
+ }
121
+ return result;
122
+ } catch (error) {
123
+ this.logger.error('Failed to load skills', error, {
124
+ agentType,
125
+ taskContext
126
+ });
127
+ throw new Error(`Skill loading failed: ${error.message}`);
128
+ }
129
+ }
130
+ /**
131
+ * Load bootstrap skills (always included)
132
+ *
133
+ * Bootstrap skills are loaded from static files without database dependency.
134
+ */ async loadBootstrapSkills() {
135
+ const skills = [];
136
+ for (const skillId of BOOTSTRAP_SKILL_IDS){
137
+ try {
138
+ // Check cache first
139
+ const cached = this.getCachedSkill(skillId);
140
+ if (cached) {
141
+ skills.push({
142
+ id: cached.skillId,
143
+ name: skillId,
144
+ version: '1.0.0',
145
+ content: cached.content,
146
+ contentHash: cached.contentHash,
147
+ namespace: 'cfn',
148
+ priority: 10
149
+ });
150
+ continue;
151
+ }
152
+ // Load from file
153
+ const skillPath = path.join(this.skillsBasePath, skillId, 'SKILL.md');
154
+ if (!fs.existsSync(skillPath)) {
155
+ this.logger.warn('Bootstrap skill file not found', {
156
+ skillId,
157
+ skillPath
158
+ });
159
+ continue;
160
+ }
161
+ const content = await fs.promises.readFile(skillPath, 'utf-8');
162
+ const contentHash = this.validator.computeHash(content);
163
+ // Cache the skill
164
+ this.setCachedSkill(skillId, content, contentHash);
165
+ skills.push({
166
+ id: skillId,
167
+ name: skillId,
168
+ version: '1.0.0',
169
+ content,
170
+ contentHash,
171
+ namespace: 'cfn',
172
+ priority: 10
173
+ });
174
+ } catch (error) {
175
+ this.logger.error('Failed to load bootstrap skill', error, {
176
+ skillId
177
+ });
178
+ }
179
+ }
180
+ return skills;
181
+ }
182
+ /**
183
+ * Load agent-specific skills from database
184
+ */ async loadAgentSkills(agentType, taskContext, phase, maxSkills) {
185
+ if (!this.dbService) {
186
+ return {
187
+ skills: [],
188
+ cacheHits: 0,
189
+ cacheMisses: 0
190
+ };
191
+ }
192
+ const skills = [];
193
+ let cacheHits = 0;
194
+ let cacheMisses = 0;
195
+ try {
196
+ // Get SQLite adapter
197
+ const sqlite = this.dbService.getAdapter('sqlite');
198
+ // Build query
199
+ const { sql, params } = SkillsQueryBuilder.getSkillsByAgentType(agentType, taskContext, phase);
200
+ // Execute query
201
+ const records = await sqlite.raw(sql, params);
202
+ // Limit results if specified
203
+ const limitedRecords = maxSkills ? records.slice(0, maxSkills) : records;
204
+ // Load skill content for each record
205
+ for (const record of limitedRecords){
206
+ try {
207
+ const skill = await this.loadSkillContent(record);
208
+ if (skill) {
209
+ skills.push(skill);
210
+ // Track cache hits
211
+ if (this.cache.has(skill.id)) {
212
+ cacheHits++;
213
+ } else {
214
+ cacheMisses++;
215
+ }
216
+ }
217
+ } catch (error) {
218
+ this.logger.error('Failed to load skill content', error, {
219
+ skillId: record.id
220
+ });
221
+ }
222
+ }
223
+ return {
224
+ skills,
225
+ cacheHits,
226
+ cacheMisses
227
+ };
228
+ } catch (error) {
229
+ this.logger.error('Failed to load agent skills from database', error, {
230
+ agentType,
231
+ taskContext
232
+ });
233
+ return {
234
+ skills: [],
235
+ cacheHits: 0,
236
+ cacheMisses: 0
237
+ };
238
+ }
239
+ }
240
+ /**
241
+ * Load skill content from file with caching and validation
242
+ */ async loadSkillContent(record) {
243
+ // Check cache first
244
+ const cached = this.getCachedSkill(record.id);
245
+ if (cached) {
246
+ // Validate cached entry against database hash
247
+ const validation = this.validator.validateCachedEntry(cached, record.content_hash);
248
+ if (validation.isValid) {
249
+ // Update last accessed time
250
+ this.updateCacheAccess(record.id);
251
+ return {
252
+ id: record.id,
253
+ name: record.name,
254
+ version: record.version,
255
+ content: cached.content,
256
+ contentHash: cached.contentHash,
257
+ namespace: record.namespace,
258
+ priority: record.priority,
259
+ tags: record.tags ? record.tags.split(',') : []
260
+ };
261
+ }
262
+ // Cache invalid - remove it
263
+ this.logger.debug('Cache invalidated', {
264
+ skillId: record.id,
265
+ reason: validation.reason
266
+ });
267
+ this.cache.delete(record.id);
268
+ }
269
+ // Load from file
270
+ const skillPath = path.isAbsolute(record.file_path) ? record.file_path : path.join(this.skillsBasePath, record.file_path);
271
+ if (!fs.existsSync(skillPath)) {
272
+ this.logger.error('Skill file not found', undefined, {
273
+ skillId: record.id,
274
+ filePath: skillPath
275
+ });
276
+ return null;
277
+ }
278
+ const content = await fs.promises.readFile(skillPath, 'utf-8');
279
+ // Validate file content hash
280
+ const actualHash = this.validator.computeHash(content);
281
+ if (actualHash !== record.content_hash) {
282
+ this.logger.warn('Skill content hash mismatch', {
283
+ skillId: record.id,
284
+ expectedHash: record.content_hash,
285
+ actualHash
286
+ });
287
+ // Note: We still return the skill but log the discrepancy
288
+ // In production, you might want to reject or update the database
289
+ }
290
+ // Cache the skill
291
+ this.setCachedSkill(record.id, content, record.content_hash);
292
+ return {
293
+ id: record.id,
294
+ name: record.name,
295
+ version: record.version,
296
+ content,
297
+ contentHash: record.content_hash,
298
+ namespace: record.namespace,
299
+ priority: record.priority,
300
+ tags: record.tags ? record.tags.split(',') : []
301
+ };
302
+ }
303
+ /**
304
+ * Get cached skill if valid
305
+ */ getCachedSkill(skillId) {
306
+ const entry = this.cache.get(skillId);
307
+ if (!entry) {
308
+ return null;
309
+ }
310
+ // Check TTL
311
+ const now = new Date();
312
+ if (now > entry.data.validUntil) {
313
+ this.cache.delete(skillId);
314
+ return null;
315
+ }
316
+ return entry.data;
317
+ }
318
+ /**
319
+ * Set cached skill
320
+ */ setCachedSkill(skillId, content, contentHash) {
321
+ // Evict oldest entry if cache is full
322
+ if (this.cache.size >= this.cacheMaxSize) {
323
+ this.evictOldestEntry();
324
+ }
325
+ const cacheEntry = this.validator.createCacheEntry(skillId, content, this.cacheTTLMinutes);
326
+ // Override contentHash if provided (from database)
327
+ if (contentHash) {
328
+ cacheEntry.contentHash = contentHash;
329
+ }
330
+ this.cache.set(skillId, {
331
+ data: cacheEntry,
332
+ lastAccessed: new Date()
333
+ });
334
+ }
335
+ /**
336
+ * Update cache access time for LRU tracking
337
+ */ updateCacheAccess(skillId) {
338
+ const entry = this.cache.get(skillId);
339
+ if (entry) {
340
+ entry.lastAccessed = new Date();
341
+ }
342
+ }
343
+ /**
344
+ * Evict oldest cache entry (LRU)
345
+ */ evictOldestEntry() {
346
+ let oldestKey = null;
347
+ let oldestTime = null;
348
+ for (const [key, entry] of this.cache.entries()){
349
+ if (!oldestTime || entry.lastAccessed < oldestTime) {
350
+ oldestKey = key;
351
+ oldestTime = entry.lastAccessed;
352
+ }
353
+ }
354
+ if (oldestKey) {
355
+ this.cache.delete(oldestKey);
356
+ this.logger.debug('Evicted LRU cache entry', {
357
+ skillId: oldestKey
358
+ });
359
+ }
360
+ }
361
+ /**
362
+ * Clear cache
363
+ */ clearCache() {
364
+ this.cache.clear();
365
+ this.logger.info('Skill cache cleared');
366
+ }
367
+ /**
368
+ * Get cache statistics
369
+ */ getCacheStats() {
370
+ return {
371
+ size: this.cache.size,
372
+ maxSize: this.cacheMaxSize,
373
+ ttlMinutes: this.cacheTTLMinutes
374
+ };
375
+ }
376
+ /**
377
+ * Validate all cached entries against database
378
+ *
379
+ * Useful for cache integrity checks and monitoring.
380
+ *
381
+ * @returns Validation result with invalidated skill IDs
382
+ */ async validateCache() {
383
+ if (!this.dbService) {
384
+ this.logger.warn('Database service not configured - cannot validate cache');
385
+ return {
386
+ isValid: true,
387
+ invalidSkillIds: [],
388
+ validCount: 0,
389
+ invalidCount: 0,
390
+ durationMs: 0
391
+ };
392
+ }
393
+ const cachedEntries = Array.from(this.cache.values()).map((entry)=>entry.data);
394
+ const validation = await this.validator.validateCachedSkills(cachedEntries);
395
+ // Automatically invalidate entries with hash mismatches
396
+ if (!validation.isValid) {
397
+ for (const skillId of validation.invalidSkillIds){
398
+ this.cache.delete(skillId);
399
+ }
400
+ this.logger.info('Cache validation found and removed stale entries', {
401
+ invalidatedCount: validation.invalidCount,
402
+ invalidSkillIds: validation.invalidSkillIds,
403
+ durationMs: validation.durationMs
404
+ });
405
+ }
406
+ return validation;
407
+ }
408
+ /**
409
+ * Preload skills into cache (warm up)
410
+ */ async preloadSkills(skillIds) {
411
+ this.logger.info('Preloading skills', {
412
+ count: skillIds.length
413
+ });
414
+ const promises = skillIds.map(async (skillId)=>{
415
+ try {
416
+ const skillPath = path.join(this.skillsBasePath, skillId, 'SKILL.md');
417
+ if (fs.existsSync(skillPath)) {
418
+ const content = await fs.promises.readFile(skillPath, 'utf-8');
419
+ const contentHash = this.validator.computeHash(content);
420
+ this.setCachedSkill(skillId, content, contentHash);
421
+ }
422
+ } catch (error) {
423
+ this.logger.error('Failed to preload skill', error, {
424
+ skillId
425
+ });
426
+ }
427
+ });
428
+ await Promise.all(promises);
429
+ this.logger.info('Skill preload completed', {
430
+ cachedCount: this.cache.size
431
+ });
432
+ }
433
+ }
434
+ /**
435
+ * Singleton instance for global use
436
+ */ let globalLoader = null;
437
+ /**
438
+ * Get or create global skill loader instance
439
+ *
440
+ * @param dbService - Database service instance
441
+ * @param logger - Optional logger instance
442
+ * @returns Global loader instance
443
+ */ export function getGlobalLoader(dbService, logger) {
444
+ if (!globalLoader) {
445
+ globalLoader = new SkillLoader(dbService, logger);
446
+ }
447
+ return globalLoader;
448
+ }
449
+ /**
450
+ * Set global loader instance
451
+ *
452
+ * @param loader - Loader instance to use globally
453
+ */ export function setGlobalLoader(loader) {
454
+ globalLoader = loader;
455
+ }
456
+
457
+ //# sourceMappingURL=skill-loader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/cli/skill-loader.ts"],"sourcesContent":["/**\r\n * Skill Loader\r\n *\r\n * High-performance skill loading system with LRU caching and hash-based validation.\r\n * Provides contextual skill selection for agent prompt building.\r\n *\r\n * Performance targets:\r\n * - Cold load: <1s\r\n * - Warm load: <100ms\r\n * - Cache TTL: 5 minutes\r\n *\r\n * @module skill-loader\r\n */\r\n\r\nimport * as fs from 'fs';\r\nimport * as path from 'path';\r\nimport { DatabaseService } from '../lib/database-service.js';\r\nimport { createLogger, Logger } from '../lib/logging.js';\r\nimport { SkillsQueryBuilder, SkillRecord, BOOTSTRAP_SKILL_IDS } from '../db/skills-query.js';\r\nimport {\r\n SkillCacheValidator,\r\n CachedSkillEntry,\r\n ValidationResult,\r\n} from './skill-cache-validator.js';\r\n\r\n/**\r\n * Skill metadata with content\r\n */\r\nexport interface Skill {\r\n id: string;\r\n name: string;\r\n version: string;\r\n content: string;\r\n contentHash: string;\r\n namespace?: string;\r\n priority?: number;\r\n tags?: string[];\r\n}\r\n\r\n/**\r\n * Skill loader configuration options\r\n */\r\nexport interface SkillLoaderOptions {\r\n /** Agent type to load skills for */\r\n agentType: string;\r\n\r\n /** Optional task context keywords for contextual filtering */\r\n taskContext?: string[];\r\n\r\n /** Maximum number of skills to load (default: 20) */\r\n maxSkills?: number;\r\n\r\n /** Include bootstrap skills (default: true) */\r\n includeBootstrap?: boolean;\r\n\r\n /** CFN Loop phase for phase-specific skills */\r\n phase?: string;\r\n}\r\n\r\n/**\r\n * Load result with metadata\r\n */\r\nexport interface SkillLoadResult {\r\n skills: Skill[];\r\n loadTimeMs: number;\r\n cacheHitCount: number;\r\n cacheMissCount: number;\r\n cacheInvalidationCount: number;\r\n totalSkills: number;\r\n bootstrapCount: number;\r\n}\r\n\r\n/**\r\n * LRU Cache Entry\r\n */\r\ninterface LRUCacheEntry {\r\n data: CachedSkillEntry;\r\n lastAccessed: Date;\r\n}\r\n\r\n/**\r\n * Skill Loader\r\n *\r\n * Manages skill loading with LRU caching and hash-based validation.\r\n */\r\nexport class SkillLoader {\r\n private logger: Logger;\r\n private validator: SkillCacheValidator;\r\n private cache: Map<string, LRUCacheEntry>;\r\n private cacheMaxSize: number = 100;\r\n private cacheTTLMinutes: number = 5;\r\n private dbService?: DatabaseService;\r\n private skillsBasePath: string;\r\n\r\n constructor(\r\n dbService?: DatabaseService,\r\n logger?: Logger,\r\n skillsBasePath?: string\r\n ) {\r\n this.logger = logger ?? createLogger('skill-loader');\r\n this.dbService = dbService;\r\n this.validator = new SkillCacheValidator(this.logger, dbService);\r\n this.cache = new Map();\r\n this.skillsBasePath = skillsBasePath ?? path.join(process.cwd(), '.claude/skills');\r\n }\r\n\r\n /**\r\n * Load contextual skills for an agent\r\n *\r\n * Main entry point for skill loading with caching and validation.\r\n *\r\n * @param options - Skill loader options\r\n * @returns Load result with skills and metadata\r\n */\r\n async loadContextualSkills(options: SkillLoaderOptions): Promise<SkillLoadResult> {\r\n const startTime = Date.now();\r\n const {\r\n agentType,\r\n taskContext = [],\r\n maxSkills = 20,\r\n includeBootstrap = true,\r\n phase,\r\n } = options;\r\n\r\n this.logger.info('Loading contextual skills', {\r\n agentType,\r\n taskContext,\r\n maxSkills,\r\n includeBootstrap,\r\n phase,\r\n });\r\n\r\n const result: SkillLoadResult = {\r\n skills: [],\r\n loadTimeMs: 0,\r\n cacheHitCount: 0,\r\n cacheMissCount: 0,\r\n cacheInvalidationCount: 0,\r\n totalSkills: 0,\r\n bootstrapCount: 0,\r\n };\r\n\r\n try {\r\n // Validate cache integrity with bulk hash check (if database available)\r\n if (this.dbService && this.cache.size > 0) {\r\n const cachedEntries = Array.from(this.cache.values()).map((entry) => entry.data);\r\n const validation = await this.validator.validateCachedSkills(cachedEntries);\r\n\r\n if (!validation.isValid) {\r\n // Invalidate cache entries with hash mismatches\r\n for (const skillId of validation.invalidSkillIds) {\r\n this.cache.delete(skillId);\r\n result.cacheInvalidationCount++;\r\n }\r\n\r\n this.logger.warn('Cache invalidated due to hash mismatches', {\r\n invalidatedCount: validation.invalidCount,\r\n invalidSkillIds: validation.invalidSkillIds,\r\n validationDurationMs: validation.durationMs,\r\n });\r\n } else {\r\n this.logger.debug('Cache validation passed', {\r\n validCount: validation.validCount,\r\n validationDurationMs: validation.durationMs,\r\n });\r\n }\r\n }\r\n\r\n // Load bootstrap skills first (always included unless explicitly disabled)\r\n if (includeBootstrap) {\r\n const bootstrapSkills = await this.loadBootstrapSkills();\r\n result.skills.push(...bootstrapSkills);\r\n result.bootstrapCount = bootstrapSkills.length;\r\n }\r\n\r\n // Load agent-specific skills from database\r\n if (this.dbService) {\r\n const agentSkills = await this.loadAgentSkills(\r\n agentType,\r\n taskContext,\r\n phase,\r\n maxSkills - result.skills.length\r\n );\r\n\r\n // Track cache hits/misses from agent skill loading\r\n const { skills, cacheHits, cacheMisses } = agentSkills;\r\n result.skills.push(...skills);\r\n result.cacheHitCount = cacheHits;\r\n result.cacheMissCount = cacheMisses;\r\n } else {\r\n this.logger.warn('Database service not configured - loading bootstrap skills only');\r\n }\r\n\r\n result.totalSkills = result.skills.length;\r\n result.loadTimeMs = Date.now() - startTime;\r\n\r\n this.logger.info('Skills loaded successfully', {\r\n totalSkills: result.totalSkills,\r\n bootstrapSkills: result.bootstrapCount,\r\n agentSkills: result.totalSkills - result.bootstrapCount,\r\n cacheHits: result.cacheHitCount,\r\n cacheMisses: result.cacheMissCount,\r\n cacheInvalidations: result.cacheInvalidationCount,\r\n loadTimeMs: result.loadTimeMs,\r\n });\r\n\r\n // Log performance warning if exceeding targets\r\n if (result.loadTimeMs > 1000) {\r\n this.logger.warn('Skill loading exceeded 1s target', {\r\n loadTimeMs: result.loadTimeMs,\r\n target: 1000,\r\n });\r\n }\r\n\r\n return result;\r\n } catch (error) {\r\n this.logger.error('Failed to load skills', error as Error, {\r\n agentType,\r\n taskContext,\r\n });\r\n\r\n throw new Error(`Skill loading failed: ${(error as Error).message}`);\r\n }\r\n }\r\n\r\n /**\r\n * Load bootstrap skills (always included)\r\n *\r\n * Bootstrap skills are loaded from static files without database dependency.\r\n */\r\n private async loadBootstrapSkills(): Promise<Skill[]> {\r\n const skills: Skill[] = [];\r\n\r\n for (const skillId of BOOTSTRAP_SKILL_IDS) {\r\n try {\r\n // Check cache first\r\n const cached = this.getCachedSkill(skillId);\r\n\r\n if (cached) {\r\n skills.push({\r\n id: cached.skillId,\r\n name: skillId,\r\n version: '1.0.0',\r\n content: cached.content,\r\n contentHash: cached.contentHash,\r\n namespace: 'cfn',\r\n priority: 10,\r\n });\r\n continue;\r\n }\r\n\r\n // Load from file\r\n const skillPath = path.join(this.skillsBasePath, skillId, 'SKILL.md');\r\n\r\n if (!fs.existsSync(skillPath)) {\r\n this.logger.warn('Bootstrap skill file not found', { skillId, skillPath });\r\n continue;\r\n }\r\n\r\n const content = await fs.promises.readFile(skillPath, 'utf-8');\r\n const contentHash = this.validator.computeHash(content);\r\n\r\n // Cache the skill\r\n this.setCachedSkill(skillId, content, contentHash);\r\n\r\n skills.push({\r\n id: skillId,\r\n name: skillId,\r\n version: '1.0.0',\r\n content,\r\n contentHash,\r\n namespace: 'cfn',\r\n priority: 10,\r\n });\r\n } catch (error) {\r\n this.logger.error('Failed to load bootstrap skill', error as Error, { skillId });\r\n }\r\n }\r\n\r\n return skills;\r\n }\r\n\r\n /**\r\n * Load agent-specific skills from database\r\n */\r\n private async loadAgentSkills(\r\n agentType: string,\r\n taskContext: string[],\r\n phase?: string,\r\n maxSkills?: number\r\n ): Promise<{ skills: Skill[]; cacheHits: number; cacheMisses: number }> {\r\n if (!this.dbService) {\r\n return { skills: [], cacheHits: 0, cacheMisses: 0 };\r\n }\r\n\r\n const skills: Skill[] = [];\r\n let cacheHits = 0;\r\n let cacheMisses = 0;\r\n\r\n try {\r\n // Get SQLite adapter\r\n const sqlite = this.dbService.getAdapter('sqlite');\r\n\r\n // Build query\r\n const { sql, params } = SkillsQueryBuilder.getSkillsByAgentType(\r\n agentType,\r\n taskContext,\r\n phase\r\n );\r\n\r\n // Execute query\r\n const records = await sqlite.raw<SkillRecord[]>(sql, params);\r\n\r\n // Limit results if specified\r\n const limitedRecords = maxSkills ? records.slice(0, maxSkills) : records;\r\n\r\n // Load skill content for each record\r\n for (const record of limitedRecords) {\r\n try {\r\n const skill = await this.loadSkillContent(record);\r\n\r\n if (skill) {\r\n skills.push(skill);\r\n\r\n // Track cache hits\r\n if (this.cache.has(skill.id)) {\r\n cacheHits++;\r\n } else {\r\n cacheMisses++;\r\n }\r\n }\r\n } catch (error) {\r\n this.logger.error('Failed to load skill content', error as Error, {\r\n skillId: record.id,\r\n });\r\n }\r\n }\r\n\r\n return { skills, cacheHits, cacheMisses };\r\n } catch (error) {\r\n this.logger.error('Failed to load agent skills from database', error as Error, {\r\n agentType,\r\n taskContext,\r\n });\r\n\r\n return { skills: [], cacheHits: 0, cacheMisses: 0 };\r\n }\r\n }\r\n\r\n /**\r\n * Load skill content from file with caching and validation\r\n */\r\n private async loadSkillContent(record: SkillRecord): Promise<Skill | null> {\r\n // Check cache first\r\n const cached = this.getCachedSkill(record.id);\r\n\r\n if (cached) {\r\n // Validate cached entry against database hash\r\n const validation = this.validator.validateCachedEntry(\r\n cached,\r\n record.content_hash\r\n );\r\n\r\n if (validation.isValid) {\r\n // Update last accessed time\r\n this.updateCacheAccess(record.id);\r\n\r\n return {\r\n id: record.id,\r\n name: record.name,\r\n version: record.version,\r\n content: cached.content,\r\n contentHash: cached.contentHash,\r\n namespace: record.namespace,\r\n priority: record.priority,\r\n tags: record.tags ? record.tags.split(',') : [],\r\n };\r\n }\r\n\r\n // Cache invalid - remove it\r\n this.logger.debug('Cache invalidated', {\r\n skillId: record.id,\r\n reason: validation.reason,\r\n });\r\n this.cache.delete(record.id);\r\n }\r\n\r\n // Load from file\r\n const skillPath = path.isAbsolute(record.file_path)\r\n ? record.file_path\r\n : path.join(this.skillsBasePath, record.file_path);\r\n\r\n if (!fs.existsSync(skillPath)) {\r\n this.logger.error('Skill file not found', undefined, {\r\n skillId: record.id,\r\n filePath: skillPath,\r\n });\r\n return null;\r\n }\r\n\r\n const content = await fs.promises.readFile(skillPath, 'utf-8');\r\n\r\n // Validate file content hash\r\n const actualHash = this.validator.computeHash(content);\r\n\r\n if (actualHash !== record.content_hash) {\r\n this.logger.warn('Skill content hash mismatch', {\r\n skillId: record.id,\r\n expectedHash: record.content_hash,\r\n actualHash,\r\n });\r\n\r\n // Note: We still return the skill but log the discrepancy\r\n // In production, you might want to reject or update the database\r\n }\r\n\r\n // Cache the skill\r\n this.setCachedSkill(record.id, content, record.content_hash);\r\n\r\n return {\r\n id: record.id,\r\n name: record.name,\r\n version: record.version,\r\n content,\r\n contentHash: record.content_hash,\r\n namespace: record.namespace,\r\n priority: record.priority,\r\n tags: record.tags ? record.tags.split(',') : [],\r\n };\r\n }\r\n\r\n /**\r\n * Get cached skill if valid\r\n */\r\n private getCachedSkill(skillId: string): CachedSkillEntry | null {\r\n const entry = this.cache.get(skillId);\r\n\r\n if (!entry) {\r\n return null;\r\n }\r\n\r\n // Check TTL\r\n const now = new Date();\r\n if (now > entry.data.validUntil) {\r\n this.cache.delete(skillId);\r\n return null;\r\n }\r\n\r\n return entry.data;\r\n }\r\n\r\n /**\r\n * Set cached skill\r\n */\r\n private setCachedSkill(skillId: string, content: string, contentHash: string): void {\r\n // Evict oldest entry if cache is full\r\n if (this.cache.size >= this.cacheMaxSize) {\r\n this.evictOldestEntry();\r\n }\r\n\r\n const cacheEntry = this.validator.createCacheEntry(\r\n skillId,\r\n content,\r\n this.cacheTTLMinutes\r\n );\r\n\r\n // Override contentHash if provided (from database)\r\n if (contentHash) {\r\n cacheEntry.contentHash = contentHash;\r\n }\r\n\r\n this.cache.set(skillId, {\r\n data: cacheEntry,\r\n lastAccessed: new Date(),\r\n });\r\n }\r\n\r\n /**\r\n * Update cache access time for LRU tracking\r\n */\r\n private updateCacheAccess(skillId: string): void {\r\n const entry = this.cache.get(skillId);\r\n\r\n if (entry) {\r\n entry.lastAccessed = new Date();\r\n }\r\n }\r\n\r\n /**\r\n * Evict oldest cache entry (LRU)\r\n */\r\n private evictOldestEntry(): void {\r\n let oldestKey: string | null = null;\r\n let oldestTime: Date | null = null;\r\n\r\n for (const [key, entry] of this.cache.entries()) {\r\n if (!oldestTime || entry.lastAccessed < oldestTime) {\r\n oldestKey = key;\r\n oldestTime = entry.lastAccessed;\r\n }\r\n }\r\n\r\n if (oldestKey) {\r\n this.cache.delete(oldestKey);\r\n this.logger.debug('Evicted LRU cache entry', { skillId: oldestKey });\r\n }\r\n }\r\n\r\n /**\r\n * Clear cache\r\n */\r\n clearCache(): void {\r\n this.cache.clear();\r\n this.logger.info('Skill cache cleared');\r\n }\r\n\r\n /**\r\n * Get cache statistics\r\n */\r\n getCacheStats(): {\r\n size: number;\r\n maxSize: number;\r\n ttlMinutes: number;\r\n hitRate?: number;\r\n } {\r\n return {\r\n size: this.cache.size,\r\n maxSize: this.cacheMaxSize,\r\n ttlMinutes: this.cacheTTLMinutes,\r\n };\r\n }\r\n\r\n /**\r\n * Validate all cached entries against database\r\n *\r\n * Useful for cache integrity checks and monitoring.\r\n *\r\n * @returns Validation result with invalidated skill IDs\r\n */\r\n async validateCache(): Promise<{\r\n isValid: boolean;\r\n invalidSkillIds: string[];\r\n validCount: number;\r\n invalidCount: number;\r\n durationMs: number;\r\n }> {\r\n if (!this.dbService) {\r\n this.logger.warn('Database service not configured - cannot validate cache');\r\n return {\r\n isValid: true,\r\n invalidSkillIds: [],\r\n validCount: 0,\r\n invalidCount: 0,\r\n durationMs: 0,\r\n };\r\n }\r\n\r\n const cachedEntries = Array.from(this.cache.values()).map((entry) => entry.data);\r\n const validation = await this.validator.validateCachedSkills(cachedEntries);\r\n\r\n // Automatically invalidate entries with hash mismatches\r\n if (!validation.isValid) {\r\n for (const skillId of validation.invalidSkillIds) {\r\n this.cache.delete(skillId);\r\n }\r\n\r\n this.logger.info('Cache validation found and removed stale entries', {\r\n invalidatedCount: validation.invalidCount,\r\n invalidSkillIds: validation.invalidSkillIds,\r\n durationMs: validation.durationMs,\r\n });\r\n }\r\n\r\n return validation;\r\n }\r\n\r\n /**\r\n * Preload skills into cache (warm up)\r\n */\r\n async preloadSkills(skillIds: string[]): Promise<void> {\r\n this.logger.info('Preloading skills', { count: skillIds.length });\r\n\r\n const promises = skillIds.map(async (skillId) => {\r\n try {\r\n const skillPath = path.join(this.skillsBasePath, skillId, 'SKILL.md');\r\n\r\n if (fs.existsSync(skillPath)) {\r\n const content = await fs.promises.readFile(skillPath, 'utf-8');\r\n const contentHash = this.validator.computeHash(content);\r\n this.setCachedSkill(skillId, content, contentHash);\r\n }\r\n } catch (error) {\r\n this.logger.error('Failed to preload skill', error as Error, { skillId });\r\n }\r\n });\r\n\r\n await Promise.all(promises);\r\n\r\n this.logger.info('Skill preload completed', {\r\n cachedCount: this.cache.size,\r\n });\r\n }\r\n}\r\n\r\n/**\r\n * Singleton instance for global use\r\n */\r\nlet globalLoader: SkillLoader | null = null;\r\n\r\n/**\r\n * Get or create global skill loader instance\r\n *\r\n * @param dbService - Database service instance\r\n * @param logger - Optional logger instance\r\n * @returns Global loader instance\r\n */\r\nexport function getGlobalLoader(\r\n dbService?: DatabaseService,\r\n logger?: Logger\r\n): SkillLoader {\r\n if (!globalLoader) {\r\n globalLoader = new SkillLoader(dbService, logger);\r\n }\r\n return globalLoader;\r\n}\r\n\r\n/**\r\n * Set global loader instance\r\n *\r\n * @param loader - Loader instance to use globally\r\n */\r\nexport function setGlobalLoader(loader: SkillLoader): void {\r\n globalLoader = loader;\r\n}\r\n"],"names":["fs","path","createLogger","SkillsQueryBuilder","BOOTSTRAP_SKILL_IDS","SkillCacheValidator","SkillLoader","logger","validator","cache","cacheMaxSize","cacheTTLMinutes","dbService","skillsBasePath","Map","join","process","cwd","loadContextualSkills","options","startTime","Date","now","agentType","taskContext","maxSkills","includeBootstrap","phase","info","result","skills","loadTimeMs","cacheHitCount","cacheMissCount","cacheInvalidationCount","totalSkills","bootstrapCount","size","cachedEntries","Array","from","values","map","entry","data","validation","validateCachedSkills","isValid","skillId","invalidSkillIds","delete","warn","invalidatedCount","invalidCount","validationDurationMs","durationMs","debug","validCount","bootstrapSkills","loadBootstrapSkills","push","length","agentSkills","loadAgentSkills","cacheHits","cacheMisses","cacheInvalidations","target","error","Error","message","cached","getCachedSkill","id","name","version","content","contentHash","namespace","priority","skillPath","existsSync","promises","readFile","computeHash","setCachedSkill","sqlite","getAdapter","sql","params","getSkillsByAgentType","records","raw","limitedRecords","slice","record","skill","loadSkillContent","has","validateCachedEntry","content_hash","updateCacheAccess","tags","split","reason","isAbsolute","file_path","undefined","filePath","actualHash","expectedHash","get","validUntil","evictOldestEntry","cacheEntry","createCacheEntry","set","lastAccessed","oldestKey","oldestTime","key","entries","clearCache","clear","getCacheStats","maxSize","ttlMinutes","validateCache","preloadSkills","skillIds","count","Promise","all","cachedCount","globalLoader","getGlobalLoader","setGlobalLoader","loader"],"mappings":"AAAA;;;;;;;;;;;;CAYC,GAED,YAAYA,QAAQ,KAAK;AACzB,YAAYC,UAAU,OAAO;AAE7B,SAASC,YAAY,QAAgB,oBAAoB;AACzD,SAASC,kBAAkB,EAAeC,mBAAmB,QAAQ,wBAAwB;AAC7F,SACEC,mBAAmB,QAGd,6BAA6B;AAyDpC;;;;CAIC,GACD,OAAO,MAAMC;IACHC,OAAe;IACfC,UAA+B;IAC/BC,MAAkC;IAClCC,eAAuB,IAAI;IAC3BC,kBAA0B,EAAE;IAC5BC,UAA4B;IAC5BC,eAAuB;IAE/B,YACED,SAA2B,EAC3BL,MAAe,EACfM,cAAuB,CACvB;QACA,IAAI,CAACN,MAAM,GAAGA,UAAUL,aAAa;QACrC,IA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EAAEmC,SAAS;gBAE1D,IAAIhD,GAAGiF,UAAU,CAACD,YAAY;oBAC5B,MAAMJ,UAAU,MAAM5E,GAAGkF,QAAQ,CAACC,QAAQ,CAACH,WAAW;oBACtD,MAAMH,cAAc,IAAI,CAACrE,SAAS,CAAC4E,WAAW,CAACR;oBAC/C,IAAI,CAACS,cAAc,CAACrC,SAAS4B,SAASC;gBACxC;YACF,EAAE,OAAOT,OAAO;gBACd,IAAI,CAAC7D,MAAM,CAAC6D,KAAK,CAAC,2BAA2BA,OAAgB;oBAAEpB;gBAAQ;YACzE;QACF;QAEA,MAAMmF,QAAQC,GAAG,CAAClD;QAElB,IAAI,CAAC3E,MAAM,CAACqB,IAAI,CAAC,2BAA2B;YAC1CyG,aAAa,IAAI,CAAC5H,KAAK,CAAC4B,IAAI;QAC9B;IACF;AACF;AAEA;;CAEC,GACD,IAAIiG,eAAmC;AAEvC;;;;;;CAMC,GACD,OAAO,SAASC,gBACd3H,SAA2B,EAC3BL,MAAe;IAEf,IAAI,CAAC+H,cAAc;QACjBA,eAAe,IAAIhI,YAAYM,WAAWL;IAC5C;IACA,OAAO+H;AACT;AAEA;;;;CAIC,GACD,OAAO,SAASE,gBAAgBC,MAAmB;IACjDH,eAAeG;AACjB"}
@@ -1,9 +1,9 @@
1
1
  import Redis from 'ioredis';
2
2
  import { performance } from 'perf_hooks';
3
3
  import { v4 as uuidv4 } from 'uuid';
4
- import { generateTraceId } from './types/event-bus.types';
4
+ import { generateTraceId } from './types/event-bus.types.js';
5
5
  // TODO: Import WASM JSON parser when available
6
- // import { parseJsonWithWasm } from '../wasm/json-parser';
6
+ // import { parseJsonWithWasm } from '../wasm/json-parser.js';
7
7
  export class QEEventBus {
8
8
  redis;
9
9
  topics = new Set();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/coordination/event-bus.ts"],"sourcesContent":["import Redis from 'ioredis';\r\nimport { performance } from 'perf_hooks';\r\nimport { v4 as uuidv4 } from 'uuid';\r\n\r\nimport {\r\n EventTopic,\r\n TraceId,\r\n EventMetadata,\r\n AgentLifecycleEvent,\r\n EventSubscription,\r\n QEEventBusConfig,\r\n IEventRouter,\r\n IEventDispatcher,\r\n generateTraceId\r\n} from './types/event-bus.types';\r\n\r\n// TODO: Import WASM JSON parser when available\r\n// import { parseJsonWithWasm } from '../wasm/json-parser';\r\n\r\nexport class QEEventBus implements IEventRouter, IEventDispatcher {\r\n private redis: Redis;\r\n private topics: Set<EventTopic> = new Set();\r\n private subscriptions: Map<string, EventSubscription> = new Map();\r\n private config: QEEventBusConfig;\r\n\r\n constructor(config: QEEventBusConfig = {}) {\r\n this.config = {\r\n redisUrl: process.env.CFN_REDIS_URL || process.env.REDIS_URL || `redis://${process.env.CFN_REDIS_HOST || 'cfn-redis'}:${process.env.CFN_REDIS_PORT || 6379}`,\r\n performanceThreshold: 100, // ms\r\n ...config\r\n };\r\n\r\n this.redis = new Redis(this.config.redisUrl);\r\n\r\n // Set up Redis pub/sub listener\r\n this.initRedisSubscription();\r\n }\r\n\r\n private initRedisSubscription() {\r\n const redisSub = new Redis(this.config.redisUrl);\r\n redisSub.on('message', async (topic, message) => {\r\n const startTime = performance.now();\r\n\r\n try {\r\n const { payload, metadata } = JSON.parse(message);\r\n const matchingSubscriptions = Array.from(this.subscriptions.values())\r\n .filter(sub => sub.topic === topic);\r\n\r\n await Promise.all(matchingSubscriptions.map(sub =>\r\n sub.callback(payload, metadata)\r\n ));\r\n } catch (error) {\r\n console.error(`Event processing error for topic ${topic}:`, error);\r\n }\r\n\r\n const processingTime = performance.now() - startTime;\r\n if (processingTime > (this.config.performanceThreshold || 100)) {\r\n console.warn(`Event processing for ${topic} took ${processingTime}ms`);\r\n }\r\n });\r\n\r\n // Subscribe to all currently registered topics\r\n this.topics.forEach(topic => redisSub.subscribe(topic));\r\n }\r\n\r\n // Event Router Implementation\r\n registerTopic(topic: EventTopic): void {\r\n if (!this.topics.has(topic)) {\r\n this.topics.add(topic);\r\n this.redis.subscribe(topic);\r\n }\r\n }\r\n\r\n removeTopic(topic: EventTopic): void {\r\n if (this.topics.has(topic)) {\r\n this.topics.delete(topic);\r\n this.redis.unsubscribe(topic);\r\n }\r\n }\r\n\r\n listTopics(): EventTopic[] {\r\n return Array.from(this.topics);\r\n }\r\n\r\n // Event Dispatcher Implementation\r\n async publish(\r\n topic: EventTopic,\r\n payload: unknown,\r\n traceId?: TraceId\r\n ): Promise<void> {\r\n if (!this.topics.has(topic)) {\r\n this.registerTopic(topic);\r\n }\r\n\r\n const metadata: EventMetadata = {\r\n timestamp: Date.now(),\r\n traceId: traceId || generateTraceId()\r\n };\r\n\r\n // TODO: Integrate WASM JSON parsing when available\r\n // const parsedPayload = this.config.wasmParserPath\r\n // ? parseJsonWithWasm(payload)\r\n // : payload;\r\n\r\n const message = JSON.stringify({ payload, metadata });\r\n await this.redis.publish(topic, message);\r\n }\r\n\r\n subscribe(\r\n topic: EventTopic,\r\n callback: EventSubscription['callback']\r\n ): string {\r\n const subscriptionId = uuidv4();\r\n const subscription: EventSubscription = {\r\n id: subscriptionId,\r\n topic,\r\n callback\r\n };\r\n\r\n this.subscriptions.set(subscriptionId, subscription);\r\n\r\n // Ensure topic is registered\r\n this.registerTopic(topic);\r\n\r\n return subscriptionId;\r\n }\r\n\r\n unsubscribe(subscriptionId: string): void {\r\n this.subscriptions.delete(subscriptionId);\r\n }\r\n\r\n // Agent Lifecycle Event Tracking\r\n trackLifecycleEvent(\r\n event: AgentLifecycleEvent,\r\n traceId?: TraceId\r\n ): Promise<void> {\r\n return this.publish(\r\n 'agent-lifecycle',\r\n event,\r\n traceId\r\n );\r\n }\r\n\r\n // Graceful Shutdown\r\n async shutdown(): Promise<void> {\r\n await this.redis.quit();\r\n }\r\n}\r\n\r\n// Singleton export for global access\r\nexport const eventBus = new QEEventBus();"],"names":["Redis","performance","v4","uuidv4","generateTraceId","QEEventBus","redis","topics","Set","subscriptions","Map","config","redisUrl","process","env","CFN_REDIS_URL","REDIS_URL","CFN_REDIS_HOST","CFN_REDIS_PORT","performanceThreshold","initRedisSubscription","redisSub","on","topic","message","startTime","now","payload","metadata","JSON","parse","matchingSubscriptions","Array","from","values","filter","sub","Promise","all","map","callback","error","console","processingTime","warn","forEach","subscribe","registerTopic","has","add","removeTopic","delete","unsubscribe","listTopics","publish","traceId","timestamp","Date","stringify","subscriptionId","subscription","id","set","trackLifecycleEvent","event","shutdown","quit","eventBus"],"mappings":"AAAA,OAAOA,WAAW,UAAU;AAC5B,SAASC,WAAW,QAAQ,aAAa;AACzC,SAASC,MAAMC,MAAM,QAAQ,OAAO;AAEpC,SASEC,eAAe,QACV,0BAA0B;AAEjC,+CAA+C;AAC/C,2DAA2D;AAE3D,OAAO,MAAMC;IACHC,MAAa;IACbC,SAA0B,IAAIC,MAAM;IACpCC,gBAAgD,IAAIC,MAAM;IAC1DC,OAAyB;IAEjC,YAAYA,SAA2B,CAAC,CAAC,CAAE;QACzC,IAAI,CAACA,MAAM,GAAG;YACZC,UAAUC,QAAQC,GAAG,CAACC,aAAa,IAAIF,QAAQC,GAAG,CAACE,SAAS,IAAI,CAAC,QAAQ,EAAEH,QAAQC,GAAG,CAACG,cAAc,IAAI,YAAY,CAAC,EAAEJ,QAAQC,GAAG,CAACI,cAAc,IAAI,MAAM;YAC5JC,sBAAsB;YACtB,GAAGR,MAAM;QACX;QAEA,IAAI,CAACL,KAAK,GAAG,IAAIN,MAAM,IAAI,CAACW,MAAM,CAACC,QAAQ;QAE3C,gCAAgC;QAChC,IAAI,CAACQ,qBAAqB;IAC5B;IAEQA,wBAAwB;QAC9B,MAAMC,WAAW,IAAIrB,MAAM,IAAI,CAACW,MAAM,CAACC,QAAQ;QAC/CS,SAASC,EAAE,CAAC,WAAW,OAAOC,OAAOC;YACnC,MAAMC,YAAYxB,YAAYyB,GAAG;YAEjC,IAAI;gBACF,MAAM,EAAEC,OAAO,EAAEC,QAAQ,EAAE,GAAGC,KAAKC,KAAK,CAACN;gBACzC,MAAMO,wBAAwBC,MAAMC,IAAI,C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MAAM,CAACyC,GAAG,CAACzB,QAAQ;YAC3B,IAAI,CAACwB,aAAa,CAACxB;QACrB;QAEA,MAAMK,WAA0B;YAC9B4B,WAAWC,KAAK/B,GAAG;YACnB6B,SAASA,WAAWnD;QACtB;QAEA,mDAAmD;QACnD,mDAAmD;QACnD,iCAAiC;QACjC,eAAe;QAEf,MAAMoB,UAAUK,KAAK6B,SAAS,CAAC;YAAE/B;YAASC;QAAS;QACnD,MAAM,IAAI,CAACtB,KAAK,CAACgD,OAAO,CAAC/B,OAAOC;IAClC;IAEAsB,UACEvB,KAAiB,EACjBiB,QAAuC,EAC/B;QACR,MAAMmB,iBAAiBxD;QACvB,MAAMyD,eAAkC;YACtCC,IAAIF;YACJpC;YACAiB;QACF;QAEA,IAAI,CAAC/B,aAAa,CAACqD,GAAG,CAACH,gBAAgBC;QAEvC,6BAA6B;QAC7B,IAAI,CAACb,aAAa,CAACxB;QAEnB,OAAOoC;IACT;IAEAP,YAAYO,cAAsB,EAAQ;QACxC,IAAI,CAAClD,aAAa,CAAC0C,MAAM,CAACQ;IAC5B;IAEA,iCAAiC;IACjCI,oBACEC,KAA0B,EAC1BT,OAAiB,EACF;QACf,OAAO,IAAI,CAACD,OAAO,CACjB,mBACAU,OACAT;IAEJ;IAEA,oBAAoB;IACpB,MAAMU,WAA0B;QAC9B,MAAM,IAAI,CAAC3D,KAAK,CAAC4D,IAAI;IACvB;AACF;AAEA,qCAAqC;AACrC,OAAO,MAAMC,WAAW,IAAI9D,aAAa"}
1
+ {"version":3,"sources":["../../src/coordination/event-bus.ts"],"sourcesContent":["import Redis from 'ioredis';\r\nimport { performance } from 'perf_hooks';\r\nimport { v4 as uuidv4 } from 'uuid';\r\n\r\nimport {\r\n EventTopic,\r\n TraceId,\r\n EventMetadata,\r\n AgentLifecycleEvent,\r\n EventSubscription,\r\n QEEventBusConfig,\r\n IEventRouter,\r\n IEventDispatcher,\r\n generateTraceId\r\n} from './types/event-bus.types.js';\r\n\r\n// TODO: Import WASM JSON parser when available\r\n// import { parseJsonWithWasm } from '../wasm/json-parser.js';\r\n\r\nexport class QEEventBus implements IEventRouter, IEventDispatcher {\r\n private redis: Redis;\r\n private topics: Set<EventTopic> = new Set();\r\n private subscriptions: Map<string, EventSubscription> = new Map();\r\n private config: QEEventBusConfig;\r\n\r\n constructor(config: QEEventBusConfig = {}) {\r\n this.config = {\r\n redisUrl: process.env.CFN_REDIS_URL || process.env.REDIS_URL || `redis://${process.env.CFN_REDIS_HOST || 'cfn-redis'}:${process.env.CFN_REDIS_PORT || 6379}`,\r\n performanceThreshold: 100, // ms\r\n ...config\r\n };\r\n\r\n this.redis = new Redis(this.config.redisUrl);\r\n\r\n // Set up Redis pub/sub listener\r\n this.initRedisSubscription();\r\n }\r\n\r\n private initRedisSubscription() {\r\n const redisSub = new Redis(this.config.redisUrl);\r\n redisSub.on('message', async (topic, message) => {\r\n const startTime = performance.now();\r\n\r\n try {\r\n const { payload, metadata } = JSON.parse(message);\r\n const matchingSubscriptions = Array.from(this.subscriptions.values())\r\n .filter(sub => sub.topic === topic);\r\n\r\n await Promise.all(matchingSubscriptions.map(sub =>\r\n sub.callback(payload, metadata)\r\n ));\r\n } catch (error) {\r\n console.error(`Event processing error for topic ${topic}:`, error);\r\n }\r\n\r\n const processingTime = performance.now() - startTime;\r\n if (processingTime > (this.config.performanceThreshold || 100)) {\r\n console.warn(`Event processing for ${topic} took ${processingTime}ms`);\r\n }\r\n });\r\n\r\n // Subscribe to all currently registered topics\r\n this.topics.forEach(topic => redisSub.subscribe(topic));\r\n }\r\n\r\n // Event Router Implementation\r\n registerTopic(topic: EventTopic): void {\r\n if (!this.topics.has(topic)) {\r\n this.topics.add(topic);\r\n this.redis.subscribe(topic);\r\n }\r\n }\r\n\r\n removeTopic(topic: EventTopic): void {\r\n if (this.topics.has(topic)) {\r\n this.topics.delete(topic);\r\n this.redis.unsubscribe(topic);\r\n }\r\n }\r\n\r\n listTopics(): EventTopic[] {\r\n return Array.from(this.topics);\r\n }\r\n\r\n // Event Dispatcher Implementation\r\n async publish(\r\n topic: EventTopic,\r\n payload: unknown,\r\n traceId?: TraceId\r\n ): Promise<void> {\r\n if (!this.topics.has(topic)) {\r\n this.registerTopic(topic);\r\n }\r\n\r\n const metadata: EventMetadata = {\r\n timestamp: Date.now(),\r\n traceId: traceId || generateTraceId()\r\n };\r\n\r\n // TODO: Integrate WASM JSON parsing when available\r\n // const parsedPayload = this.config.wasmParserPath\r\n // ? parseJsonWithWasm(payload)\r\n // : payload;\r\n\r\n const message = JSON.stringify({ payload, metadata });\r\n await this.redis.publish(topic, message);\r\n }\r\n\r\n subscribe(\r\n topic: EventTopic,\r\n callback: EventSubscription['callback']\r\n ): string {\r\n const subscriptionId = uuidv4();\r\n const subscription: EventSubscription = {\r\n id: subscriptionId,\r\n topic,\r\n callback\r\n };\r\n\r\n this.subscriptions.set(subscriptionId, subscription);\r\n\r\n // Ensure topic is registered\r\n this.registerTopic(topic);\r\n\r\n return subscriptionId;\r\n }\r\n\r\n unsubscribe(subscriptionId: string): void {\r\n this.subscriptions.delete(subscriptionId);\r\n }\r\n\r\n // Agent Lifecycle Event Tracking\r\n trackLifecycleEvent(\r\n event: AgentLifecycleEvent,\r\n traceId?: TraceId\r\n ): Promise<void> {\r\n return this.publish(\r\n 'agent-lifecycle',\r\n event,\r\n traceId\r\n );\r\n }\r\n\r\n // Graceful Shutdown\r\n async shutdown(): Promise<void> {\r\n await this.redis.quit();\r\n }\r\n}\r\n\r\n// Singleton export for global access\r\nexport const eventBus = new QEEventBus();"],"names":["Redis","performance","v4","uuidv4","generateTraceId","QEEventBus","redis","topics","Set","subscriptions","Map","config","redisUrl","process","env","CFN_REDIS_URL","REDIS_URL","CFN_REDIS_HOST","CFN_REDIS_PORT","performanceThreshold","initRedisSubscription","redisSub","on","topic","message","startTime","now","payload","metadata","JSON","parse","matchingSubscriptions","Array","from","values","filter","sub","Promise","all","map","callback","error","console","processingTime","warn","forEach","subscribe","registerTopic","has","add","removeTopic","delete","unsubscribe","listTopics","publish","traceId","timestamp","Date","stringify","subscriptionId","subscription","id","set","trackLifecycleEvent","event","shutdown","quit","eventBus"],"mappings":"AAAA,OAAOA,WAAW,UAAU;AAC5B,SAASC,WAAW,QAAQ,aAAa;AACzC,SAASC,MAAMC,MAAM,QAAQ,OAAO;AAEpC,SASEC,eAAe,QACV,6BAA6B;AAEpC,+CAA+C;AAC/C,8DAA8D;AAE9D,OAAO,MAAMC;IACHC,MAAa;IACbC,SAA0B,IAAIC,MAAM;IACpCC,gBAAgD,IAAIC,MAAM;IAC1DC,OAAyB;IAEjC,YAAYA,SAA2B,CAAC,CAAC,CAAE;QACzC,IAAI,CAACA,MAAM,GAAG;YACZC,UAAUC,QAAQC,GAAG,CAACC,aAAa,IAAIF,QAAQC,GAAG,CAACE,SAAS,IAAI,CAAC,QAAQ,EAAEH,QAAQC,GAAG,CAACG,cAAc,IAAI,YAAY,CAAC,EAAEJ,QAAQC,GAAG,CAACI,cAAc,IAAI,MAAM;YAC5JC,sBAAsB;YACtB,GAAGR,MAAM;QACX;QAEA,IAAI,CAACL,KAAK,GAAG,IAAIN,MAAM,IAAI,CAACW,MAAM,CAACC,QAAQ;QAE3C,gCAAgC;QAChC,IAAI,CAACQ,qBAAqB;IAC5B;IAEQA,wBAAwB;QAC9B,MAAMC,WAAW,IAAIrB,MAAM,IAAI,CAACW,MAAM,CAACC,QAAQ;QAC/CS,SAASC,EAAE,CAAC,WAAW,OAAOC,OAAOC;YACnC,MAAMC,YAAYxB,YAAYyB,GAAG;YAEjC,IAAI;gBACF,MAAM,EAAEC,OAAO,EAAEC,QAAQ,EAAE,GAAGC,KAAKC,KAAK,CAACN;gBACzC,MAAMO,wBAAwBC,MAAMC,IAAI,CAAC,IAAI,CAACxB,aAAa,CAACyB,MAAM,IAC/DC,MAAM,CAACC,CAAAA,MAAOA,IAAIb,KAAK,KAAKA;gBAE/B,MAAMc,QAAQC,GAAG,CAACP,sBAAsBQ,GAAG,CAACH,CAAAA,MAC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DAAmD;QACnD,mDAAmD;QACnD,iCAAiC;QACjC,eAAe;QAEf,MAAMoB,UAAUK,KAAK6B,SAAS,CAAC;YAAE/B;YAASC;QAAS;QACnD,MAAM,IAAI,CAACtB,KAAK,CAACgD,OAAO,CAAC/B,OAAOC;IAClC;IAEAsB,UACEvB,KAAiB,EACjBiB,QAAuC,EAC/B;QACR,MAAMmB,iBAAiBxD;QACvB,MAAMyD,eAAkC;YACtCC,IAAIF;YACJpC;YACAiB;QACF;QAEA,IAAI,CAAC/B,aAAa,CAACqD,GAAG,CAACH,gBAAgBC;QAEvC,6BAA6B;QAC7B,IAAI,CAACb,aAAa,CAACxB;QAEnB,OAAOoC;IACT;IAEAP,YAAYO,cAAsB,EAAQ;QACxC,IAAI,CAAClD,aAAa,CAAC0C,MAAM,CAACQ;IAC5B;IAEA,iCAAiC;IACjCI,oBACEC,KAA0B,EAC1BT,OAAiB,EACF;QACf,OAAO,IAAI,CAACD,OAAO,CACjB,mBACAU,OACAT;IAEJ;IAEA,oBAAoB;IACpB,MAAMU,WAA0B;QAC9B,MAAM,IAAI,CAAC3D,KAAK,CAAC4D,IAAI;IACvB;AACF;AAEA,qCAAqC;AACrC,OAAO,MAAMC,WAAW,IAAI9D,aAAa"}
@@ -1,4 +1,4 @@
1
- import { ResourceTier } from './types/fleet-manager.types';
1
+ import { ResourceTier } from './types/fleet-manager.types.js';
2
2
  export class FleetManager {
3
3
  redis;
4
4
  agentRegistry;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/coordination/fleet-manager.ts"],"sourcesContent":["import Redis from 'ioredis';\nimport { AgentRegistry } from '../agents/agent-registry';\nimport { DependencyTracker } from '../lifecycle/dependency-tracker';\nimport { TransparencyMiddleware } from './transparency-middleware';\nimport {\n AgentId,\n AgentLifecycleStatus\n} from '../agents/agent-registry.types';\nimport {\n ResourceTier,\n AgentResourceRequirements,\n AgentPerformanceMetrics,\n AgentResourceAllocation,\n FleetManagerConfig,\n LoadBalancingResult\n} from './types/fleet-manager.types';\n\nexport class FleetManager {\n private redis: Redis;\n private agentRegistry: AgentRegistry;\n private dependencyTracker: DependencyTracker;\n private transparencyMiddleware: TransparencyMiddleware;\n private config: FleetManagerConfig;\n\n private agentAllocations: Map<AgentId, AgentResourceAllocation>;\n private performanceHistory: Map<AgentId, AgentPerformanceMetrics[]>;\n\n constructor(\n redisClient: Redis,\n agentRegistry: AgentRegistry,\n dependencyTracker: DependencyTracker,\n transparencyMiddleware: TransparencyMiddleware,\n config?: Partial<FleetManagerConfig>\n ) {\n this.redis = redisClient;\n this.agentRegistry = agentRegistry;\n this.dependencyTracker = dependencyTracker;\n this.transparencyMiddleware = transparencyMiddleware;\n\n this.config = {\n maxAgents: config?.maxAgents ?? 1000,\n resourceAllocationStrategy: config?.resourceAllocationStrategy ?? 'least-loaded'\n };\n\n this.agentAllocations = new Map();\n this.performanceHistory = new Map();\n }\n\n async registerAgent(\n agentId: AgentId,\n tier: ResourceTier = ResourceTier.Shared\n ): Promise<boolean> {\n // Check if agent registry allows registration\n const registrationResult = await this.agentRegistry.registerAgent(agentId);\n\n if (!registrationResult) {\n this.transparencyMiddleware.logEvent('fleet_manager', 'agent_registration_failed', { agentId });\n return false;\n }\n\n // Validate agent count\n const currentAgentCount = this.agentAllocations.size;\n if (currentAgentCount >= this.config.maxAgents) {\n this.transparencyMiddleware.logEvent('fleet_manager', 'max_agents_reached', {\n currentCount: currentAgentCount,\n maxAgents: this.config.maxAgents\n });\n return false;\n }\n\n // Store agent allocation\n const defaultResources: AgentResourceRequirements = this.getDefaultResourcesByTier(tier);\n const initialMetrics: AgentPerformanceMetrics = this.createInitialMetrics();\n\n const allocation: AgentResourceAllocation = {\n agentId,\n tier,\n allocatedResources: defaultResources,\n currentMetrics: initialMetrics\n };\n\n this.agentAllocations.set(agentId, allocation);\n this.performanceHistory.set(agentId, [initialMetrics]);\n\n // Redis tracking\n await this.redis.hset(`fleet:agents:${agentId}`, 'tier', tier);\n await this.redis.sadd('fleet:registered_agents', agentId);\n\n this.transparencyMiddleware.logEvent('fleet_manager', 'agent_registered', {\n agentId,\n tier\n });\n\n return true;\n }\n\n async allocateResources(\n agentId: AgentId,\n requirements: AgentResourceRequirements\n ): Promise<boolean> {\n const currentAllocation = this.agentAllocations.get(agentId);\n if (!currentAllocation) {\n return false;\n }\n\n // Validate resource allocation based on tier\n const isAllocationValid = this.validateResourceAllocation(\n currentAllocation.tier,\n requirements\n );\n\n if (!isAllocationValid) {\n this.transparencyMiddleware.logEvent('fleet_manager', 'resource_allocation_denied', {\n agentId,\n requirements,\n tier: currentAllocation.tier\n });\n return false;\n }\n\n // Update allocation\n currentAllocation.allocatedResources = requirements;\n this.agentAllocations.set(agentId, currentAllocation);\n\n // Redis tracking\n await this.redis.hset(`fleet:agents:${agentId}`, 'resources', JSON.stringify(requirements));\n\n this.transparencyMiddleware.logEvent('fleet_manager', 'resources_allocated', {\n agentId,\n requirements\n });\n\n return true;\n }\n\n async getPerformanceMetrics(agentId: AgentId): Promise<AgentPerformanceMetrics | null> {\n const history = this.performanceHistory.get(agentId);\n return history ? history[history.length - 1] : null;\n }\n\n async balanceLoad(agents: AgentId[]): Promise<LoadBalancingResult> {\n const loadBalancingResult: LoadBalancingResult = {\n rebalancedAgents: [],\n migrationPlan: {}\n };\n\n switch (this.config.resourceAllocationStrategy) {\n case 'least-loaded':\n return this.leastLoadedBalancing(agents);\n case 'round-robin':\n return this.roundRobinBalancing(agents);\n case 'weighted':\n return this.weightedBalancing(agents);\n default:\n return loadBalancingResult;\n }\n }\n\n private getDefaultResourcesByTier(tier: ResourceTier): AgentResourceRequirements {\n switch (tier) {\n case ResourceTier.Shared:\n return { cpu: 2, memory: 4, network: 50, storageIO: 100 };\n case ResourceTier.Dedicated:\n return { cpu: 8, memory: 16, network: 200, storageIO: 500 };\n case ResourceTier.Premium:\n return { cpu: 16, memory: 32, network: 500, storageIO: 1000 };\n }\n }\n\n private createInitialMetrics(): AgentPerformanceMetrics {\n return {\n cpuUtilization: 0,\n memoryUsage: 0,\n networkThroughput: 0,\n storageIOPS: 0,\n timestamp: Date.now()\n };\n }\n\n private validateResourceAllocation(\n tier: ResourceTier,\n requirements: AgentResourceRequirements\n ): boolean {\n const tierLimits = this.getDefaultResourcesByTier(tier);\n return (\n requirements.cpu <= tierLimits.cpu &&\n requirements.memory <= tierLimits.memory &&\n requirements.network <= tierLimits.network &&\n requirements.storageIO <= tierLimits.storageIO\n );\n }\n\n private leastLoadedBalancing(agents: AgentId[]): LoadBalancingResult {\n // Placeholder implementation\n return {\n rebalancedAgents: [],\n migrationPlan: {}\n };\n }\n\n private roundRobinBalancing(agents: AgentId[]): LoadBalancingResult {\n // Placeholder implementation\n return {\n rebalancedAgents: [],\n migrationPlan: {}\n };\n }\n\n private weightedBalancing(agents: AgentId[]): LoadBalancingResult {\n // Placeholder implementation\n return {\n rebalancedAgents: [],\n migrationPlan: {}\n };\n }\n}\n"],"names":["ResourceTier","FleetManager","redis","agentRegistry","dependencyTracker","transparencyMiddleware","config","agentAllocations","performanceHistory","redisClient","maxAgents","resourceAllocationStrategy","Map","registerAgent","agentId","tier","Shared","registrationResult","logEvent","currentAgentCount","size","currentCount","defaultResources","getDefaultResourcesByTier","initialMetrics","createInitialMetrics","allocation","allocatedResources","currentMetrics","set","hset","sadd","allocateResources","requirements","currentAllocation","get","isAllocationValid","validateResourceAllocation","JSON","stringify","getPerformanceMetrics","history","length","balanceLoad","agents","loadBalancingResult","rebalancedAgents","migrationPlan","leastLoadedBalancing","roundRobinBalancing","weightedBalancing","cpu","memory","network","storageIO","Dedicated","Premium","cpuUtilization","memoryUsage","networkThroughput","storageIOPS","timestamp","Date","now","tierLimits"],"mappings":"AAQA,SACEA,YAAY,QAMP,8BAA8B;AAErC,OAAO,MAAMC;IACHC,MAAa;IACbC,cAA6B;IAC7BC,kBAAqC;IACrCC,uBAA+C;IAC/CC,OAA2B;IAE3BC,iBAAwD;IACxDC,mBAA4D;IAEpE,YACEC,WAAkB,EAClBN,aAA4B,EAC5BC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EAAE;YACpBC,eAAe,CAAC;QAClB;IACF;IAEQG,kBAAkBN,MAAiB,EAAuB;QAChE,6BAA6B;QAC7B,OAAO;YACLE,kBAAkB,EAAE;YACpBC,eAAe,CAAC;QAClB;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/coordination/fleet-manager.ts"],"sourcesContent":["import Redis from 'ioredis';\nimport { AgentRegistry } from '../agents/agent-registry.js';\nimport { DependencyTracker } from '../lifecycle/dependency-tracker.js';\nimport { TransparencyMiddleware } from './transparency-middleware.js';\nimport {\n AgentId,\n AgentLifecycleStatus\n} from '../agents/agent-registry.types.js';\nimport {\n ResourceTier,\n AgentResourceRequirements,\n AgentPerformanceMetrics,\n AgentResourceAllocation,\n FleetManagerConfig,\n LoadBalancingResult\n} from './types/fleet-manager.types.js';\n\nexport class FleetManager {\n private redis: Redis;\n private agentRegistry: AgentRegistry;\n private dependencyTracker: DependencyTracker;\n private transparencyMiddleware: TransparencyMiddleware;\n private config: FleetManagerConfig;\n\n private agentAllocations: Map<AgentId, AgentResourceAllocation>;\n private performanceHistory: Map<AgentId, AgentPerformanceMetrics[]>;\n\n constructor(\n redisClient: Redis,\n agentRegistry: AgentRegistry,\n dependencyTracker: DependencyTracker,\n transparencyMiddleware: TransparencyMiddleware,\n config?: Partial<FleetManagerConfig>\n ) {\n this.redis = redisClient;\n this.agentRegistry = agentRegistry;\n this.dependencyTracker = dependencyTracker;\n this.transparencyMiddleware = transparencyMiddleware;\n\n this.config = {\n maxAgents: config?.maxAgents ?? 1000,\n resourceAllocationStrategy: config?.resourceAllocationStrategy ?? 'least-loaded'\n };\n\n this.agentAllocations = new Map();\n this.performanceHistory = new Map();\n }\n\n async registerAgent(\n agentId: AgentId,\n tier: ResourceTier = ResourceTier.Shared\n ): Promise<boolean> {\n // Check if agent registry allows registration\n const registrationResult = await this.agentRegistry.registerAgent(agentId);\n\n if (!registrationResult) {\n this.transparencyMiddleware.logEvent('fleet_manager', 'agent_registration_failed', { agentId });\n return false;\n }\n\n // Validate agent count\n const currentAgentCount = this.agentAllocations.size;\n if (currentAgentCount >= this.config.maxAgents) {\n this.transparencyMiddleware.logEvent('fleet_manager', 'max_agents_reached', {\n currentCount: currentAgentCount,\n maxAgents: this.config.maxAgents\n });\n return false;\n }\n\n // Store agent allocation\n const defaultResources: AgentResourceRequirements = this.getDefaultResourcesByTier(tier);\n const initialMetrics: AgentPerformanceMetrics = this.createInitialMetrics();\n\n const allocation: AgentResourceAllocation = {\n agentId,\n tier,\n allocatedResources: defaultResources,\n currentMetrics: initialMetrics\n };\n\n this.agentAllocations.set(agentId, allocation);\n this.performanceHistory.set(agentId, [initialMetrics]);\n\n // Redis tracking\n await this.redis.hset(`fleet:agents:${agentId}`, 'tier', tier);\n await this.redis.sadd('fleet:registered_agents', agentId);\n\n this.transparencyMiddleware.logEvent('fleet_manager', 'agent_registered', {\n agentId,\n tier\n });\n\n return true;\n }\n\n async allocateResources(\n agentId: AgentId,\n requirements: AgentResourceRequirements\n ): Promise<boolean> {\n const currentAllocation = this.agentAllocations.get(agentId);\n if (!currentAllocation) {\n return false;\n }\n\n // Validate resource allocation based on tier\n const isAllocationValid = this.validateResourceAllocation(\n currentAllocation.tier,\n requirements\n );\n\n if (!isAllocationValid) {\n this.transparencyMiddleware.logEvent('fleet_manager', 'resource_allocation_denied', {\n agentId,\n requirements,\n tier: currentAllocation.tier\n });\n return false;\n }\n\n // Update allocation\n currentAllocation.allocatedResources = requirements;\n this.agentAllocations.set(agentId, currentAllocation);\n\n // Redis tracking\n await this.redis.hset(`fleet:agents:${agentId}`, 'resources', JSON.stringify(requirements));\n\n this.transparencyMiddleware.logEvent('fleet_manager', 'resources_allocated', {\n agentId,\n requirements\n });\n\n return true;\n }\n\n async getPerformanceMetrics(agentId: AgentId): Promise<AgentPerformanceMetrics | null> {\n const history = this.performanceHistory.get(agentId);\n return history ? history[history.length - 1] : null;\n }\n\n async balanceLoad(agents: AgentId[]): Promise<LoadBalancingResult> {\n const loadBalancingResult: LoadBalancingResult = {\n rebalancedAgents: [],\n migrationPlan: {}\n };\n\n switch (this.config.resourceAllocationStrategy) {\n case 'least-loaded':\n return this.leastLoadedBalancing(agents);\n case 'round-robin':\n return this.roundRobinBalancing(agents);\n case 'weighted':\n return this.weightedBalancing(agents);\n default:\n return loadBalancingResult;\n }\n }\n\n private getDefaultResourcesByTier(tier: ResourceTier): AgentResourceRequirements {\n switch (tier) {\n case ResourceTier.Shared:\n return { cpu: 2, memory: 4, network: 50, storageIO: 100 };\n case ResourceTier.Dedicated:\n return { cpu: 8, memory: 16, network: 200, storageIO: 500 };\n case ResourceTier.Premium:\n return { cpu: 16, memory: 32, network: 500, storageIO: 1000 };\n }\n }\n\n private createInitialMetrics(): AgentPerformanceMetrics {\n return {\n cpuUtilization: 0,\n memoryUsage: 0,\n networkThroughput: 0,\n storageIOPS: 0,\n timestamp: Date.now()\n };\n }\n\n private validateResourceAllocation(\n tier: ResourceTier,\n requirements: AgentResourceRequirements\n ): boolean {\n const tierLimits = this.getDefaultResourcesByTier(tier);\n return (\n requirements.cpu <= tierLimits.cpu &&\n requirements.memory <= tierLimits.memory &&\n requirements.network <= tierLimits.network &&\n requirements.storageIO <= tierLimits.storageIO\n );\n }\n\n private leastLoadedBalancing(agents: AgentId[]): LoadBalancingResult {\n // Placeholder implementation\n return {\n rebalancedAgents: [],\n migrationPlan: {}\n };\n }\n\n private roundRobinBalancing(agents: AgentId[]): LoadBalancingResult {\n // Placeholder implementation\n return {\n rebalancedAgents: [],\n migrationPlan: {}\n };\n }\n\n private weightedBalancing(agents: AgentId[]): LoadBalancingResult {\n // Placeholder implementation\n return {\n rebalancedAgents: [],\n migrationPlan: {}\n };\n }\n}\n"],"names":["ResourceTier","FleetManager","redis","agentRegistry","dependencyTracker","transparencyMiddleware","config","agentAllocations","performanceHistory","redisClient","maxAgents","resourceAllocationStrategy","Map","registerAgent","agentId","tier","Shared","registrationResult","logEvent","currentAgentCount","size","currentCount","defaultResources","getDefaultResourcesByTier","initialMetrics","createInitialMetrics","allocation","allocatedResources","currentMetrics","set","hset","sadd","allocateResources","requirements","currentAllocation","get","isAllocationValid","validateResourceAllocation","JSON","stringify","getPerformanceMetrics","history","length","balanceLoad","agents","loadBalancingResult","rebalancedAgents","migrationPlan","leastLoadedBalancing","roundRobinBalancing","weightedBalancing","cpu","memory","network","storageIO","Dedicated","Premium","cpuUtilization","memoryUsage","networkThroughput","storageIOPS","timestamp","Date","now","tierLimits"],"mappings":"AAQA,SACEA,YAAY,QAMP,iCAAiC;AAExC,OAAO,MAAMC;IACHC,MAAa;IACbC,cAA6B;IAC7BC,kBAAqC;IACrCC,uBAA+C;IAC/CC,OAA2B;IAE3BC,iBAAwD;IACxDC,mBAA4D;IAEpE,YACEC,WAAkB,EAClBN,aAA4B,EAC5BC,iBAAoC,EACpCC,sBAA8C,EAC9CC,MAAoC,CACpC;QACA,IAAI,CAACJ,KAAK,GAAGO;QACb,IAAI,CAACN,aAAa,GAAGA;QACrB,IAAI,CAACC,iBAAiB,GAAGA;QACzB,IAAI,CAACC,sBAAsB,GAAGA;QAE9B,IAAI,CAACC,MAAM,GAAG;YACZI,WAAWJ,QAAQI,aAAa;YAChCC,4BAA4BL,QAAQK,8BAA8B;QACpE;QAEA,IAAI,CAACJ,gBAAgB,GAAG,IAAIK;QAC5B,IAAI,CAACJ,kBAAkB,GAAG,IAAII;IAChC;IAEA,MAAMC,cACJC,OAAgB,EAChBC,OAAqBf,aAAagB,MAAM,EACtB;QAClB,8CAA8C;QAC9C,MAAMC,qBAAqB,MAAM,IAAI,CAACd,aAAa,CAACU,aAAa,CAACC;QAElE,IAAI,CAACG,oBAAoB;YACvB,IAAI,CAACZ,sBAAsB,CAACa,QAAQ,CAAC,iBAAiB,6BAA6B;gBAAEJ;YAAQ;YAC7F,OAAO;QACT;QAEA,uBAAuB;QACvB,MAAMK,oBAAoB,IAAI,CAACZ,gBAAgB,CAACa,IAAI;QACpD,IAAID,qBAAqB,IAAI,CAACb,MAAM,CAACI,SAAS,E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