snow-flow 1.4.49 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (595) hide show
  1. package/.claude/helpers/github-setup.sh +28 -0
  2. package/.claude/helpers/quick-start.sh +19 -0
  3. package/.claude/helpers/setup-mcp.sh +18 -0
  4. package/.claude/settings.local.json +33 -0
  5. package/.claude-flow/metrics/system-metrics.json +1992 -0
  6. package/.env.example +21 -0
  7. package/.roo/README.md +402 -0
  8. package/.roo/mcp-list.txt +257 -0
  9. package/.roo/mcp.json +32 -0
  10. package/.roo/workflows/basic-tdd.json +32 -0
  11. package/.roomodes +201 -0
  12. package/README.md +114 -628
  13. package/activate-mcp.sh +15 -0
  14. package/dist/cli.js.bak +2052 -0
  15. package/manual-register-mcp.js +134 -0
  16. package/mcp-wrapper.sh +12 -0
  17. package/package.json +2 -2
  18. package/scripts/create-env.js +6 -1
  19. package/scripts/reset-mcp-servers.js +246 -0
  20. package/scripts/update-version.js +31 -0
  21. package/src/agents/README.md +192 -0
  22. package/src/agents/base-agent.ts +251 -0
  23. package/src/agents/coordinator.ts +971 -0
  24. package/src/agents/index.ts +18 -0
  25. package/src/agents/queen-403-handler.ts +230 -0
  26. package/src/agents/queen-agent.ts +1399 -0
  27. package/src/agents/script-writer-agent.ts +769 -0
  28. package/src/agents/security-agent.ts +726 -0
  29. package/src/agents/widget-creator-agent.ts +568 -0
  30. package/src/api/error-handling.ts +1758 -0
  31. package/src/api/natural-language-mapper.ts +630 -0
  32. package/src/api/performance-optimizer.ts +891 -0
  33. package/src/api/transaction-manager.ts +754 -0
  34. package/src/cli/deploy-artifact.ts +304 -0
  35. package/src/cli/snow-flow-cli-integration.ts +434 -0
  36. package/src/cli.ts +4455 -0
  37. package/src/cli.ts.bak +5616 -0
  38. package/src/compliance/advanced-compliance-system.ts +1268 -0
  39. package/src/compliance/index.ts +19 -0
  40. package/src/config/snow-flow-config.ts +1019 -0
  41. package/src/documentation/index.ts +16 -0
  42. package/src/documentation/self-documenting-system.ts +1421 -0
  43. package/src/dynamic-version.ts +44 -0
  44. package/src/healing/index.ts +20 -0
  45. package/src/healing/self-healing-system.ts +1435 -0
  46. package/src/health/README.md +161 -0
  47. package/src/health/system-health.ts +995 -0
  48. package/src/index.ts +60 -0
  49. package/src/intelligence/acl-analyzer.ts +377 -0
  50. package/src/intelligence/auto-resolution-engine.ts +643 -0
  51. package/src/intelligence/gap-analysis-engine.ts +488 -0
  52. package/src/intelligence/manual-instructions-generator.ts +744 -0
  53. package/src/intelligence/mcp-coverage-analyzer.ts +708 -0
  54. package/src/intelligence/multi-pass-requirements-analyzer.ts +603 -0
  55. package/src/intelligence/performance-recommendations-engine.ts +1223 -0
  56. package/src/intelligence/requirements-analyzer.ts +1148 -0
  57. package/src/intelligence/task-analyzer.ts +628 -0
  58. package/src/managers/scope-manager.ts +555 -0
  59. package/src/mcp/advanced/servicenow-advanced-features-mcp.ts +16110 -0
  60. package/src/mcp/base-mcp-server.ts +660 -0
  61. package/src/mcp/http-transport-wrapper.ts +426 -0
  62. package/src/mcp/service-discovery-client.ts +312 -0
  63. package/src/mcp/servicenow-automation-mcp-refactored.ts +678 -0
  64. package/src/mcp/servicenow-automation-mcp.ts +838 -0
  65. package/src/mcp/servicenow-deployment-mcp-refactored.ts +1292 -0
  66. package/src/mcp/servicenow-deployment-mcp.ts +7244 -0
  67. package/src/mcp/servicenow-graph-memory-mcp-refactored.ts +721 -0
  68. package/src/mcp/servicenow-graph-memory-mcp.ts +832 -0
  69. package/src/mcp/servicenow-integration-mcp-refactored.ts +655 -0
  70. package/src/mcp/servicenow-integration-mcp.ts +819 -0
  71. package/src/mcp/servicenow-intelligent-mcp-refactored.ts +977 -0
  72. package/src/mcp/servicenow-intelligent-mcp.ts +4638 -0
  73. package/src/mcp/servicenow-mcp-server.ts +728 -0
  74. package/src/mcp/servicenow-memory-mcp.ts +474 -0
  75. package/src/mcp/servicenow-operations-mcp-refactored.ts +1995 -0
  76. package/src/mcp/servicenow-operations-mcp.ts +3384 -0
  77. package/src/mcp/servicenow-platform-development-mcp-refactored.ts +611 -0
  78. package/src/mcp/servicenow-platform-development-mcp.ts +970 -0
  79. package/src/mcp/servicenow-progressive-indexer.ts +370 -0
  80. package/src/mcp/servicenow-reporting-analytics-mcp-refactored.ts +695 -0
  81. package/src/mcp/servicenow-reporting-analytics-mcp.ts +1123 -0
  82. package/src/mcp/servicenow-security-compliance-mcp-refactored.ts +642 -0
  83. package/src/mcp/servicenow-security-compliance-mcp.ts +1157 -0
  84. package/src/mcp/servicenow-update-set-mcp-refactored.ts +751 -0
  85. package/src/mcp/servicenow-update-set-mcp.ts +811 -0
  86. package/src/mcp/shared/agent-context-provider.ts +365 -0
  87. package/src/mcp/shared/base-mcp-server.ts +2463 -0
  88. package/src/mcp/shared/mcp-memory-manager.ts +540 -0
  89. package/src/mcp/shared/mcp-resource-manager.ts +367 -0
  90. package/src/mcp/snow-flow-mcp.ts +911 -0
  91. package/src/mcp/start-all-mcp-servers.ts +102 -0
  92. package/src/mcp/start-servicenow-mcp.ts +67 -0
  93. package/src/monitoring/enhanced-monitoring-system.ts +1345 -0
  94. package/src/monitoring/performance-tracker.ts +777 -0
  95. package/src/optimization/cost-optimization-engine.ts +1125 -0
  96. package/src/optimization/index.ts +10 -0
  97. package/src/queen/README.md +403 -0
  98. package/src/queen/agent-factory.ts +574 -0
  99. package/src/queen/index.ts +94 -0
  100. package/src/queen/mcp-execution-bridge.ts +681 -0
  101. package/src/queen/neural-learning.ts +319 -0
  102. package/src/queen/parallel-agent-engine.ts +848 -0
  103. package/src/queen/queen-memory-system.ts +490 -0
  104. package/src/queen/queen-memory.ts +456 -0
  105. package/src/queen/servicenow-queen.ts +1029 -0
  106. package/src/queen/types.ts +87 -0
  107. package/src/rollback/smart-rollback-system.ts +866 -0
  108. package/src/schemas/deployment.schema.json +58 -0
  109. package/src/schemas/flow.schema.json +79 -0
  110. package/src/schemas/widget.schema.json +72 -0
  111. package/src/snow-flow-system.ts +541 -0
  112. package/src/sparc/sparc-help.ts +49 -0
  113. package/src/sparc/team-sparc.ts +88 -0
  114. package/src/strategies/global-scope-strategy.ts +736 -0
  115. package/src/templates/base/application.template.json +45 -0
  116. package/src/templates/base/business_rule.template.json +33 -0
  117. package/src/templates/base/script_include.template.json +18 -0
  118. package/src/templates/base/table.template.json +64 -0
  119. package/src/templates/base/widget.template.json +25 -0
  120. package/src/templates/patterns/composite.incident-management.template.json +140 -0
  121. package/src/templates/patterns/widget.dashboard.template.json +238 -0
  122. package/src/templates/patterns/widget.datatable.template.json +292 -0
  123. package/src/testing/integration-test-suite.ts +1276 -0
  124. package/src/types/index.ts +183 -0
  125. package/src/types/neo4j-driver.d.ts +23 -0
  126. package/src/types/servicenow.types.ts +307 -0
  127. package/src/types/snow-flow.types.ts +186 -0
  128. package/src/types/todo.types.ts +70 -0
  129. package/src/utils/action-type-cache.ts +286 -0
  130. package/src/utils/agent-detector.ts +573 -0
  131. package/src/utils/artifact-tracker.ts +379 -0
  132. package/src/utils/dependency-detector.ts +233 -0
  133. package/src/utils/deployment-metadata-handler.ts +518 -0
  134. package/src/utils/error-recovery.ts +680 -0
  135. package/src/utils/logger.ts +60 -0
  136. package/src/utils/mcp-auth-middleware.ts +262 -0
  137. package/src/utils/mcp-config-manager.ts +270 -0
  138. package/src/utils/mcp-server-manager.ts +446 -0
  139. package/src/utils/mcp-tool-registry.ts +298 -0
  140. package/src/utils/migrate-snow-flow.ts +98 -0
  141. package/src/utils/oauth-html-templates.ts +188 -0
  142. package/src/utils/scope-utils.ts +443 -0
  143. package/src/utils/servicenow-client.ts +3321 -0
  144. package/src/utils/servicenow-id-generator.ts +181 -0
  145. package/src/utils/snow-memory-manager.ts +605 -0
  146. package/src/utils/snow-oauth.ts +797 -0
  147. package/src/utils/template-engine.ts +463 -0
  148. package/src/utils/theme-manager.ts +295 -0
  149. package/src/utils/unified-auth-store.ts +222 -0
  150. package/src/utils/update-set-importer.ts +422 -0
  151. package/src/utils/update-set-xml-packager.ts +371 -0
  152. package/src/utils/widget-template-generator.ts +1744 -0
  153. package/src/version.ts +1950 -0
  154. package/.claude/commands/memory/README.md +0 -9
  155. package/dist/agents/app-creator.agent.d.ts.map +0 -1
  156. package/dist/agents/app-creator.agent.js.map +0 -1
  157. package/dist/agents/base/base-snow-agent.d.ts.map +0 -1
  158. package/dist/agents/base/base-snow-agent.js.map +0 -1
  159. package/dist/agents/base-agent.d.ts.map +0 -1
  160. package/dist/agents/base-agent.js.map +0 -1
  161. package/dist/agents/base-snow-agent.d.ts.map +0 -1
  162. package/dist/agents/base-snow-agent.js.map +0 -1
  163. package/dist/agents/coordinator.d.ts.map +0 -1
  164. package/dist/agents/coordinator.js.map +0 -1
  165. package/dist/agents/flow-builder-agent.d.ts.map +0 -1
  166. package/dist/agents/flow-builder-agent.js.map +0 -1
  167. package/dist/agents/index.d.ts.map +0 -1
  168. package/dist/agents/index.js.map +0 -1
  169. package/dist/agents/queen-403-handler.d.ts.map +0 -1
  170. package/dist/agents/queen-403-handler.js.map +0 -1
  171. package/dist/agents/queen-agent-example.d.ts.map +0 -1
  172. package/dist/agents/queen-agent-example.js.map +0 -1
  173. package/dist/agents/queen-agent.d.ts.map +0 -1
  174. package/dist/agents/queen-agent.js.map +0 -1
  175. package/dist/agents/queen-agent.test.d.ts.map +0 -1
  176. package/dist/agents/queen-agent.test.js.map +0 -1
  177. package/dist/agents/script-generator.agent.d.ts.map +0 -1
  178. package/dist/agents/script-generator.agent.js.map +0 -1
  179. package/dist/agents/script-writer-agent.d.ts.map +0 -1
  180. package/dist/agents/script-writer-agent.js.map +0 -1
  181. package/dist/agents/security-agent.d.ts.map +0 -1
  182. package/dist/agents/security-agent.js.map +0 -1
  183. package/dist/agents/specialists/automation-specialist.agent.d.ts.map +0 -1
  184. package/dist/agents/specialists/automation-specialist.agent.js.map +0 -1
  185. package/dist/agents/specialists/data-specialist.agent.d.ts.map +0 -1
  186. package/dist/agents/specialists/data-specialist.agent.js.map +0 -1
  187. package/dist/agents/specialists/integration-specialist.agent.d.ts.map +0 -1
  188. package/dist/agents/specialists/integration-specialist.agent.js.map +0 -1
  189. package/dist/agents/specialists/reporting-specialist.agent.d.ts.map +0 -1
  190. package/dist/agents/specialists/reporting-specialist.agent.js.map +0 -1
  191. package/dist/agents/specialists/security-specialist.agent.d.ts.map +0 -1
  192. package/dist/agents/specialists/security-specialist.agent.js.map +0 -1
  193. package/dist/agents/teams/adaptive/adaptive-coordinator.agent.d.ts.map +0 -1
  194. package/dist/agents/teams/adaptive/adaptive-coordinator.agent.js.map +0 -1
  195. package/dist/agents/teams/base-team.d.ts.map +0 -1
  196. package/dist/agents/teams/base-team.js.map +0 -1
  197. package/dist/agents/teams/team-types.d.ts.map +0 -1
  198. package/dist/agents/teams/team-types.js.map +0 -1
  199. package/dist/agents/teams/widget/widget-architect.agent.d.ts.map +0 -1
  200. package/dist/agents/teams/widget/widget-architect.agent.js.map +0 -1
  201. package/dist/agents/teams/widget/widget-backend.agent.d.ts.map +0 -1
  202. package/dist/agents/teams/widget/widget-backend.agent.js.map +0 -1
  203. package/dist/agents/teams/widget/widget-frontend.agent.d.ts.map +0 -1
  204. package/dist/agents/teams/widget/widget-frontend.agent.js.map +0 -1
  205. package/dist/agents/teams/widget/widget-platform.agent.d.ts.map +0 -1
  206. package/dist/agents/teams/widget/widget-platform.agent.js.map +0 -1
  207. package/dist/agents/teams/widget/widget-uiux.agent.d.ts.map +0 -1
  208. package/dist/agents/teams/widget/widget-uiux.agent.js.map +0 -1
  209. package/dist/agents/test-agent.d.ts.map +0 -1
  210. package/dist/agents/test-agent.js.map +0 -1
  211. package/dist/agents/test-agents.d.ts.map +0 -1
  212. package/dist/agents/test-agents.js.map +0 -1
  213. package/dist/agents/ui-builder.agent.d.ts.map +0 -1
  214. package/dist/agents/ui-builder.agent.js.map +0 -1
  215. package/dist/agents/widget-builder.agent.d.ts.map +0 -1
  216. package/dist/agents/widget-builder.agent.js.map +0 -1
  217. package/dist/agents/widget-creator-agent.d.ts.map +0 -1
  218. package/dist/agents/widget-creator-agent.js.map +0 -1
  219. package/dist/agents/workflow-designer.agent.d.ts.map +0 -1
  220. package/dist/agents/workflow-designer.agent.js.map +0 -1
  221. package/dist/api/error-handling.d.ts.map +0 -1
  222. package/dist/api/error-handling.js.map +0 -1
  223. package/dist/api/flow-designer-api.d.ts.map +0 -1
  224. package/dist/api/flow-designer-api.js.map +0 -1
  225. package/dist/api/natural-language-mapper.d.ts.map +0 -1
  226. package/dist/api/natural-language-mapper.js.map +0 -1
  227. package/dist/api/performance-optimizer.d.ts.map +0 -1
  228. package/dist/api/performance-optimizer.js.map +0 -1
  229. package/dist/api/transaction-manager.d.ts.map +0 -1
  230. package/dist/api/transaction-manager.js.map +0 -1
  231. package/dist/assembly/team-assembler.d.ts.map +0 -1
  232. package/dist/assembly/team-assembler.js.map +0 -1
  233. package/dist/cli/deploy-artifact.d.ts.map +0 -1
  234. package/dist/cli/deploy-artifact.js.map +0 -1
  235. package/dist/cli/snow-flow-cli-integration.d.ts.map +0 -1
  236. package/dist/cli/snow-flow-cli-integration.js.map +0 -1
  237. package/dist/cli.d.ts.map +0 -1
  238. package/dist/cli.js.map +0 -1
  239. package/dist/compliance/advanced-compliance-system.d.ts.map +0 -1
  240. package/dist/compliance/advanced-compliance-system.js.map +0 -1
  241. package/dist/compliance/index.d.ts.map +0 -1
  242. package/dist/compliance/index.js.map +0 -1
  243. package/dist/config/snow-flow-config.d.ts.map +0 -1
  244. package/dist/config/snow-flow-config.js.map +0 -1
  245. package/dist/documentation/index.d.ts.map +0 -1
  246. package/dist/documentation/index.js.map +0 -1
  247. package/dist/documentation/self-documenting-system.d.ts.map +0 -1
  248. package/dist/documentation/self-documenting-system.js.map +0 -1
  249. package/dist/dynamic-version.d.ts.map +0 -1
  250. package/dist/dynamic-version.js.map +0 -1
  251. package/dist/healing/index.d.ts.map +0 -1
  252. package/dist/healing/index.js.map +0 -1
  253. package/dist/healing/self-healing-system.d.ts.map +0 -1
  254. package/dist/healing/self-healing-system.js.map +0 -1
  255. package/dist/health/system-health.d.ts.map +0 -1
  256. package/dist/health/system-health.js.map +0 -1
  257. package/dist/index.d.ts.map +0 -1
  258. package/dist/index.js.map +0 -1
  259. package/dist/intelligence/acl-analyzer.d.ts.map +0 -1
  260. package/dist/intelligence/acl-analyzer.js.map +0 -1
  261. package/dist/intelligence/auto-resolution-engine.d.ts.map +0 -1
  262. package/dist/intelligence/auto-resolution-engine.js.map +0 -1
  263. package/dist/intelligence/gap-analysis-engine.d.ts.map +0 -1
  264. package/dist/intelligence/gap-analysis-engine.js.map +0 -1
  265. package/dist/intelligence/manual-instructions-generator.d.ts.map +0 -1
  266. package/dist/intelligence/manual-instructions-generator.js.map +0 -1
  267. package/dist/intelligence/mcp-coverage-analyzer.d.ts.map +0 -1
  268. package/dist/intelligence/mcp-coverage-analyzer.js.map +0 -1
  269. package/dist/intelligence/multi-pass-requirements-analyzer.d.ts.map +0 -1
  270. package/dist/intelligence/multi-pass-requirements-analyzer.js.map +0 -1
  271. package/dist/intelligence/performance-recommendations-engine.d.ts.map +0 -1
  272. package/dist/intelligence/performance-recommendations-engine.js.map +0 -1
  273. package/dist/intelligence/requirements-analyzer.d.ts.map +0 -1
  274. package/dist/intelligence/requirements-analyzer.js.map +0 -1
  275. package/dist/intelligence/task-analyzer.d.ts.map +0 -1
  276. package/dist/intelligence/task-analyzer.js.map +0 -1
  277. package/dist/managers/scope-manager.d.ts.map +0 -1
  278. package/dist/managers/scope-manager.js.map +0 -1
  279. package/dist/mcp/advanced/servicenow-advanced-features-mcp.d.ts.map +0 -1
  280. package/dist/mcp/advanced/servicenow-advanced-features-mcp.js.map +0 -1
  281. package/dist/mcp/base-mcp-server.d.ts.map +0 -1
  282. package/dist/mcp/base-mcp-server.js.map +0 -1
  283. package/dist/mcp/example-refactored-server.d.ts.map +0 -1
  284. package/dist/mcp/example-refactored-server.js.map +0 -1
  285. package/dist/mcp/http-transport-wrapper.d.ts.map +0 -1
  286. package/dist/mcp/http-transport-wrapper.js.map +0 -1
  287. package/dist/mcp/mcp-wrapper.d.ts.map +0 -1
  288. package/dist/mcp/mcp-wrapper.js.map +0 -1
  289. package/dist/mcp/service-discovery-client.d.ts.map +0 -1
  290. package/dist/mcp/service-discovery-client.js.map +0 -1
  291. package/dist/mcp/servicenow-automation-mcp-refactored.d.ts.map +0 -1
  292. package/dist/mcp/servicenow-automation-mcp-refactored.js.map +0 -1
  293. package/dist/mcp/servicenow-automation-mcp.d.ts.map +0 -1
  294. package/dist/mcp/servicenow-automation-mcp.js.map +0 -1
  295. package/dist/mcp/servicenow-deployment-mcp-refactored.d.ts.map +0 -1
  296. package/dist/mcp/servicenow-deployment-mcp-refactored.js.map +0 -1
  297. package/dist/mcp/servicenow-deployment-mcp.d.ts.map +0 -1
  298. package/dist/mcp/servicenow-deployment-mcp.js.map +0 -1
  299. package/dist/mcp/servicenow-flow-composer-mcp-refactored.d.ts.map +0 -1
  300. package/dist/mcp/servicenow-flow-composer-mcp-refactored.js.map +0 -1
  301. package/dist/mcp/servicenow-flow-composer-mcp.d.ts.map +0 -1
  302. package/dist/mcp/servicenow-flow-composer-mcp.js.map +0 -1
  303. package/dist/mcp/servicenow-graph-memory-mcp-refactored.d.ts.map +0 -1
  304. package/dist/mcp/servicenow-graph-memory-mcp-refactored.js.map +0 -1
  305. package/dist/mcp/servicenow-graph-memory-mcp.d.ts.map +0 -1
  306. package/dist/mcp/servicenow-graph-memory-mcp.js.map +0 -1
  307. package/dist/mcp/servicenow-integration-mcp-refactored.d.ts.map +0 -1
  308. package/dist/mcp/servicenow-integration-mcp-refactored.js.map +0 -1
  309. package/dist/mcp/servicenow-integration-mcp.d.ts.map +0 -1
  310. package/dist/mcp/servicenow-integration-mcp.js.map +0 -1
  311. package/dist/mcp/servicenow-intelligent-mcp-refactored.d.ts.map +0 -1
  312. package/dist/mcp/servicenow-intelligent-mcp-refactored.js.map +0 -1
  313. package/dist/mcp/servicenow-intelligent-mcp.d.ts.map +0 -1
  314. package/dist/mcp/servicenow-intelligent-mcp.js.map +0 -1
  315. package/dist/mcp/servicenow-mcp-server.d.ts.map +0 -1
  316. package/dist/mcp/servicenow-mcp-server.js.map +0 -1
  317. package/dist/mcp/servicenow-memory-mcp.d.ts.map +0 -1
  318. package/dist/mcp/servicenow-memory-mcp.js.map +0 -1
  319. package/dist/mcp/servicenow-operations-mcp-refactored.d.ts.map +0 -1
  320. package/dist/mcp/servicenow-operations-mcp-refactored.js.map +0 -1
  321. package/dist/mcp/servicenow-operations-mcp.d.ts.map +0 -1
  322. package/dist/mcp/servicenow-operations-mcp.js.map +0 -1
  323. package/dist/mcp/servicenow-platform-development-mcp-refactored.d.ts.map +0 -1
  324. package/dist/mcp/servicenow-platform-development-mcp-refactored.js.map +0 -1
  325. package/dist/mcp/servicenow-platform-development-mcp.d.ts.map +0 -1
  326. package/dist/mcp/servicenow-platform-development-mcp.js.map +0 -1
  327. package/dist/mcp/servicenow-progressive-indexer.d.ts.map +0 -1
  328. package/dist/mcp/servicenow-progressive-indexer.js.map +0 -1
  329. package/dist/mcp/servicenow-reporting-analytics-mcp-refactored.d.ts.map +0 -1
  330. package/dist/mcp/servicenow-reporting-analytics-mcp-refactored.js.map +0 -1
  331. package/dist/mcp/servicenow-reporting-analytics-mcp.d.ts.map +0 -1
  332. package/dist/mcp/servicenow-reporting-analytics-mcp.js.map +0 -1
  333. package/dist/mcp/servicenow-security-compliance-mcp-refactored.d.ts.map +0 -1
  334. package/dist/mcp/servicenow-security-compliance-mcp-refactored.js.map +0 -1
  335. package/dist/mcp/servicenow-security-compliance-mcp.d.ts.map +0 -1
  336. package/dist/mcp/servicenow-security-compliance-mcp.js.map +0 -1
  337. package/dist/mcp/servicenow-update-set-mcp-refactored.d.ts.map +0 -1
  338. package/dist/mcp/servicenow-update-set-mcp-refactored.js.map +0 -1
  339. package/dist/mcp/servicenow-update-set-mcp.d.ts.map +0 -1
  340. package/dist/mcp/servicenow-update-set-mcp.js.map +0 -1
  341. package/dist/mcp/servicenow-xml-flow-mcp.d.ts.map +0 -1
  342. package/dist/mcp/servicenow-xml-flow-mcp.js.map +0 -1
  343. package/dist/mcp/shared/agent-context-provider.d.ts.map +0 -1
  344. package/dist/mcp/shared/agent-context-provider.js.map +0 -1
  345. package/dist/mcp/shared/base-mcp-server.d.ts.map +0 -1
  346. package/dist/mcp/shared/base-mcp-server.js.map +0 -1
  347. package/dist/mcp/shared/mcp-memory-manager.d.ts.map +0 -1
  348. package/dist/mcp/shared/mcp-memory-manager.js.map +0 -1
  349. package/dist/mcp/shared/mcp-resource-manager.d.ts.map +0 -1
  350. package/dist/mcp/shared/mcp-resource-manager.js.map +0 -1
  351. package/dist/mcp/snow-flow-mcp.d.ts.map +0 -1
  352. package/dist/mcp/snow-flow-mcp.js.map +0 -1
  353. package/dist/mcp/start-all-mcp-servers.d.ts.map +0 -1
  354. package/dist/mcp/start-all-mcp-servers.js.map +0 -1
  355. package/dist/mcp/start-servicenow-mcp.d.ts.map +0 -1
  356. package/dist/mcp/start-servicenow-mcp.js.map +0 -1
  357. package/dist/mcp/test-simple-mcp.d.ts.map +0 -1
  358. package/dist/mcp/test-simple-mcp.js.map +0 -1
  359. package/dist/memory/hierarchical-memory-system.d.ts +0 -90
  360. package/dist/memory/hierarchical-memory-system.d.ts.map +0 -1
  361. package/dist/memory/hierarchical-memory-system.js +0 -400
  362. package/dist/memory/hierarchical-memory-system.js.map +0 -1
  363. package/dist/memory/index.d.ts +0 -9
  364. package/dist/memory/index.d.ts.map +0 -1
  365. package/dist/memory/index.js +0 -20
  366. package/dist/memory/index.js.map +0 -1
  367. package/dist/memory/mcp-integration-example.d.ts +0 -6
  368. package/dist/memory/mcp-integration-example.d.ts.map +0 -1
  369. package/dist/memory/mcp-integration-example.js +0 -281
  370. package/dist/memory/mcp-integration-example.js.map +0 -1
  371. package/dist/memory/memory-client.d.ts +0 -199
  372. package/dist/memory/memory-client.d.ts.map +0 -1
  373. package/dist/memory/memory-client.js +0 -364
  374. package/dist/memory/memory-client.js.map +0 -1
  375. package/dist/memory/memory-manager.d.ts +0 -29
  376. package/dist/memory/memory-manager.d.ts.map +0 -1
  377. package/dist/memory/memory-manager.js +0 -280
  378. package/dist/memory/memory-manager.js.map +0 -1
  379. package/dist/memory/memory-operations.d.ts +0 -179
  380. package/dist/memory/memory-operations.d.ts.map +0 -1
  381. package/dist/memory/memory-operations.js +0 -691
  382. package/dist/memory/memory-operations.js.map +0 -1
  383. package/dist/memory/memory-system.d.ts +0 -152
  384. package/dist/memory/memory-system.d.ts.map +0 -1
  385. package/dist/memory/memory-system.js +0 -632
  386. package/dist/memory/memory-system.js.map +0 -1
  387. package/dist/memory/memory-test.d.ts +0 -6
  388. package/dist/memory/memory-test.d.ts.map +0 -1
  389. package/dist/memory/memory-test.js +0 -161
  390. package/dist/memory/memory-test.js.map +0 -1
  391. package/dist/memory/servicenow-artifact-indexer.d.ts +0 -119
  392. package/dist/memory/servicenow-artifact-indexer.d.ts.map +0 -1
  393. package/dist/memory/servicenow-artifact-indexer.js +0 -560
  394. package/dist/memory/servicenow-artifact-indexer.js.map +0 -1
  395. package/dist/memory/snow-flow-memory-patterns.d.ts +0 -213
  396. package/dist/memory/snow-flow-memory-patterns.d.ts.map +0 -1
  397. package/dist/memory/snow-flow-memory-patterns.js +0 -200
  398. package/dist/memory/snow-flow-memory-patterns.js.map +0 -1
  399. package/dist/memory/snow-memory.d.ts +0 -54
  400. package/dist/memory/snow-memory.d.ts.map +0 -1
  401. package/dist/memory/snow-memory.js +0 -301
  402. package/dist/memory/snow-memory.js.map +0 -1
  403. package/dist/memory/swarm-memory.d.ts +0 -135
  404. package/dist/memory/swarm-memory.d.ts.map +0 -1
  405. package/dist/memory/swarm-memory.js +0 -378
  406. package/dist/memory/swarm-memory.js.map +0 -1
  407. package/dist/monitoring/enhanced-monitoring-system.d.ts.map +0 -1
  408. package/dist/monitoring/enhanced-monitoring-system.js.map +0 -1
  409. package/dist/monitoring/performance-tracker.d.ts.map +0 -1
  410. package/dist/monitoring/performance-tracker.js.map +0 -1
  411. package/dist/optimization/cost-optimization-engine.d.ts.map +0 -1
  412. package/dist/optimization/cost-optimization-engine.js.map +0 -1
  413. package/dist/optimization/index.d.ts.map +0 -1
  414. package/dist/optimization/index.js.map +0 -1
  415. package/dist/orchestration/discovery/service-discovery.d.ts.map +0 -1
  416. package/dist/orchestration/discovery/service-discovery.js.map +0 -1
  417. package/dist/orchestration/distributed-orchestrator.d.ts.map +0 -1
  418. package/dist/orchestration/distributed-orchestrator.js.map +0 -1
  419. package/dist/orchestration/distribution/task-distribution-engine.d.ts.map +0 -1
  420. package/dist/orchestration/distribution/task-distribution-engine.js.map +0 -1
  421. package/dist/orchestration/interfaces/distributed-orchestration.interface.d.ts.map +0 -1
  422. package/dist/orchestration/interfaces/distributed-orchestration.interface.js.map +0 -1
  423. package/dist/orchestration/protocols/mcpx-protocol.d.ts.map +0 -1
  424. package/dist/orchestration/protocols/mcpx-protocol.js.map +0 -1
  425. package/dist/orchestration/state/distributed-state-manager.d.ts.map +0 -1
  426. package/dist/orchestration/state/distributed-state-manager.js.map +0 -1
  427. package/dist/orchestrator/flow-composer.d.ts.map +0 -1
  428. package/dist/orchestrator/flow-composer.js.map +0 -1
  429. package/dist/orchestrator/flow-pattern-templates.d.ts.map +0 -1
  430. package/dist/orchestrator/flow-pattern-templates.js.map +0 -1
  431. package/dist/orchestrator/flow-subflow-decision-engine.d.ts.map +0 -1
  432. package/dist/orchestrator/flow-subflow-decision-engine.js.map +0 -1
  433. package/dist/orchestrator/flow-validation-engine.d.ts.map +0 -1
  434. package/dist/orchestrator/flow-validation-engine.js.map +0 -1
  435. package/dist/orchestrator/snow-orchestrator.d.ts.map +0 -1
  436. package/dist/orchestrator/snow-orchestrator.js.map +0 -1
  437. package/dist/orchestrator/subflow-creation-handler.d.ts.map +0 -1
  438. package/dist/orchestrator/subflow-creation-handler.js.map +0 -1
  439. package/dist/patterns/adaptive-patterns.d.ts.map +0 -1
  440. package/dist/patterns/adaptive-patterns.js.map +0 -1
  441. package/dist/queen/advanced-integration-test.d.ts.map +0 -1
  442. package/dist/queen/advanced-integration-test.js.map +0 -1
  443. package/dist/queen/agent-factory.d.ts.map +0 -1
  444. package/dist/queen/agent-factory.js.map +0 -1
  445. package/dist/queen/index.d.ts.map +0 -1
  446. package/dist/queen/index.js.map +0 -1
  447. package/dist/queen/integration-example.d.ts.map +0 -1
  448. package/dist/queen/integration-example.js.map +0 -1
  449. package/dist/queen/integration-test.d.ts.map +0 -1
  450. package/dist/queen/integration-test.js.map +0 -1
  451. package/dist/queen/mcp-execution-bridge.d.ts.map +0 -1
  452. package/dist/queen/mcp-execution-bridge.js.map +0 -1
  453. package/dist/queen/mock-mcp-client.d.ts.map +0 -1
  454. package/dist/queen/mock-mcp-client.js.map +0 -1
  455. package/dist/queen/neural-learning.d.ts.map +0 -1
  456. package/dist/queen/neural-learning.js.map +0 -1
  457. package/dist/queen/parallel-agent-engine.d.ts.map +0 -1
  458. package/dist/queen/parallel-agent-engine.js.map +0 -1
  459. package/dist/queen/queen-memory-system.d.ts.map +0 -1
  460. package/dist/queen/queen-memory-system.js.map +0 -1
  461. package/dist/queen/queen-memory.d.ts.map +0 -1
  462. package/dist/queen/queen-memory.js.map +0 -1
  463. package/dist/queen/run-integration-tests.d.ts.map +0 -1
  464. package/dist/queen/run-integration-tests.js.map +0 -1
  465. package/dist/queen/servicenow-queen.d.ts.map +0 -1
  466. package/dist/queen/servicenow-queen.js.map +0 -1
  467. package/dist/queen/types.d.ts.map +0 -1
  468. package/dist/queen/types.js.map +0 -1
  469. package/dist/rollback/smart-rollback-system.d.ts.map +0 -1
  470. package/dist/rollback/smart-rollback-system.js.map +0 -1
  471. package/dist/snow-flow-system.d.ts.map +0 -1
  472. package/dist/snow-flow-system.js.map +0 -1
  473. package/dist/sparc/coordinators/adaptive-coordinator.d.ts.map +0 -1
  474. package/dist/sparc/coordinators/adaptive-coordinator.js.map +0 -1
  475. package/dist/sparc/coordinators/team-coordinator.d.ts.map +0 -1
  476. package/dist/sparc/coordinators/team-coordinator.js.map +0 -1
  477. package/dist/sparc/modes/team-modes.d.ts.map +0 -1
  478. package/dist/sparc/modes/team-modes.js.map +0 -1
  479. package/dist/sparc/sparc-help.d.ts.map +0 -1
  480. package/dist/sparc/sparc-help.js.map +0 -1
  481. package/dist/sparc/team-sparc.d.ts.map +0 -1
  482. package/dist/sparc/team-sparc.js.map +0 -1
  483. package/dist/sparc/teams/application-team.d.ts.map +0 -1
  484. package/dist/sparc/teams/application-team.js.map +0 -1
  485. package/dist/sparc/teams/flow-team.d.ts.map +0 -1
  486. package/dist/sparc/teams/flow-team.js.map +0 -1
  487. package/dist/sparc/teams/widget-team.d.ts.map +0 -1
  488. package/dist/sparc/teams/widget-team.js.map +0 -1
  489. package/dist/specialists/app-specialists.d.ts.map +0 -1
  490. package/dist/specialists/app-specialists.js.map +0 -1
  491. package/dist/specialists/base-specialist.d.ts.map +0 -1
  492. package/dist/specialists/base-specialist.js.map +0 -1
  493. package/dist/specialists/flow-specialists.d.ts.map +0 -1
  494. package/dist/specialists/flow-specialists.js.map +0 -1
  495. package/dist/specialists/individual-specialists.d.ts.map +0 -1
  496. package/dist/specialists/individual-specialists.js.map +0 -1
  497. package/dist/specialists/widget-specialists.d.ts.map +0 -1
  498. package/dist/specialists/widget-specialists.js.map +0 -1
  499. package/dist/strategies/global-scope-strategy.d.ts.map +0 -1
  500. package/dist/strategies/global-scope-strategy.js.map +0 -1
  501. package/dist/teams/adaptive-team.d.ts.map +0 -1
  502. package/dist/teams/adaptive-team.js.map +0 -1
  503. package/dist/teams/application-team.d.ts.map +0 -1
  504. package/dist/teams/application-team.js.map +0 -1
  505. package/dist/teams/base-team.d.ts.map +0 -1
  506. package/dist/teams/base-team.js.map +0 -1
  507. package/dist/teams/flow-team.d.ts.map +0 -1
  508. package/dist/teams/flow-team.js.map +0 -1
  509. package/dist/teams/widget-team.d.ts.map +0 -1
  510. package/dist/teams/widget-team.js.map +0 -1
  511. package/dist/testing/integration-test-suite.d.ts.map +0 -1
  512. package/dist/testing/integration-test-suite.js.map +0 -1
  513. package/dist/types/index.d.ts.map +0 -1
  514. package/dist/types/index.js.map +0 -1
  515. package/dist/types/servicenow.types.d.ts.map +0 -1
  516. package/dist/types/servicenow.types.js.map +0 -1
  517. package/dist/types/snow-flow.types.d.ts.map +0 -1
  518. package/dist/types/snow-flow.types.js.map +0 -1
  519. package/dist/types/todo.types.d.ts.map +0 -1
  520. package/dist/types/todo.types.js.map +0 -1
  521. package/dist/utils/action-type-cache.d.ts.map +0 -1
  522. package/dist/utils/action-type-cache.js.map +0 -1
  523. package/dist/utils/agent-detector.d.ts.map +0 -1
  524. package/dist/utils/agent-detector.js.map +0 -1
  525. package/dist/utils/artifact-tracker.d.ts.map +0 -1
  526. package/dist/utils/artifact-tracker.js.map +0 -1
  527. package/dist/utils/dependency-detector.d.ts.map +0 -1
  528. package/dist/utils/dependency-detector.js.map +0 -1
  529. package/dist/utils/deployment-metadata-handler.d.ts.map +0 -1
  530. package/dist/utils/deployment-metadata-handler.js.map +0 -1
  531. package/dist/utils/error-recovery.d.ts.map +0 -1
  532. package/dist/utils/error-recovery.js.map +0 -1
  533. package/dist/utils/flow-api-discovery.d.ts.map +0 -1
  534. package/dist/utils/flow-api-discovery.js.map +0 -1
  535. package/dist/utils/flow-xml-generator.d.ts.map +0 -1
  536. package/dist/utils/flow-xml-generator.js.map +0 -1
  537. package/dist/utils/logger.d.ts.map +0 -1
  538. package/dist/utils/logger.js.map +0 -1
  539. package/dist/utils/mcp-auth-middleware.d.ts.map +0 -1
  540. package/dist/utils/mcp-auth-middleware.js.map +0 -1
  541. package/dist/utils/mcp-config-manager.d.ts.map +0 -1
  542. package/dist/utils/mcp-config-manager.js.map +0 -1
  543. package/dist/utils/mcp-server-manager.d.ts.map +0 -1
  544. package/dist/utils/mcp-server-manager.js.map +0 -1
  545. package/dist/utils/mcp-tool-registry.d.ts.map +0 -1
  546. package/dist/utils/mcp-tool-registry.js.map +0 -1
  547. package/dist/utils/migrate-claude-flow.d.ts.map +0 -1
  548. package/dist/utils/migrate-claude-flow.js.map +0 -1
  549. package/dist/utils/migrate-snow-flow.d.ts.map +0 -1
  550. package/dist/utils/migrate-snow-flow.js.map +0 -1
  551. package/dist/utils/oauth-html-templates.d.ts.map +0 -1
  552. package/dist/utils/oauth-html-templates.js.map +0 -1
  553. package/dist/utils/scope-utils.d.ts.map +0 -1
  554. package/dist/utils/scope-utils.js.map +0 -1
  555. package/dist/utils/servicenow-client.d.ts.map +0 -1
  556. package/dist/utils/servicenow-client.js.map +0 -1
  557. package/dist/utils/servicenow-id-generator.d.ts.map +0 -1
  558. package/dist/utils/servicenow-id-generator.js.map +0 -1
  559. package/dist/utils/snow-memory-manager.d.ts.map +0 -1
  560. package/dist/utils/snow-memory-manager.js.map +0 -1
  561. package/dist/utils/snow-oauth-old.d.ts.map +0 -1
  562. package/dist/utils/snow-oauth-old.js.map +0 -1
  563. package/dist/utils/snow-oauth.d.ts.map +0 -1
  564. package/dist/utils/snow-oauth.js.map +0 -1
  565. package/dist/utils/template-engine.d.ts.map +0 -1
  566. package/dist/utils/template-engine.js.map +0 -1
  567. package/dist/utils/theme-manager.d.ts.map +0 -1
  568. package/dist/utils/theme-manager.js.map +0 -1
  569. package/dist/utils/unified-auth-store.d.ts.map +0 -1
  570. package/dist/utils/unified-auth-store.js.map +0 -1
  571. package/dist/utils/update-set-importer.d.ts.map +0 -1
  572. package/dist/utils/update-set-importer.js.map +0 -1
  573. package/dist/utils/update-set-xml-packager.d.ts.map +0 -1
  574. package/dist/utils/update-set-xml-packager.js.map +0 -1
  575. package/dist/utils/widget-template-generator.d.ts.map +0 -1
  576. package/dist/utils/widget-template-generator.js.map +0 -1
  577. package/dist/version.d.ts.map +0 -1
  578. package/dist/version.js.map +0 -1
  579. package/memory/agents/README.md +0 -31
  580. package/memory/claude-flow-data.json +0 -5
  581. package/memory/servicenow_artifacts/000d9224c895221055906c7518aa2d3d.json +0 -30
  582. package/memory/servicenow_artifacts/0196b66173303010e46b4a2214f6a7a2.json +0 -36
  583. package/memory/servicenow_artifacts/125e5d1d837e2a102a7ea130ceaad397.json +0 -30
  584. package/memory/servicenow_artifacts/7637c1f2b7112210a5e5911cde11a972.json +0 -30
  585. package/memory/servicenow_artifacts/default_documentation_tables_1754056582292.json +0 -55
  586. package/memory/servicenow_artifacts/default_documentation_tables_1754057477189.json +0 -55
  587. package/memory/sessions/README.md +0 -32
  588. package/memory/update-set-sessions/01f82af583faea102a7ea130ceaad3d4.json +0 -9
  589. package/memory/update-set-sessions/27718fb983faea102a7ea130ceaad34b.json +0 -9
  590. package/memory/update-set-sessions/412e9bf6833e22502a7ea130ceaad30a.json +0 -8
  591. package/memory/update-set-sessions/66fc5a79837aea102a7ea130ceaad3ab.json +0 -9
  592. package/memory/update-set-sessions/71a30ff5837eea102a7ea130ceaad37f.json +0 -9
  593. package/memory/update-set-sessions/74fba27983faea102a7ea130ceaad3bd.json +0 -9
  594. package/memory/update-set-sessions/a0b147b5837eea102a7ea130ceaad344.json +0 -58
  595. package/memory/update-set-sessions/b13f5eb983baea102a7ea130ceaad33e.json +0 -9
@@ -0,0 +1,1399 @@
1
+ /**
2
+ * Queen Agent Core with Enhanced 403 Error Handling
3
+ * Master coordinator that analyzes objectives and spawns specialized agents
4
+ * Works through Claude Code interface using TodoWrite for task coordination
5
+ * Now with intelligent 403 error handling using Gap Analysis Engine
6
+ */
7
+
8
+ import { EventEmitter } from 'eventemitter3';
9
+ import { TodoItem, TodoStatus } from '../types/todo.types';
10
+ import { ServiceNowTask, Agent, AgentType, TaskAnalysis, DeploymentPattern } from '../queen/types';
11
+ import { QueenMemorySystem } from '../queen/queen-memory';
12
+ import { AgentCoordinator } from './coordinator';
13
+ import { ParallelAgentEngine, ParallelizationOpportunity } from '../queen/parallel-agent-engine';
14
+ import { Queen403Handler } from './queen-403-handler';
15
+ import { Logger } from '../utils/logger';
16
+ import * as crypto from 'crypto';
17
+
18
+ export interface QueenAgentConfig {
19
+ memoryPath?: string;
20
+ maxConcurrentAgents?: number;
21
+ debugMode?: boolean;
22
+ autoSpawn?: boolean;
23
+ claudeCodeInterface?: boolean;
24
+ mcpTools?: any; // MCP tools for Gap Analysis
25
+ }
26
+
27
+ export interface QueenObjective {
28
+ id: string;
29
+ description: string;
30
+ priority?: 'low' | 'medium' | 'high' | 'critical';
31
+ constraints?: string[];
32
+ metadata?: Record<string, any>;
33
+ }
34
+
35
+ export interface TodoCoordination {
36
+ objectiveId: string;
37
+ todos: TodoItem[];
38
+ agentAssignments: Map<string, string>; // todoId -> agentId
39
+ dependencies: Map<string, string[]>; // todoId -> [dependencyIds]
40
+ }
41
+
42
+ export class QueenAgent extends EventEmitter {
43
+ private memory: QueenMemorySystem;
44
+ private coordinator: AgentCoordinator;
45
+ private parallelEngine: ParallelAgentEngine;
46
+ private handler403: Queen403Handler;
47
+ private config: Required<QueenAgentConfig>;
48
+ private activeObjectives: Map<string, QueenObjective>;
49
+ private todoCoordinations: Map<string, TodoCoordination>;
50
+ private activeAgents: Map<string, Agent>;
51
+ private logger: Logger;
52
+
53
+ constructor(config: QueenAgentConfig = {}) {
54
+ super();
55
+
56
+ this.config = {
57
+ memoryPath: config.memoryPath,
58
+ maxConcurrentAgents: config.maxConcurrentAgents || 8,
59
+ debugMode: config.debugMode || false,
60
+ autoSpawn: config.autoSpawn !== false,
61
+ claudeCodeInterface: config.claudeCodeInterface !== false,
62
+ mcpTools: config.mcpTools || {}
63
+ };
64
+
65
+ // Initialize logger first
66
+ this.logger = new Logger('QueenAgent');
67
+
68
+ // Initialize core systems
69
+ this.memory = new QueenMemorySystem(this.config.memoryPath);
70
+ this.coordinator = new AgentCoordinator(this.memory);
71
+ this.parallelEngine = new ParallelAgentEngine(this.memory);
72
+ this.handler403 = new Queen403Handler(this.logger, this.config.mcpTools);
73
+ this.activeObjectives = new Map();
74
+ this.todoCoordinations = new Map();
75
+ this.activeAgents = new Map();
76
+
77
+ this.setupEventHandlers();
78
+
79
+ if (this.config.debugMode) {
80
+ console.log('👑 Queen Agent initialized with Claude Code interface and 403 handling');
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Update MCP tools configuration (useful when tools become available later)
86
+ */
87
+ updateMCPTools(mcpTools: any): void {
88
+ this.config.mcpTools = mcpTools;
89
+ this.handler403 = new Queen403Handler(this.logger, mcpTools);
90
+ }
91
+
92
+ /**
93
+ * Analyze objective and create coordinated execution plan
94
+ */
95
+ async analyzeObjective(objective: string | QueenObjective): Promise<TaskAnalysis> {
96
+ const queenObjective = typeof objective === 'string'
97
+ ? { id: this.generateId('obj'), description: objective }
98
+ : objective;
99
+
100
+ this.activeObjectives.set(queenObjective.id, queenObjective);
101
+ this.emit('objective:analyzing', queenObjective);
102
+
103
+ try {
104
+ // Analyze objective using memory patterns and neural learning
105
+ const _analysis = await this.performObjectiveAnalysis(queenObjective);
106
+
107
+ // Store _analysis in memory for coordination
108
+ await this.memory.store(`analysis_${queenObjective.id}`, {
109
+ objective: queenObjective,
110
+ _analysis,
111
+ timestamp: new Date().toISOString()
112
+ });
113
+
114
+ // Create TodoWrite coordination structure
115
+ const todoCoordination = await this.createTodoCoordination(queenObjective, _analysis);
116
+ this.todoCoordinations.set(queenObjective.id, todoCoordination);
117
+
118
+ this.emit('objective:analyzed', { objective: queenObjective, _analysis, todos: todoCoordination.todos });
119
+
120
+ return _analysis;
121
+
122
+ } catch (error) {
123
+ this.emit('objective:error', { objective: queenObjective, error });
124
+ throw error;
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Handle deployment error with intelligent 403 detection and resolution
130
+ */
131
+ async handleDeploymentError(error: any, context: {
132
+ objectiveId: string;
133
+ agentId?: string;
134
+ operation: string;
135
+ artifactType?: string;
136
+ tableName?: string;
137
+ }): Promise<boolean> {
138
+ // Check if it's a 403 permission error
139
+ if (this.is403Error(error)) {
140
+ console.log('🚨 Queen Agent: Detected 403 permission error - activating intelligent _analysis');
141
+
142
+ const objective = this.activeObjectives.get(context.objectiveId);
143
+ if (!objective) {
144
+ console.error('No objective found for error context');
145
+ return false;
146
+ }
147
+
148
+ // Use 403 handler with Gap Analysis
149
+ const result = await this.handler403.handle403Error({
150
+ error,
151
+ operation: context.operation,
152
+ tableName: context.tableName,
153
+ artifactType: context.artifactType,
154
+ objective: objective.description
155
+ });
156
+
157
+ // Update todos based on analysis
158
+ if (result.nextSteps.length > 0) {
159
+ await this.updateTodosWithPermissionFixes(context.objectiveId, result);
160
+ }
161
+
162
+ // If automatic fixes were applied, return true to retry
163
+ if (result.resolved) {
164
+ console.log('✅ Queen Agent: Automatic fixes applied - suggesting retry');
165
+ this.emit('permission:auto-fixed', { context, result });
166
+ return true;
167
+ }
168
+
169
+ // Emit event for manual intervention needed
170
+ this.emit('permission:manual-required', { context, result });
171
+ return false;
172
+ }
173
+
174
+ return false;
175
+ }
176
+
177
+ /**
178
+ * Check if error is a 403 permission error
179
+ */
180
+ private is403Error(error: any): boolean {
181
+ const errorStr = error?.toString() || '';
182
+ const errorMsg = error?.message || '';
183
+ const statusCode = error?.status || error?.statusCode || error?.response?.status;
184
+
185
+ return statusCode === 403 ||
186
+ errorStr.includes('403') ||
187
+ errorMsg.includes('403') ||
188
+ errorMsg.includes('permission') ||
189
+ errorMsg.includes('access denied') ||
190
+ errorMsg.includes('insufficient privileges');
191
+ }
192
+
193
+ /**
194
+ * Update todos with permission fix steps
195
+ */
196
+ private async updateTodosWithPermissionFixes(
197
+ objectiveId: string,
198
+ permissionResult: any
199
+ ): Promise<void> {
200
+ const todoCoordination = this.todoCoordinations.get(objectiveId);
201
+ if (!todoCoordination) return;
202
+
203
+ // Add new todos for permission fixes
204
+ const newTodos: TodoItem[] = [];
205
+
206
+ // Add retry todo if automatic fixes were applied
207
+ if (permissionResult.resolved) {
208
+ newTodos.push({
209
+ id: this.generateId('todo'),
210
+ content: '🔄 Retry deployment after automatic permission fixes',
211
+ status: 'pending',
212
+ priority: 'high'
213
+ });
214
+ }
215
+
216
+ // Add manual action todos
217
+ permissionResult.nextSteps.forEach((step: string) => {
218
+ newTodos.push({
219
+ id: this.generateId('todo'),
220
+ content: step,
221
+ status: 'pending',
222
+ priority: 'high'
223
+ });
224
+ });
225
+
226
+ // Insert new todos at the beginning of pending todos
227
+ const pendingIndex = todoCoordination.todos.findIndex(t => t.status === 'pending');
228
+ if (pendingIndex >= 0) {
229
+ todoCoordination.todos.splice(pendingIndex, 0, ...newTodos);
230
+ } else {
231
+ todoCoordination.todos.push(...newTodos);
232
+ }
233
+
234
+ // Emit update event
235
+ this.emit('todos:updated', { objectiveId, todos: todoCoordination.todos });
236
+ }
237
+
238
+ /**
239
+ * Spawn agents based on objective requirements with intelligent parallelization
240
+ */
241
+ async spawnAgents(objectiveId: string): Promise<Agent[]> {
242
+ const todoCoordination = this.todoCoordinations.get(objectiveId);
243
+ if (!todoCoordination) {
244
+ throw new Error(`No todo coordination found for objective: ${objectiveId}`);
245
+ }
246
+
247
+ const _analysis = await this.memory.get(`analysis_${objectiveId}`) as { _analysis: TaskAnalysis };
248
+ if (!_analysis) {
249
+ throw new Error(`No _analysis found for objective: ${objectiveId}`);
250
+ }
251
+
252
+ console.log('🧠 Queen Agent: Analyzing parallelization opportunities...');
253
+
254
+ // 🚀 NEW: Detect parallelization opportunities
255
+ const opportunities = await this.parallelEngine.detectParallelizationOpportunities(
256
+ todoCoordination.todos,
257
+ _analysis._analysis.type,
258
+ Array.from(this.activeAgents.values())
259
+ );
260
+
261
+ if (opportunities.length > 0) {
262
+ console.log(`🎯 Found ${opportunities.length} parallelization opportunities!`);
263
+ return await this.spawnParallelAgents(objectiveId, todoCoordination, opportunities);
264
+ } else {
265
+ console.log('📋 No parallelization opportunities found, using sequential approach');
266
+ return await this.spawnSequentialAgents(objectiveId, todoCoordination, _analysis._analysis);
267
+ }
268
+ }
269
+
270
+ /**
271
+ * 🚀 NEW: Spawn parallel agents based on opportunities
272
+ */
273
+ private async spawnParallelAgents(
274
+ objectiveId: string,
275
+ todoCoordination: TodoCoordination,
276
+ opportunities: ParallelizationOpportunity[]
277
+ ): Promise<Agent[]> {
278
+ console.log('🚀 Queen Agent: Spawning parallel agent teams...');
279
+
280
+ // Create execution plan
281
+ const executionPlan = await this.parallelEngine.createExecutionPlan(
282
+ opportunities,
283
+ todoCoordination.todos,
284
+ this.config.maxConcurrentAgents
285
+ );
286
+
287
+ // Execute the plan and get spawned agents
288
+ const result = await this.parallelEngine.executeParallelPlan(
289
+ executionPlan,
290
+ async (type: AgentType, specialization?: string) => {
291
+ return await this.spawnSpecializedAgent(type, objectiveId, specialization);
292
+ }
293
+ );
294
+
295
+ console.log(`✅ Spawned ${result.spawnedAgents.length} specialized agents in parallel`);
296
+ console.log(`⚡ Estimated speedup: ${result.executionDetails.estimatedSpeedup}`);
297
+
298
+ return result.spawnedAgents;
299
+ }
300
+
301
+ /**
302
+ * Fallback to sequential agent spawning
303
+ */
304
+ private async spawnSequentialAgents(
305
+ objectiveId: string,
306
+ todoCoordination: TodoCoordination,
307
+ _analysis: TaskAnalysis
308
+ ): Promise<Agent[]> {
309
+ const agents: Agent[] = [];
310
+ const requiredAgentTypes = new Set(_analysis.requiredAgents);
311
+
312
+ // Spawn agents for each required type
313
+ for (const agentType of requiredAgentTypes) {
314
+ const agent = await this.spawnSpecializedAgent(agentType, objectiveId);
315
+ agents.push(agent);
316
+ }
317
+
318
+ return agents;
319
+ }
320
+
321
+ /**
322
+ * Spawn a specialized agent with optional specialization
323
+ */
324
+ private async spawnSpecializedAgent(
325
+ type: AgentType,
326
+ objectiveId: string,
327
+ specialization?: string
328
+ ): Promise<Agent> {
329
+ const agentId = this.generateId('agent');
330
+
331
+ const agent: Agent = {
332
+ id: agentId,
333
+ type,
334
+ status: 'active',
335
+ objectiveId,
336
+ specialization,
337
+ startTime: Date.now(),
338
+ capabilities: [],
339
+ mcpTools: []
340
+ };
341
+
342
+ this.activeAgents.set(agentId, agent);
343
+
344
+ // Store agent info in memory for coordination
345
+ await this.memory.store(`agent_${agentId}`, {
346
+ agent,
347
+ objective: this.activeObjectives.get(objectiveId),
348
+ assignedTodos: [],
349
+ status: 'initializing'
350
+ });
351
+
352
+ this.emit('agent:spawned', agent);
353
+
354
+ // Assign todos to agent based on capabilities
355
+ await this.assignTodosToAgent(agent, objectiveId);
356
+
357
+ return agent;
358
+ }
359
+
360
+ /**
361
+ * Analyze objective to determine requirements
362
+ */
363
+ private async performObjectiveAnalysis(objective: QueenObjective): Promise<TaskAnalysis> {
364
+ const description = objective.description.toLowerCase();
365
+
366
+ // Determine task type
367
+ let type: ServiceNowTask['type'] = 'unknown';
368
+ let requiredAgents: AgentType[] = [];
369
+ let estimatedComplexity = 5;
370
+ let suggestedPattern: DeploymentPattern = {
371
+ taskType: 'standard',
372
+ successRate: 0.8,
373
+ agentSequence: [],
374
+ mcpSequence: [],
375
+ avgDuration: 300,
376
+ lastUsed: new Date()
377
+ };
378
+ const dependencies: string[] = [];
379
+
380
+ // Portal page detection - check for specific page keywords
381
+ if ((description.includes('portal') && description.includes('page')) ||
382
+ description.includes('portal page') ||
383
+ (description.includes('widget') && description.includes('page')) ||
384
+ (description.includes('widget') && description.includes('plaats')) ||
385
+ (description.includes('widget') && description.includes('add')) ||
386
+ description.includes('service portal page')) {
387
+ type = 'portal_page';
388
+ requiredAgents = ['widget-creator', 'page-designer', 'script-writer', 'tester'];
389
+ if (description.includes('dashboard') || description.includes('multi')) {
390
+ estimatedComplexity = 8;
391
+ requiredAgents.push('ui-ux-specialist');
392
+ }
393
+ }
394
+ // Widget development detection (only if not portal page)
395
+ else if (description.includes('widget') || description.includes('ui component')) {
396
+ type = 'widget';
397
+ requiredAgents = ['widget-creator', 'script-writer', 'tester'];
398
+ if (description.includes('complex') || description.includes('interactive')) {
399
+ estimatedComplexity = 8;
400
+ requiredAgents.push('ui-ux-specialist');
401
+ }
402
+ }
403
+
404
+ // Flow development detection
405
+ else if (description.includes('flow') || description.includes('workflow') || description.includes('automation')) {
406
+ type = 'flow';
407
+ requiredAgents = ['flow-builder', 'integration-specialist', 'tester'];
408
+ if (description.includes('approval')) {
409
+ requiredAgents.push('approval-specialist');
410
+ dependencies.push('user_management', 'notification_system');
411
+ }
412
+ }
413
+
414
+ // Application development
415
+ else if (description.includes('application') || description.includes('app') || description.includes('complete solution')) {
416
+ type = 'application';
417
+ requiredAgents = ['app-architect', 'widget-creator', 'flow-builder', 'script-writer', 'tester'];
418
+ estimatedComplexity = 10;
419
+ suggestedPattern = {
420
+ taskType: 'modular',
421
+ successRate: 0.8,
422
+ agentSequence: requiredAgents,
423
+ mcpSequence: [],
424
+ avgDuration: 900,
425
+ lastUsed: new Date()
426
+ };
427
+ }
428
+
429
+ // Script development
430
+ else if (description.includes('script') || description.includes('business rule') || description.includes('api')) {
431
+ type = 'script';
432
+ requiredAgents = ['script-writer', 'tester'];
433
+ if (description.includes('integration')) {
434
+ requiredAgents.push('integration-specialist');
435
+ }
436
+ }
437
+
438
+ // Integration development
439
+ else if (description.includes('integration') || description.includes('connect') || description.includes('external')) {
440
+ type = 'integration';
441
+ requiredAgents = ['integration-specialist', 'script-writer', 'tester'];
442
+ dependencies.push('authentication', 'data_transformation');
443
+ }
444
+
445
+ // Add security agent if mentioned
446
+ if (description.includes('secure') || description.includes('security') || description.includes('permission')) {
447
+ requiredAgents.push('security-specialist');
448
+ }
449
+
450
+ return {
451
+ type,
452
+ complexity: estimatedComplexity.toString(),
453
+ requiredAgents: [...new Set(requiredAgents)], // Remove duplicates
454
+ estimatedComplexity: Math.min(10, Math.max(1, estimatedComplexity)),
455
+ suggestedPattern,
456
+ dependencies
457
+ };
458
+ }
459
+
460
+ /**
461
+ * Create todo coordination structure for Claude Code interface
462
+ */
463
+ private async createTodoCoordination(
464
+ objective: QueenObjective,
465
+ _analysis: TaskAnalysis
466
+ ): Promise<TodoCoordination> {
467
+ const todos = this.generateTodosForObjective(objective, _analysis);
468
+
469
+ const coordination: TodoCoordination = {
470
+ objectiveId: objective.id,
471
+ todos,
472
+ agentAssignments: new Map(),
473
+ dependencies: this.analyzeTodoDependencies(todos)
474
+ };
475
+
476
+ // Store coordination info in memory
477
+ await this.memory.store(`coordination_${objective.id}`, coordination);
478
+
479
+ return coordination;
480
+ }
481
+
482
+ /**
483
+ * Generate todos based on objective type
484
+ */
485
+ private generateTodosForObjective(objective: QueenObjective, _analysis: TaskAnalysis): TodoItem[] {
486
+ const baseTodos: TodoItem[] = [
487
+ {
488
+ id: this.generateId('todo'),
489
+ content: `Initialize swarm memory session for: ${objective.description}`,
490
+ status: 'pending',
491
+ priority: 'high'
492
+ },
493
+ {
494
+ id: this.generateId('todo'),
495
+ content: 'Validate ServiceNow authentication and permissions',
496
+ status: 'pending',
497
+ priority: 'high'
498
+ },
499
+ {
500
+ id: this.generateId('todo'),
501
+ content: 'Check for existing similar artifacts',
502
+ status: 'pending',
503
+ priority: 'medium'
504
+ },
505
+ {
506
+ id: this.generateId('todo'),
507
+ content: 'Create Update Set for tracking changes',
508
+ status: 'pending',
509
+ priority: 'high'
510
+ }
511
+ ];
512
+
513
+ // Add type-specific todos
514
+ switch (_analysis.type) {
515
+ case 'widget':
516
+ baseTodos.push(...this.createWidgetTodos(objective, _analysis));
517
+ break;
518
+ case 'portal_page':
519
+ baseTodos.push(...this.createPortalPageTodos(objective, _analysis));
520
+ break;
521
+ case 'flow':
522
+ baseTodos.push(...this.createFlowTodos(objective, _analysis));
523
+ break;
524
+ case 'application':
525
+ baseTodos.push(...this.createApplicationTodos(objective, _analysis));
526
+ break;
527
+ case 'script':
528
+ baseTodos.push(...this.createScriptTodos(objective, _analysis));
529
+ break;
530
+ case 'integration':
531
+ baseTodos.push(...this.createIntegrationTodos(objective, _analysis));
532
+ break;
533
+ default:
534
+ baseTodos.push(...this.createGenericTodos(objective, _analysis));
535
+ }
536
+
537
+ // Add final todos
538
+ baseTodos.push(
539
+ {
540
+ id: this.generateId('todo'),
541
+ content: 'Validate solution completeness',
542
+ status: 'pending',
543
+ priority: 'high'
544
+ },
545
+ {
546
+ id: this.generateId('todo'),
547
+ content: 'Generate documentation and handoff materials',
548
+ status: 'pending',
549
+ priority: 'medium'
550
+ }
551
+ );
552
+
553
+ return baseTodos;
554
+ }
555
+
556
+ /**
557
+ * Create widget-specific todos
558
+ */
559
+ private createWidgetTodos(objective: QueenObjective, _analysis: TaskAnalysis): TodoItem[] {
560
+ // 🚀 ENHANCED: More specific todos to trigger parallel agent specialization
561
+ const todos: TodoItem[] = [
562
+ {
563
+ id: this.generateId('todo'),
564
+ content: `Analyze portal requirements and user experience design: ${objective.description}`,
565
+ status: 'pending',
566
+ priority: 'high'
567
+ },
568
+ {
569
+ id: this.generateId('todo'),
570
+ content: 'Create widget HTML structure with responsive design and accessibility features',
571
+ status: 'pending',
572
+ priority: 'high'
573
+ },
574
+ {
575
+ id: this.generateId('todo'),
576
+ content: 'Develop server-side script for backend data processing and API integration',
577
+ status: 'pending',
578
+ priority: 'high'
579
+ },
580
+ {
581
+ id: this.generateId('todo'),
582
+ content: 'Build client-side controller with interactive features and event handling',
583
+ status: 'pending',
584
+ priority: 'high'
585
+ },
586
+ {
587
+ id: this.generateId('todo'),
588
+ content: 'Style widget with CSS including responsive design and theme compliance',
589
+ status: 'pending',
590
+ priority: 'high'
591
+ },
592
+ {
593
+ id: this.generateId('todo'),
594
+ content: 'Implement performance optimization and caching strategies',
595
+ status: 'pending',
596
+ priority: 'medium'
597
+ },
598
+ {
599
+ id: this.generateId('todo'),
600
+ content: 'Test widget functionality including cross-browser and mobile testing',
601
+ status: 'pending',
602
+ priority: 'high'
603
+ },
604
+ {
605
+ id: this.generateId('todo'),
606
+ content: 'Ensure security best practices and vulnerability scanning',
607
+ status: 'pending',
608
+ priority: 'high'
609
+ }
610
+ ];
611
+
612
+ return todos;
613
+ }
614
+
615
+ /**
616
+ * Create portal page-specific todos
617
+ */
618
+ private createPortalPageTodos(objective: QueenObjective, _analysis: TaskAnalysis): TodoItem[] {
619
+ const todos: TodoItem[] = [
620
+ {
621
+ id: this.generateId('todo'),
622
+ content: `Analyze portal page requirements: ${objective.description}`,
623
+ status: 'pending',
624
+ priority: 'high'
625
+ },
626
+ {
627
+ id: this.generateId('todo'),
628
+ content: 'Create or identify widget to be placed on the page',
629
+ status: 'pending',
630
+ priority: 'high'
631
+ },
632
+ {
633
+ id: this.generateId('todo'),
634
+ content: 'Design portal page layout (single column, multi-column, or with sidebar)',
635
+ status: 'pending',
636
+ priority: 'high'
637
+ },
638
+ {
639
+ id: this.generateId('todo'),
640
+ content: 'Determine target portal (Service Portal or Employee Service Center)',
641
+ status: 'pending',
642
+ priority: 'medium'
643
+ },
644
+ {
645
+ id: this.generateId('todo'),
646
+ content: 'Create portal page with proper page ID and title',
647
+ status: 'pending',
648
+ priority: 'high'
649
+ },
650
+ {
651
+ id: this.generateId('todo'),
652
+ content: 'Configure page structure (containers, rows, columns)',
653
+ status: 'pending',
654
+ priority: 'high'
655
+ },
656
+ {
657
+ id: this.generateId('todo'),
658
+ content: 'Place widget instance on the portal page with proper sizing',
659
+ status: 'pending',
660
+ priority: 'high'
661
+ },
662
+ {
663
+ id: this.generateId('todo'),
664
+ content: 'Apply custom CSS styling for page layout and responsiveness',
665
+ status: 'pending',
666
+ priority: 'medium'
667
+ },
668
+ {
669
+ id: this.generateId('todo'),
670
+ content: 'Configure page permissions and accessibility settings',
671
+ status: 'pending',
672
+ priority: 'medium'
673
+ },
674
+ {
675
+ id: this.generateId('todo'),
676
+ content: 'Test portal page across different devices and browsers',
677
+ status: 'pending',
678
+ priority: 'high'
679
+ },
680
+ {
681
+ id: this.generateId('todo'),
682
+ content: 'Add page to portal navigation menu if needed',
683
+ status: 'pending',
684
+ priority: 'low'
685
+ }
686
+ ];
687
+
688
+ return todos;
689
+ }
690
+
691
+ /**
692
+ * Create flow-specific todos
693
+ */
694
+ private createFlowTodos(objective: QueenObjective, _analysis: TaskAnalysis): TodoItem[] {
695
+ const todos: TodoItem[] = [
696
+ {
697
+ id: this.generateId('todo'),
698
+ content: `Analyze flow requirements: ${objective.description}`,
699
+ status: 'pending',
700
+ priority: 'high'
701
+ },
702
+ {
703
+ id: this.generateId('todo'),
704
+ content: 'Design flow trigger conditions and events',
705
+ status: 'pending',
706
+ priority: 'high'
707
+ },
708
+ {
709
+ id: this.generateId('todo'),
710
+ content: 'Map out flow steps and decision points',
711
+ status: 'pending',
712
+ priority: 'high'
713
+ },
714
+ {
715
+ id: this.generateId('todo'),
716
+ content: 'Configure flow actions and integrations',
717
+ status: 'pending',
718
+ priority: 'medium'
719
+ },
720
+ {
721
+ id: this.generateId('todo'),
722
+ content: 'Set up data transformations and variables',
723
+ status: 'pending',
724
+ priority: 'medium'
725
+ },
726
+ {
727
+ id: this.generateId('todo'),
728
+ content: 'Create flow using natural language API',
729
+ status: 'pending',
730
+ priority: 'high'
731
+ },
732
+ {
733
+ id: this.generateId('todo'),
734
+ content: 'Test flow with mock data scenarios',
735
+ status: 'pending',
736
+ priority: 'high'
737
+ }
738
+ ];
739
+
740
+ return todos;
741
+ }
742
+
743
+ /**
744
+ * Create application-specific todos
745
+ */
746
+ private createApplicationTodos(objective: QueenObjective, _analysis: TaskAnalysis): TodoItem[] {
747
+ const todos: TodoItem[] = [
748
+ {
749
+ id: this.generateId('todo'),
750
+ content: `Design application architecture: ${objective.description}`,
751
+ status: 'pending',
752
+ priority: 'high'
753
+ },
754
+ {
755
+ id: this.generateId('todo'),
756
+ content: 'Create application scope and structure',
757
+ status: 'pending',
758
+ priority: 'high'
759
+ },
760
+ {
761
+ id: this.generateId('todo'),
762
+ content: 'Design data model and tables',
763
+ status: 'pending',
764
+ priority: 'high'
765
+ },
766
+ {
767
+ id: this.generateId('todo'),
768
+ content: 'Create UI components and widgets',
769
+ status: 'pending',
770
+ priority: 'high'
771
+ },
772
+ {
773
+ id: this.generateId('todo'),
774
+ content: 'Implement business logic and workflows',
775
+ status: 'pending',
776
+ priority: 'high'
777
+ },
778
+ {
779
+ id: this.generateId('todo'),
780
+ content: 'Configure security and access controls',
781
+ status: 'pending',
782
+ priority: 'high'
783
+ },
784
+ {
785
+ id: this.generateId('todo'),
786
+ content: 'Create integration points',
787
+ status: 'pending',
788
+ priority: 'medium'
789
+ },
790
+ {
791
+ id: this.generateId('todo'),
792
+ content: 'Test application end-to-end',
793
+ status: 'pending',
794
+ priority: 'high'
795
+ }
796
+ ];
797
+
798
+ return todos;
799
+ }
800
+
801
+ /**
802
+ * Create script-specific todos
803
+ */
804
+ private createScriptTodos(objective: QueenObjective, _analysis: TaskAnalysis): TodoItem[] {
805
+ const todos: TodoItem[] = [
806
+ {
807
+ id: this.generateId('todo'),
808
+ content: `Analyze script requirements: ${objective.description}`,
809
+ status: 'pending',
810
+ priority: 'high'
811
+ },
812
+ {
813
+ id: this.generateId('todo'),
814
+ content: 'Design script logic and error handling',
815
+ status: 'pending',
816
+ priority: 'high'
817
+ },
818
+ {
819
+ id: this.generateId('todo'),
820
+ content: 'Implement core functionality',
821
+ status: 'pending',
822
+ priority: 'high'
823
+ },
824
+ {
825
+ id: this.generateId('todo'),
826
+ content: 'Add logging and debugging capabilities',
827
+ status: 'pending',
828
+ priority: 'medium'
829
+ },
830
+ {
831
+ id: this.generateId('todo'),
832
+ content: 'Optimize performance',
833
+ status: 'pending',
834
+ priority: 'medium'
835
+ },
836
+ {
837
+ id: this.generateId('todo'),
838
+ content: 'Create unit tests',
839
+ status: 'pending',
840
+ priority: 'high'
841
+ },
842
+ {
843
+ id: this.generateId('todo'),
844
+ content: 'Deploy and validate in ServiceNow',
845
+ status: 'pending',
846
+ priority: 'high'
847
+ }
848
+ ];
849
+
850
+ return todos;
851
+ }
852
+
853
+ /**
854
+ * Create integration-specific todos
855
+ */
856
+ private createIntegrationTodos(objective: QueenObjective, _analysis: TaskAnalysis): TodoItem[] {
857
+ const todos: TodoItem[] = [
858
+ {
859
+ id: this.generateId('todo'),
860
+ content: `Analyze integration requirements: ${objective.description}`,
861
+ status: 'pending',
862
+ priority: 'high'
863
+ },
864
+ {
865
+ id: this.generateId('todo'),
866
+ content: 'Identify external systems and APIs',
867
+ status: 'pending',
868
+ priority: 'high'
869
+ },
870
+ {
871
+ id: this.generateId('todo'),
872
+ content: 'Design data mapping and transformation',
873
+ status: 'pending',
874
+ priority: 'high'
875
+ },
876
+ {
877
+ id: this.generateId('todo'),
878
+ content: 'Configure authentication and security',
879
+ status: 'pending',
880
+ priority: 'high'
881
+ },
882
+ {
883
+ id: this.generateId('todo'),
884
+ content: 'Create REST/SOAP message configurations',
885
+ status: 'pending',
886
+ priority: 'medium'
887
+ },
888
+ {
889
+ id: this.generateId('todo'),
890
+ content: 'Implement error handling and retry logic',
891
+ status: 'pending',
892
+ priority: 'medium'
893
+ },
894
+ {
895
+ id: this.generateId('todo'),
896
+ content: 'Test integration with mock endpoints',
897
+ status: 'pending',
898
+ priority: 'high'
899
+ },
900
+ {
901
+ id: this.generateId('todo'),
902
+ content: 'Deploy and monitor integration',
903
+ status: 'pending',
904
+ priority: 'high'
905
+ }
906
+ ];
907
+
908
+ return todos;
909
+ }
910
+
911
+ /**
912
+ * Create generic todos for unknown task types
913
+ */
914
+ private createGenericTodos(objective: QueenObjective, _analysis: TaskAnalysis): TodoItem[] {
915
+ const todos: TodoItem[] = [
916
+ {
917
+ id: this.generateId('todo'),
918
+ content: `Analyze requirements: ${objective.description}`,
919
+ status: 'pending',
920
+ priority: 'high'
921
+ },
922
+ {
923
+ id: this.generateId('todo'),
924
+ content: 'Research existing ServiceNow capabilities',
925
+ status: 'pending',
926
+ priority: 'high'
927
+ },
928
+ {
929
+ id: this.generateId('todo'),
930
+ content: 'Design solution architecture',
931
+ status: 'pending',
932
+ priority: 'high'
933
+ },
934
+ {
935
+ id: this.generateId('todo'),
936
+ content: 'Implement core functionality',
937
+ status: 'pending',
938
+ priority: 'high'
939
+ },
940
+ {
941
+ id: this.generateId('todo'),
942
+ content: 'Create necessary configurations',
943
+ status: 'pending',
944
+ priority: 'medium'
945
+ },
946
+ {
947
+ id: this.generateId('todo'),
948
+ content: 'Test solution thoroughly',
949
+ status: 'pending',
950
+ priority: 'high'
951
+ },
952
+ {
953
+ id: this.generateId('todo'),
954
+ content: 'Deploy to ServiceNow',
955
+ status: 'pending',
956
+ priority: 'high'
957
+ },
958
+ {
959
+ id: this.generateId('todo'),
960
+ content: 'Monitor and validate deployment',
961
+ status: 'pending',
962
+ priority: 'medium'
963
+ }
964
+ ];
965
+
966
+ return todos;
967
+ }
968
+
969
+ /**
970
+ * Analyze todo dependencies
971
+ */
972
+ private analyzeTodoDependencies(todos: TodoItem[]): Map<string, string[]> {
973
+ const dependencies = new Map<string, string[]>();
974
+
975
+ // Simple dependency _analysis - each todo depends on all previous high priority todos
976
+ const highPriorityTodos = todos.filter(t => t.priority === 'high');
977
+
978
+ highPriorityTodos.forEach((todo, index) => {
979
+ if (index > 0) {
980
+ const prevHighPriorityIds = highPriorityTodos
981
+ .slice(0, index)
982
+ .map(t => t.id);
983
+ dependencies.set(todo.id, prevHighPriorityIds);
984
+ }
985
+ });
986
+
987
+ return dependencies;
988
+ }
989
+
990
+ /**
991
+ * Assign todos to agent based on capabilities
992
+ */
993
+ private async assignTodosToAgent(agent: Agent, objectiveId: string): Promise<void> {
994
+ const todoCoordination = this.todoCoordinations.get(objectiveId);
995
+ if (!todoCoordination) return;
996
+
997
+ const unassignedTodos = todoCoordination.todos.filter(todo =>
998
+ !Array.from(todoCoordination.agentAssignments.values()).includes(todo.id) &&
999
+ todo.status === 'pending'
1000
+ );
1001
+
1002
+ // Assign todos based on agent type and specialization
1003
+ const assignableTodos = unassignedTodos.filter(todo =>
1004
+ this.canAgentHandleTodo(agent, todo)
1005
+ );
1006
+
1007
+ for (const todo of assignableTodos) {
1008
+ todoCoordination.agentAssignments.set(todo.id, agent.id);
1009
+
1010
+ // Update agent's assigned todos in memory
1011
+ const agentData = await this.memory.get(`agent_${agent.id}`) as any;
1012
+ if (agentData) {
1013
+ agentData.assignedTodos.push(todo.id);
1014
+ await this.memory.store(`agent_${agent.id}`, agentData);
1015
+ }
1016
+ }
1017
+
1018
+ this.emit('todos:assigned', { agent, todos: assignableTodos });
1019
+ }
1020
+
1021
+ /**
1022
+ * Check if agent can handle specific todo
1023
+ */
1024
+ private canAgentHandleTodo(agent: Agent, todo: TodoItem): boolean {
1025
+ const todoContent = todo.content.toLowerCase();
1026
+
1027
+ switch (agent.type) {
1028
+ case 'widget-creator':
1029
+ return todoContent.includes('widget') ||
1030
+ todoContent.includes('html') ||
1031
+ todoContent.includes('portal') ||
1032
+ todoContent.includes('ui');
1033
+
1034
+ case 'css-specialist':
1035
+ return todoContent.includes('style') ||
1036
+ todoContent.includes('css') ||
1037
+ todoContent.includes('responsive') ||
1038
+ todoContent.includes('theme');
1039
+
1040
+ case 'backend-specialist':
1041
+ return todoContent.includes('server') ||
1042
+ todoContent.includes('backend') ||
1043
+ todoContent.includes('data') ||
1044
+ todoContent.includes('api');
1045
+
1046
+ case 'frontend-specialist':
1047
+ return todoContent.includes('client') ||
1048
+ todoContent.includes('controller') ||
1049
+ todoContent.includes('interactive') ||
1050
+ todoContent.includes('event');
1051
+
1052
+ case 'flow-builder':
1053
+ return todoContent.includes('flow') ||
1054
+ todoContent.includes('workflow') ||
1055
+ todoContent.includes('trigger') ||
1056
+ todoContent.includes('action');
1057
+
1058
+ case 'script-writer':
1059
+ return todoContent.includes('script') ||
1060
+ todoContent.includes('logic') ||
1061
+ todoContent.includes('function');
1062
+
1063
+ case 'integration-specialist':
1064
+ return todoContent.includes('integration') ||
1065
+ todoContent.includes('external') ||
1066
+ todoContent.includes('api') ||
1067
+ todoContent.includes('rest');
1068
+
1069
+ case 'tester':
1070
+ return todoContent.includes('test') ||
1071
+ todoContent.includes('validate') ||
1072
+ todoContent.includes('verify');
1073
+
1074
+ case 'security-specialist':
1075
+ return todoContent.includes('security') ||
1076
+ todoContent.includes('permission') ||
1077
+ todoContent.includes('access') ||
1078
+ todoContent.includes('vulnerability');
1079
+
1080
+ case 'performance-specialist':
1081
+ return todoContent.includes('performance') ||
1082
+ todoContent.includes('optimization') ||
1083
+ todoContent.includes('caching');
1084
+
1085
+ case 'ui-ux-specialist':
1086
+ return todoContent.includes('user experience') ||
1087
+ todoContent.includes('design') ||
1088
+ todoContent.includes('ux');
1089
+
1090
+ case 'page-designer':
1091
+ return todoContent.includes('portal page') ||
1092
+ todoContent.includes('page layout') ||
1093
+ todoContent.includes('page structure') ||
1094
+ todoContent.includes('place widget') ||
1095
+ todoContent.includes('configure page') ||
1096
+ todoContent.includes('containers') ||
1097
+ todoContent.includes('rows') ||
1098
+ todoContent.includes('columns') ||
1099
+ todoContent.includes('page permissions') ||
1100
+ todoContent.includes('portal navigation');
1101
+
1102
+ default:
1103
+ // Generic agents can handle setup and coordination tasks
1104
+ return todoContent.includes('initialize') ||
1105
+ todoContent.includes('validate') ||
1106
+ todoContent.includes('create update set') ||
1107
+ todoContent.includes('documentation');
1108
+ }
1109
+ }
1110
+
1111
+ /**
1112
+ * Monitor agent progress through todo updates
1113
+ */
1114
+ async monitorProgress(objectiveId: string): Promise<{
1115
+ overall: number;
1116
+ byAgent: Map<string, number>;
1117
+ blockingIssues: string[];
1118
+ estimatedCompletion: Date;
1119
+ }> {
1120
+ const todoCoordination = this.todoCoordinations.get(objectiveId);
1121
+ if (!todoCoordination) {
1122
+ throw new Error(`No todo coordination found for objective: ${objectiveId}`);
1123
+ }
1124
+
1125
+ // Calculate progress from todos
1126
+ const completedTodos = todoCoordination.todos.filter(t => t.status === 'completed').length;
1127
+ const totalTodos = todoCoordination.todos.length;
1128
+ const overallProgress = totalTodos > 0 ? (completedTodos / totalTodos) * 100 : 0;
1129
+
1130
+ // Calculate per-agent progress
1131
+ const byAgent = new Map<string, number>();
1132
+ for (const [todoId, agentId] of todoCoordination.agentAssignments) {
1133
+ const agentTodos = Array.from(todoCoordination.agentAssignments.entries())
1134
+ .filter(([_, aid]) => aid === agentId);
1135
+ const agentCompleted = agentTodos.filter(([tid, _]) =>
1136
+ todoCoordination.todos.find(t => t.id === tid)?.status === 'completed'
1137
+ ).length;
1138
+ const agentProgress = agentTodos.length > 0 ? (agentCompleted / agentTodos.length) * 100 : 0;
1139
+ byAgent.set(agentId, agentProgress);
1140
+ }
1141
+
1142
+ // Identify blocking issues
1143
+ const blockingIssues = await this.identifyBlockingIssues(todoCoordination);
1144
+
1145
+ // Estimate completion based on current velocity
1146
+ const estimatedCompletion = this.estimateCompletion(todoCoordination, overallProgress);
1147
+
1148
+ // Store progress in memory
1149
+ await this.memory.store(`progress_${objectiveId}`, {
1150
+ overall: overallProgress,
1151
+ byAgent: Object.fromEntries(byAgent),
1152
+ blockingIssues,
1153
+ estimatedCompletion: estimatedCompletion.toISOString(),
1154
+ timestamp: new Date().toISOString()
1155
+ });
1156
+
1157
+ this.emit('progress:updated', { objectiveId, overall: overallProgress, byAgent, blockingIssues });
1158
+
1159
+ return {
1160
+ overall: overallProgress,
1161
+ byAgent,
1162
+ blockingIssues,
1163
+ estimatedCompletion
1164
+ };
1165
+ }
1166
+
1167
+ /**
1168
+ * Make memory-driven decisions based on past patterns
1169
+ */
1170
+ async makeDecision(context: {
1171
+ objective: string;
1172
+ currentState: any;
1173
+ options: string[];
1174
+ }): Promise<{
1175
+ decision: string;
1176
+ confidence: number;
1177
+ reasoning: string;
1178
+ }> {
1179
+ // Query memory for similar past decisions
1180
+ const similarPatterns = await this.memory.findSimilarPatterns(context.objective);
1181
+
1182
+ // Analyze success rates of past decisions
1183
+ const successRates = new Map<string, number>();
1184
+ for (const option of context.options) {
1185
+ const pastOutcomes = similarPatterns.filter(p => p.decision === option);
1186
+ const successRate = pastOutcomes.length > 0
1187
+ ? pastOutcomes.filter(p => p.outcome === 'success').length / pastOutcomes.length
1188
+ : 0.5; // Default to 50% if no history
1189
+ successRates.set(option, successRate);
1190
+ }
1191
+
1192
+ // Choose option with highest success rate
1193
+ let bestOption = context.options[0];
1194
+ let highestRate = 0;
1195
+
1196
+ for (const [option, rate] of successRates) {
1197
+ if (rate > highestRate) {
1198
+ highestRate = rate;
1199
+ bestOption = option;
1200
+ }
1201
+ }
1202
+
1203
+ const confidence = highestRate > 0.7 ? 0.9 : highestRate > 0.5 ? 0.7 : 0.5;
1204
+
1205
+ const decision = {
1206
+ decision: bestOption,
1207
+ confidence,
1208
+ reasoning: `Based on ${similarPatterns.length} similar past scenarios, "${bestOption}" has a ${(highestRate * 100).toFixed(0)}% success rate.`
1209
+ };
1210
+
1211
+ // Store decision for future learning
1212
+ await this.memory.storeDecision('decision', {
1213
+ context,
1214
+ decision: decision.decision,
1215
+ confidence: decision.confidence,
1216
+ timestamp: new Date().toISOString()
1217
+ });
1218
+
1219
+ this.emit('decision:made', decision);
1220
+
1221
+ return decision;
1222
+ }
1223
+
1224
+ /**
1225
+ * Setup event handlers for coordination
1226
+ */
1227
+ private setupEventHandlers(): void {
1228
+ // Handle agent lifecycle events
1229
+ this.coordinator.on('agent:ready', async (data) => {
1230
+ console.log(`✅ Agent ${data.agentId} ready for tasks`);
1231
+ await this.assignTodosToAgent(
1232
+ this.activeAgents.get(data.agentId)!,
1233
+ data.objectiveId
1234
+ );
1235
+ });
1236
+
1237
+ this.coordinator.on('agent:completed', async (data) => {
1238
+ console.log(`✅ Agent ${data.agentId} completed all tasks`);
1239
+ this.activeAgents.delete(data.agentId);
1240
+
1241
+ // Check if we need to spawn more agents
1242
+ if (this.config.autoSpawn) {
1243
+ await this.checkAndSpawnAgents(data.objectiveId);
1244
+ }
1245
+ });
1246
+
1247
+ this.coordinator.on('agent:error', async (data) => {
1248
+ console.error(`❌ Agent ${data.agentId} encountered error:`, data.error);
1249
+
1250
+ // Handle 403 errors specifically
1251
+ if (this.is403Error(data.error)) {
1252
+ const handled = await this.handleDeploymentError(data.error, {
1253
+ objectiveId: data.objectiveId,
1254
+ agentId: data.agentId,
1255
+ operation: 'deployment',
1256
+ artifactType: data.artifactType
1257
+ });
1258
+
1259
+ if (handled) {
1260
+ // Retry the agent's task
1261
+ this.emit('agent:retry', data);
1262
+ }
1263
+ }
1264
+ });
1265
+ }
1266
+
1267
+ /**
1268
+ * Check if more agents need to be spawned
1269
+ */
1270
+ private async checkAndSpawnAgents(objectiveId: string): Promise<void> {
1271
+ const todoCoordination = this.todoCoordinations.get(objectiveId);
1272
+ if (!todoCoordination) return;
1273
+
1274
+ const unassignedTodos = todoCoordination.todos.filter(todo =>
1275
+ !Array.from(todoCoordination.agentAssignments.values()).includes(todo.id) &&
1276
+ todo.status === 'pending'
1277
+ );
1278
+
1279
+ if (unassignedTodos.length > 0 && this.activeAgents.size < this.config.maxConcurrentAgents) {
1280
+ // Spawn additional agents if needed
1281
+ await this.spawnAgents(objectiveId);
1282
+ }
1283
+ }
1284
+
1285
+ /**
1286
+ * Handle coordination errors
1287
+ */
1288
+ private async handleCoordinationError(error: any, context: any): Promise<void> {
1289
+ console.error('❌ Coordination error:', error);
1290
+
1291
+ // Store error in memory for learning - using store method
1292
+ await this.memory.store('error', {
1293
+ error: error.message || error,
1294
+ context,
1295
+ timestamp: new Date().toISOString(),
1296
+ recovery: null
1297
+ });
1298
+
1299
+ this.emit('coordination:error', { error, context });
1300
+ }
1301
+
1302
+ /**
1303
+ * Identify blocking issues from todos
1304
+ */
1305
+ private async identifyBlockingIssues(todoCoordination: TodoCoordination): Promise<string[]> {
1306
+ const issues: string[] = [];
1307
+
1308
+ // Check for failed todos
1309
+ const failedTodos = todoCoordination.todos.filter(t => t.status === 'failed' as TodoStatus);
1310
+ if (failedTodos.length > 0) {
1311
+ issues.push(`${failedTodos.length} failed tasks blocking progress`);
1312
+ }
1313
+
1314
+ // Check for stuck in-progress todos (older than 10 minutes)
1315
+ const stuckTodos = todoCoordination.todos.filter(t => {
1316
+ if (t.status !== 'in_progress') return false;
1317
+ const todoData = this.memory.get(`todo_${t.id}`) as any;
1318
+ if (!todoData || !todoData.startTime) return false;
1319
+ return Date.now() - todoData.startTime > 10 * 60 * 1000; // 10 minutes
1320
+ });
1321
+
1322
+ if (stuckTodos.length > 0) {
1323
+ issues.push(`${stuckTodos.length} tasks stuck in progress`);
1324
+ }
1325
+
1326
+ // Check for dependency bottlenecks
1327
+ const pendingWithDeps = todoCoordination.todos.filter(t =>
1328
+ t.status === 'pending' &&
1329
+ todoCoordination.dependencies.has(t.id)
1330
+ );
1331
+
1332
+ for (const todo of pendingWithDeps) {
1333
+ const deps = todoCoordination.dependencies.get(todo.id) || [];
1334
+ const incompleteDeps = deps.filter(depId => {
1335
+ const depTodo = todoCoordination.todos.find(t => t.id === depId);
1336
+ return depTodo && depTodo.status !== 'completed';
1337
+ });
1338
+
1339
+ if (incompleteDeps.length === deps.length) {
1340
+ issues.push(`Task "${todo.content}" blocked by dependencies`);
1341
+ }
1342
+ }
1343
+
1344
+ return issues;
1345
+ }
1346
+
1347
+ /**
1348
+ * Estimate completion time based on current progress
1349
+ */
1350
+ private estimateCompletion(todoCoordination: TodoCoordination, currentProgress: number): Date {
1351
+ if (currentProgress === 0) {
1352
+ return new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours if no progress
1353
+ }
1354
+
1355
+ const completedTodos = todoCoordination.todos.filter(t => t.status === 'completed').length;
1356
+ const startTime = this.activeObjectives.get(todoCoordination.objectiveId)?.metadata?.startTime || Date.now();
1357
+ const elapsedTime = Date.now() - startTime;
1358
+
1359
+ const averageTimePerTodo = elapsedTime / completedTodos;
1360
+ const remainingTodos = todoCoordination.todos.filter(t => t.status !== 'completed').length;
1361
+ const estimatedRemainingTime = averageTimePerTodo * remainingTodos;
1362
+
1363
+ return new Date(Date.now() + estimatedRemainingTime);
1364
+ }
1365
+
1366
+ /**
1367
+ * Generate unique ID for entities
1368
+ */
1369
+ private generateId(prefix: string): string {
1370
+ return `${prefix}_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`;
1371
+ }
1372
+
1373
+ /**
1374
+ * Shutdown queen agent gracefully
1375
+ */
1376
+ async shutdown(): Promise<void> {
1377
+ console.log('👑 Queen Agent shutting down...');
1378
+
1379
+ // Save current state
1380
+ for (const [objectiveId, objective] of this.activeObjectives) {
1381
+ await this.memory.store(`objective_state_${objectiveId}`, {
1382
+ objective,
1383
+ todoCoordination: this.todoCoordinations.get(objectiveId),
1384
+ activeAgents: Array.from(this.activeAgents.values()).filter(a => a.objectiveId === objectiveId),
1385
+ timestamp: new Date().toISOString()
1386
+ });
1387
+ }
1388
+
1389
+ // Notify all active agents
1390
+ for (const agent of this.activeAgents.values()) {
1391
+ this.emit('agent:shutdown', agent);
1392
+ }
1393
+
1394
+ await this.memory.close();
1395
+ this.removeAllListeners();
1396
+
1397
+ console.log('✅ Queen Agent shutdown complete');
1398
+ }
1399
+ }