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,1435 @@
1
+ /**
2
+ * 🤖 Self-Healing System for Autonomous Error Recovery
3
+ *
4
+ * Advanced autonomous system that detects, diagnoses, and automatically
5
+ * recovers from errors without manual intervention, ensuring maximum
6
+ * system availability and reliability.
7
+ */
8
+
9
+ import { Logger } from '../utils/logger.js';
10
+ import { ServiceNowClient } from '../utils/servicenow-client.js';
11
+ import { MemorySystem } from '../memory/memory-system.js';
12
+
13
+ export interface HealingProfile {
14
+ id: string;
15
+ systemName: string;
16
+ assessmentDate: string;
17
+ healthScore: number;
18
+ incidents: HealthIncident[];
19
+ healingActions: HealingAction[];
20
+ patterns: ErrorPattern[];
21
+ predictions: HealthPrediction[];
22
+ recoveryStrategies: RecoveryStrategy[];
23
+ systemMetrics: SystemMetrics;
24
+ recommendations: HealingRecommendation[];
25
+ metadata: HealingMetadata;
26
+ }
27
+
28
+ export interface HealthIncident {
29
+ id: string;
30
+ type: 'error' | 'performance' | 'availability' | 'security' | 'data-integrity';
31
+ severity: 'critical' | 'high' | 'medium' | 'low';
32
+ title: string;
33
+ description: string;
34
+ detectedAt: string;
35
+ status: 'active' | 'healing' | 'resolved' | 'escalated';
36
+ rootCause?: RootCause;
37
+ impact: IncidentImpact;
38
+ healingAttempts: number;
39
+ resolvedAt?: string;
40
+ resolutionMethod?: string;
41
+ }
42
+
43
+ export interface RootCause {
44
+ id: string;
45
+ category: 'code' | 'configuration' | 'resource' | 'external' | 'data' | 'network';
46
+ description: string;
47
+ confidence: number; // 0-1
48
+ evidence: string[];
49
+ relatedIncidents: string[];
50
+ preventable: boolean;
51
+ }
52
+
53
+ export interface IncidentImpact {
54
+ users: number;
55
+ services: string[];
56
+ availability: number; // percentage
57
+ performance: number; // degradation percentage
58
+ dataLoss: boolean;
59
+ financialImpact?: number;
60
+ duration: number; // milliseconds
61
+ }
62
+
63
+ export interface HealingAction {
64
+ id: string;
65
+ incidentId: string;
66
+ type: 'restart' | 'rollback' | 'patch' | 'scale' | 'reroute' | 'cleanup' | 'restore';
67
+ title: string;
68
+ description: string;
69
+ status: 'pending' | 'executing' | 'completed' | 'failed' | 'rolled-back';
70
+ automated: boolean;
71
+ executionSteps: HealingStep[];
72
+ startTime?: string;
73
+ endTime?: string;
74
+ result?: HealingResult;
75
+ rollbackPlan?: string;
76
+ }
77
+
78
+ export interface HealingStep {
79
+ order: number;
80
+ action: string;
81
+ target: string;
82
+ parameters: Record<string, any>;
83
+ status: 'pending' | 'executing' | 'completed' | 'failed' | 'skipped';
84
+ output?: string;
85
+ error?: string;
86
+ duration?: number;
87
+ }
88
+
89
+ export interface HealingResult {
90
+ success: boolean;
91
+ message: string;
92
+ metricsAfter: {
93
+ availability: number;
94
+ performance: number;
95
+ errorRate: number;
96
+ };
97
+ sideEffects: string[];
98
+ verificationPassed: boolean;
99
+ }
100
+
101
+ export interface ErrorPattern {
102
+ id: string;
103
+ name: string;
104
+ description: string;
105
+ signature: PatternSignature;
106
+ occurrences: number;
107
+ lastSeen: string;
108
+ avgResolutionTime: number;
109
+ successRate: number;
110
+ recommendedActions: string[];
111
+ autoHealable: boolean;
112
+ }
113
+
114
+ export interface PatternSignature {
115
+ errorTypes: string[];
116
+ keywords: string[];
117
+ frequency: 'sporadic' | 'recurring' | 'persistent';
118
+ timePattern?: string;
119
+ correlations: string[];
120
+ }
121
+
122
+ export interface HealthPrediction {
123
+ id: string;
124
+ type: 'failure' | 'degradation' | 'capacity' | 'security';
125
+ component: string;
126
+ probability: number; // 0-1
127
+ timeframe: string;
128
+ impact: 'critical' | 'high' | 'medium' | 'low';
129
+ preventiveActions: PreventiveAction[];
130
+ confidence: number; // 0-1
131
+ basedOn: string[];
132
+ }
133
+
134
+ export interface PreventiveAction {
135
+ action: string;
136
+ priority: 'immediate' | 'high' | 'medium' | 'low';
137
+ estimatedPrevention: number; // percentage
138
+ cost: 'minimal' | 'moderate' | 'significant';
139
+ automatable: boolean;
140
+ }
141
+
142
+ export interface RecoveryStrategy {
143
+ id: string;
144
+ name: string;
145
+ description: string;
146
+ applicableTo: string[];
147
+ steps: RecoveryStep[];
148
+ estimatedTime: number;
149
+ successRate: number;
150
+ requirements: string[];
151
+ risks: string[];
152
+ }
153
+
154
+ export interface RecoveryStep {
155
+ order: number;
156
+ action: string;
157
+ automated: boolean;
158
+ timeout: number;
159
+ verification: string;
160
+ fallback?: string;
161
+ }
162
+
163
+ export interface SystemMetrics {
164
+ availability: {
165
+ current: number;
166
+ target: number;
167
+ trend: 'improving' | 'stable' | 'degrading';
168
+ };
169
+ performance: {
170
+ responseTime: number;
171
+ throughput: number;
172
+ errorRate: number;
173
+ trend: 'improving' | 'stable' | 'degrading';
174
+ };
175
+ reliability: {
176
+ mtbf: number; // mean time between failures
177
+ mttr: number; // mean time to recovery
178
+ failureRate: number;
179
+ };
180
+ capacity: {
181
+ cpu: number;
182
+ memory: number;
183
+ storage: number;
184
+ network: number;
185
+ };
186
+ }
187
+
188
+ export interface HealingRecommendation {
189
+ id: string;
190
+ category: 'architecture' | 'monitoring' | 'redundancy' | 'automation' | 'capacity';
191
+ priority: 'critical' | 'high' | 'medium' | 'low';
192
+ title: string;
193
+ description: string;
194
+ benefit: string;
195
+ effort: 'minimal' | 'moderate' | 'significant' | 'major';
196
+ preventedIncidents: number;
197
+ roi: number; // return on investment percentage
198
+ }
199
+
200
+ export interface HealingMetadata {
201
+ monitoringEnabled: boolean;
202
+ autoHealingEnabled: boolean;
203
+ learningMode: boolean;
204
+ retentionDays: number;
205
+ integrations: string[];
206
+ lastFullScan: string;
207
+ nextScheduledScan: string;
208
+ }
209
+
210
+ export interface HealingRequest {
211
+ scope?: 'full' | 'incremental' | 'specific-services';
212
+ services?: string[];
213
+ autoHeal?: boolean;
214
+ predictive?: boolean;
215
+ learning?: boolean;
216
+ }
217
+
218
+ export interface HealingResponse {
219
+ success: boolean;
220
+ profile: HealingProfile;
221
+ incidentsDetected: number;
222
+ incidentsHealed: number;
223
+ predictionsGenerated: number;
224
+ recommendations: string[];
225
+ warnings: string[];
226
+ }
227
+
228
+ export class SelfHealingSystem {
229
+ private logger: Logger;
230
+ private client: ServiceNowClient;
231
+ private memory: MemorySystem;
232
+ private healingProfiles: Map<string, HealingProfile> = new Map();
233
+ private activeIncidents: Map<string, HealthIncident> = new Map();
234
+ private errorPatterns: Map<string, ErrorPattern> = new Map();
235
+ private recoveryStrategies: Map<string, RecoveryStrategy> = new Map();
236
+ private monitoringActive: boolean = true;
237
+ private learningEngine: LearningEngine;
238
+
239
+ constructor(client: ServiceNowClient, memory: MemorySystem) {
240
+ this.logger = new Logger('SelfHealingSystem');
241
+ this.client = client;
242
+ this.memory = memory;
243
+ this.learningEngine = new LearningEngine(memory);
244
+
245
+ this.initializeRecoveryStrategies();
246
+ this.startHealthMonitoring();
247
+ }
248
+
249
+ /**
250
+ * Perform system health assessment and healing
251
+ */
252
+ async performHealthCheck(request: HealingRequest = {}): Promise<HealingResponse> {
253
+ this.logger.info('🏥 Performing system health check', request);
254
+
255
+ const profileId = `heal_${Date.now()}_${Math.random().toString(36).substr(2, 8)}`;
256
+ const startTime = Date.now();
257
+
258
+ try {
259
+ // Detect health incidents
260
+ const incidents = await this.detectHealthIncidents(request);
261
+
262
+ // Analyze root causes
263
+ for (const incident of incidents) {
264
+ incident.rootCause = await this.analyzeRootCause(incident);
265
+ }
266
+
267
+ // Identify error patterns
268
+ const patterns = await this.identifyErrorPatterns(incidents);
269
+
270
+ // Generate predictions if requested
271
+ let predictions: HealthPrediction[] = [];
272
+ if (request.predictive) {
273
+ predictions = await this.generateHealthPredictions(incidents, patterns);
274
+ }
275
+
276
+ // Create healing actions
277
+ const healingActions = await this.createHealingActions(incidents);
278
+
279
+ // Execute auto-healing if enabled
280
+ let healedCount = 0;
281
+ if (request.autoHeal) {
282
+ healedCount = await this.executeAutoHealing(healingActions);
283
+ }
284
+
285
+ // Generate recovery strategies
286
+ const strategies = await this.generateRecoveryStrategies(patterns);
287
+
288
+ // Collect system metrics
289
+ const metrics = await this.collectSystemMetrics();
290
+
291
+ // Generate recommendations
292
+ const recommendations = await this.generateHealingRecommendations(incidents, patterns, metrics);
293
+
294
+ const profile: HealingProfile = {
295
+ id: profileId,
296
+ systemName: 'ServiceNow Multi-Agent System',
297
+ assessmentDate: new Date().toISOString(),
298
+ healthScore: this.calculateHealthScore(metrics, incidents),
299
+ incidents,
300
+ healingActions,
301
+ patterns,
302
+ predictions,
303
+ recoveryStrategies: strategies,
304
+ systemMetrics: metrics,
305
+ recommendations,
306
+ metadata: {
307
+ monitoringEnabled: true,
308
+ autoHealingEnabled: request.autoHeal || false,
309
+ learningMode: request.learning || true,
310
+ retentionDays: 90,
311
+ integrations: ['ServiceNow', 'Memory System', 'Monitoring'],
312
+ lastFullScan: new Date().toISOString(),
313
+ nextScheduledScan: new Date(Date.now() + 3600000).toISOString()
314
+ }
315
+ };
316
+
317
+ // Store profile
318
+ this.healingProfiles.set(profileId, profile);
319
+ await this.memory.store(`healing_profile_${profileId}`, profile, 7776000000); // 90 days
320
+
321
+ // Update learning engine if enabled
322
+ if (request.learning) {
323
+ await this.learningEngine.learn(incidents, healingActions);
324
+ }
325
+
326
+ this.logger.info('✅ Health check completed', {
327
+ profileId,
328
+ healthScore: profile.healthScore,
329
+ incidentsDetected: incidents.length,
330
+ incidentsHealed: healedCount,
331
+ predictionsGenerated: predictions.length
332
+ });
333
+
334
+ return {
335
+ success: true,
336
+ profile,
337
+ incidentsDetected: incidents.length,
338
+ incidentsHealed: healedCount,
339
+ predictionsGenerated: predictions.length,
340
+ recommendations: recommendations.map(r => r.title),
341
+ warnings: this.generateWarnings(profile)
342
+ };
343
+
344
+ } catch (error) {
345
+ this.logger.error('❌ Health check failed', error);
346
+ throw error;
347
+ }
348
+ }
349
+
350
+ /**
351
+ * Start autonomous self-healing
352
+ */
353
+ async startAutonomousHealing(options: {
354
+ checkInterval?: number;
355
+ healingThreshold?: number;
356
+ maxRetries?: number;
357
+ preventive?: boolean;
358
+ } = {}): Promise<void> {
359
+ this.logger.info('🤖 Starting autonomous self-healing', options);
360
+
361
+ const interval = options.checkInterval || 300000; // Default: 5 minutes
362
+ const threshold = options.healingThreshold || 0.8; // 80% confidence
363
+
364
+ setInterval(async () => {
365
+ try {
366
+ // Perform incremental health check
367
+ const result = await this.performHealthCheck({
368
+ scope: 'incremental',
369
+ autoHeal: true,
370
+ predictive: options.preventive || true,
371
+ learning: true
372
+ });
373
+
374
+ // Handle critical incidents
375
+ const criticalIncidents = result.profile.incidents.filter(
376
+ i => i.severity === 'critical' && i.status === 'active'
377
+ );
378
+
379
+ if (criticalIncidents.length > 0) {
380
+ await this.handleCriticalIncidents(criticalIncidents);
381
+ }
382
+
383
+ // Execute preventive actions
384
+ if (options.preventive) {
385
+ await this.executePreventiveActions(result.profile.predictions);
386
+ }
387
+
388
+ } catch (error) {
389
+ this.logger.error('Error in autonomous healing', error);
390
+ // Self-heal the self-healing system
391
+ await this.healSelf(error);
392
+ }
393
+ }, interval);
394
+ }
395
+
396
+ /**
397
+ * Get real-time health dashboard
398
+ */
399
+ async getHealthDashboard(): Promise<{
400
+ systemHealth: string;
401
+ healthScore: number;
402
+ activeIncidents: HealthIncident[];
403
+ recentHealing: HealingAction[];
404
+ systemMetrics: SystemMetrics;
405
+ predictions: HealthPrediction[];
406
+ recommendations: HealingRecommendation[];
407
+ }> {
408
+ const latestProfile = this.getLatestHealingProfile();
409
+
410
+ if (!latestProfile) {
411
+ const result = await this.performHealthCheck();
412
+ return this.generateDashboard(result.profile);
413
+ }
414
+
415
+ return this.generateDashboard(latestProfile);
416
+ }
417
+
418
+ /**
419
+ * Manually trigger healing action
420
+ */
421
+ async executeHealingAction(
422
+ actionId: string,
423
+ options: {
424
+ verify?: boolean;
425
+ monitor?: boolean;
426
+ rollbackOnFailure?: boolean;
427
+ } = {}
428
+ ): Promise<{
429
+ success: boolean;
430
+ result: HealingResult;
431
+ duration: number;
432
+ }> {
433
+ this.logger.info('💊 Executing healing action', { actionId, options });
434
+
435
+ const action = await this.getHealingAction(actionId);
436
+ if (!action) {
437
+ throw new Error(`Healing action not found: ${actionId}`);
438
+ }
439
+
440
+ const startTime = Date.now();
441
+
442
+ try {
443
+ // Verify if requested
444
+ if (options.verify) {
445
+ const verification = await this.verifyHealingSafety(action);
446
+ if (!verification.safe) {
447
+ throw new Error(`Healing verification failed: ${verification.reason}`);
448
+ }
449
+ }
450
+
451
+ // Execute healing steps
452
+ action.status = 'executing';
453
+ action.startTime = new Date().toISOString();
454
+
455
+ const result = await this.executeHealingSteps(action);
456
+
457
+ // Monitor if requested
458
+ if (options.monitor) {
459
+ await this.monitorHealingProgress(action, result);
460
+ }
461
+
462
+ // Handle failure with rollback
463
+ if (!result.success && options.rollbackOnFailure) {
464
+ await this.rollbackHealing(action);
465
+ throw new Error(`Healing failed and was rolled back: ${result.message}`);
466
+ }
467
+
468
+ // Update action status
469
+ action.status = result.success ? 'completed' : 'failed';
470
+ action.endTime = new Date().toISOString();
471
+ action.result = result;
472
+
473
+ const duration = Date.now() - startTime;
474
+
475
+ return {
476
+ success: result.success,
477
+ result,
478
+ duration
479
+ };
480
+
481
+ } catch (error) {
482
+ this.logger.error('❌ Healing action failed', error);
483
+ action.status = 'failed';
484
+ throw error;
485
+ }
486
+ }
487
+
488
+ /**
489
+ * Private helper methods
490
+ */
491
+
492
+ private initializeRecoveryStrategies(): void {
493
+ // Initialize common recovery strategies
494
+ this.recoveryStrategies.set('restart_service', {
495
+ id: 'restart_service',
496
+ name: 'Service Restart',
497
+ description: 'Restart affected service to clear transient errors',
498
+ applicableTo: ['error', 'performance'],
499
+ steps: [
500
+ {
501
+ order: 1,
502
+ action: 'Gracefully stop service',
503
+ automated: true,
504
+ timeout: 30000,
505
+ verification: 'Service stopped',
506
+ fallback: 'Force stop service'
507
+ },
508
+ {
509
+ order: 2,
510
+ action: 'Clear temporary data',
511
+ automated: true,
512
+ timeout: 10000,
513
+ verification: 'Temp data cleared'
514
+ },
515
+ {
516
+ order: 3,
517
+ action: 'Start service',
518
+ automated: true,
519
+ timeout: 60000,
520
+ verification: 'Service healthy'
521
+ }
522
+ ],
523
+ estimatedTime: 120000,
524
+ successRate: 85,
525
+ requirements: ['Service control permissions'],
526
+ risks: ['Brief downtime']
527
+ });
528
+
529
+ this.recoveryStrategies.set('rollback_deployment', {
530
+ id: 'rollback_deployment',
531
+ name: 'Deployment Rollback',
532
+ description: 'Rollback to previous stable version',
533
+ applicableTo: ['error', 'availability'],
534
+ steps: [
535
+ {
536
+ order: 1,
537
+ action: 'Identify rollback point',
538
+ automated: true,
539
+ timeout: 5000,
540
+ verification: 'Rollback point valid'
541
+ },
542
+ {
543
+ order: 2,
544
+ action: 'Execute rollback',
545
+ automated: true,
546
+ timeout: 300000,
547
+ verification: 'Rollback completed'
548
+ },
549
+ {
550
+ order: 3,
551
+ action: 'Verify system stability',
552
+ automated: true,
553
+ timeout: 60000,
554
+ verification: 'System stable'
555
+ }
556
+ ],
557
+ estimatedTime: 600000,
558
+ successRate: 95,
559
+ requirements: ['Rollback points available'],
560
+ risks: ['Feature regression']
561
+ });
562
+
563
+ this.recoveryStrategies.set('scale_resources', {
564
+ id: 'scale_resources',
565
+ name: 'Resource Scaling',
566
+ description: 'Scale up resources to handle load',
567
+ applicableTo: ['performance', 'availability'],
568
+ steps: [
569
+ {
570
+ order: 1,
571
+ action: 'Analyze resource usage',
572
+ automated: true,
573
+ timeout: 10000,
574
+ verification: 'Bottleneck identified'
575
+ },
576
+ {
577
+ order: 2,
578
+ action: 'Scale resources',
579
+ automated: true,
580
+ timeout: 120000,
581
+ verification: 'Resources scaled'
582
+ },
583
+ {
584
+ order: 3,
585
+ action: 'Load balance traffic',
586
+ automated: true,
587
+ timeout: 30000,
588
+ verification: 'Traffic balanced'
589
+ }
590
+ ],
591
+ estimatedTime: 180000,
592
+ successRate: 90,
593
+ requirements: ['Scaling capability'],
594
+ risks: ['Increased costs']
595
+ });
596
+ }
597
+
598
+ private async detectHealthIncidents(request: HealingRequest): Promise<HealthIncident[]> {
599
+ const incidents: HealthIncident[] = [];
600
+
601
+ // Check system logs for errors
602
+ const errorLogs = await this.checkErrorLogs();
603
+ for (const error of errorLogs) {
604
+ incidents.push({
605
+ id: `inc_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
606
+ type: 'error',
607
+ severity: this.determineSeverity(error),
608
+ title: error.message,
609
+ description: error.stack || error.message,
610
+ detectedAt: new Date().toISOString(),
611
+ status: 'active',
612
+ impact: {
613
+ users: error.affectedUsers || 0,
614
+ services: error.affectedServices || [],
615
+ availability: 100,
616
+ performance: 0,
617
+ dataLoss: false,
618
+ duration: 0
619
+ },
620
+ healingAttempts: 0
621
+ });
622
+ }
623
+
624
+ // Check performance metrics
625
+ const perfIssues = await this.checkPerformanceMetrics();
626
+ for (const issue of perfIssues) {
627
+ incidents.push({
628
+ id: `inc_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
629
+ type: 'performance',
630
+ severity: issue.severity,
631
+ title: `Performance degradation in ${issue.service}`,
632
+ description: `Response time increased by ${issue.degradation}%`,
633
+ detectedAt: new Date().toISOString(),
634
+ status: 'active',
635
+ impact: {
636
+ users: issue.affectedUsers,
637
+ services: [issue.service],
638
+ availability: 100,
639
+ performance: issue.degradation,
640
+ dataLoss: false,
641
+ duration: issue.duration
642
+ },
643
+ healingAttempts: 0
644
+ });
645
+ }
646
+
647
+ // Check availability
648
+ const availabilityIssues = await this.checkAvailability();
649
+ for (const issue of availabilityIssues) {
650
+ incidents.push({
651
+ id: `inc_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
652
+ type: 'availability',
653
+ severity: 'critical',
654
+ title: `Service unavailable: ${issue.service}`,
655
+ description: issue.reason,
656
+ detectedAt: new Date().toISOString(),
657
+ status: 'active',
658
+ impact: {
659
+ users: issue.affectedUsers,
660
+ services: [issue.service],
661
+ availability: 0,
662
+ performance: 100,
663
+ dataLoss: false,
664
+ duration: issue.downtime
665
+ },
666
+ healingAttempts: 0
667
+ });
668
+ }
669
+
670
+ return incidents;
671
+ }
672
+
673
+ private async analyzeRootCause(incident: HealthIncident): Promise<RootCause> {
674
+ // AI-powered root cause analysis
675
+ const relatedLogs = await this.getRelatedLogs(incident);
676
+ const systemState = await this.getSystemStateAt(incident.detectedAt);
677
+
678
+ // Analyze patterns
679
+ const category = this.categorizeRootCause(incident, relatedLogs);
680
+ const confidence = this.calculateConfidence(relatedLogs, systemState);
681
+
682
+ return {
683
+ id: `rc_${Date.now()}`,
684
+ category,
685
+ description: this.generateRootCauseDescription(incident, category, relatedLogs),
686
+ confidence,
687
+ evidence: relatedLogs.map(l => l.message),
688
+ relatedIncidents: await this.findRelatedIncidents(incident),
689
+ preventable: confidence > 0.7
690
+ };
691
+ }
692
+
693
+ private async identifyErrorPatterns(incidents: HealthIncident[]): Promise<ErrorPattern[]> {
694
+ const patterns: ErrorPattern[] = [];
695
+
696
+ // Group incidents by similarity
697
+ const groups = this.groupIncidentsBySimilarity(incidents);
698
+
699
+ for (const group of groups) {
700
+ if (group.length >= 2) { // Pattern requires at least 2 occurrences
701
+ const pattern: ErrorPattern = {
702
+ id: `pat_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
703
+ name: this.generatePatternName(group),
704
+ description: this.generatePatternDescription(group),
705
+ signature: {
706
+ errorTypes: [...new Set(group.map(i => i.type))],
707
+ keywords: this.extractKeywords(group),
708
+ frequency: this.determineFrequency(group),
709
+ correlations: this.findCorrelations(group)
710
+ },
711
+ occurrences: group.length,
712
+ lastSeen: group[group.length - 1].detectedAt,
713
+ avgResolutionTime: this.calculateAvgResolutionTime(group),
714
+ successRate: this.calculateSuccessRate(group),
715
+ recommendedActions: this.getRecommendedActions(group),
716
+ autoHealable: this.isAutoHealable(group)
717
+ };
718
+
719
+ patterns.push(pattern);
720
+ this.errorPatterns.set(pattern.id, pattern);
721
+ }
722
+ }
723
+
724
+ return patterns;
725
+ }
726
+
727
+ private async generateHealthPredictions(
728
+ incidents: HealthIncident[],
729
+ patterns: ErrorPattern[]
730
+ ): Promise<HealthPrediction[]> {
731
+ const predictions: HealthPrediction[] = [];
732
+
733
+ // Analyze trends
734
+ const trends = await this.analyzeTrends(incidents, patterns);
735
+
736
+ // Capacity predictions
737
+ const capacityIssues = await this.predictCapacityIssues();
738
+ for (const issue of capacityIssues) {
739
+ predictions.push({
740
+ id: `pred_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
741
+ type: 'capacity',
742
+ component: issue.component,
743
+ probability: issue.probability,
744
+ timeframe: issue.timeframe,
745
+ impact: issue.impact,
746
+ preventiveActions: [
747
+ {
748
+ action: `Scale ${issue.component} capacity`,
749
+ priority: issue.probability > 0.8 ? 'immediate' : 'high',
750
+ estimatedPrevention: 90,
751
+ cost: 'moderate',
752
+ automatable: true
753
+ }
754
+ ],
755
+ confidence: issue.confidence,
756
+ basedOn: ['Historical usage patterns', 'Current growth rate']
757
+ });
758
+ }
759
+
760
+ // Failure predictions based on patterns
761
+ for (const pattern of patterns) {
762
+ if ((pattern as any).frequency === 'recurring' || (pattern as any).frequency === 'persistent') {
763
+ const nextOccurrence = this.predictNextOccurrence(pattern);
764
+ if (nextOccurrence.probability > 0.6) {
765
+ predictions.push({
766
+ id: `pred_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
767
+ type: 'failure',
768
+ component: 'System',
769
+ probability: nextOccurrence.probability,
770
+ timeframe: nextOccurrence.timeframe,
771
+ impact: 'high',
772
+ preventiveActions: pattern.recommendedActions.map(action => ({
773
+ action,
774
+ priority: 'high',
775
+ estimatedPrevention: 80,
776
+ cost: 'minimal',
777
+ automatable: pattern.autoHealable
778
+ })),
779
+ confidence: 0.85,
780
+ basedOn: [`Pattern: ${pattern.name}`, `${pattern.occurrences} previous occurrences`]
781
+ });
782
+ }
783
+ }
784
+ }
785
+
786
+ return predictions;
787
+ }
788
+
789
+ private async createHealingActions(incidents: HealthIncident[]): Promise<HealingAction[]> {
790
+ const actions: HealingAction[] = [];
791
+
792
+ for (const incident of incidents) {
793
+ // Find matching recovery strategy
794
+ const strategy = this.findBestStrategy(incident);
795
+ if (!strategy) continue;
796
+
797
+ const action: HealingAction = {
798
+ id: `heal_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
799
+ incidentId: incident.id,
800
+ type: this.determineActionType(incident, strategy),
801
+ title: `Heal: ${incident.title}`,
802
+ description: `Apply ${strategy.name} to resolve ${incident.type} issue`,
803
+ status: 'pending',
804
+ automated: strategy.steps.every(s => s.automated),
805
+ executionSteps: strategy.steps.map(s => ({
806
+ order: s.order,
807
+ action: s.action,
808
+ target: incident.impact.services[0] || 'System',
809
+ parameters: {},
810
+ status: 'pending'
811
+ })),
812
+ rollbackPlan: 'Restore from pre-healing snapshot'
813
+ };
814
+
815
+ actions.push(action);
816
+ incident.healingAttempts++;
817
+ }
818
+
819
+ return actions;
820
+ }
821
+
822
+ private async executeAutoHealing(actions: HealingAction[]): Promise<number> {
823
+ let healedCount = 0;
824
+
825
+ for (const action of actions) {
826
+ if (action.automated && action.status === 'pending') {
827
+ try {
828
+ const result = await this.executeHealingSteps(action);
829
+ if (result.success) {
830
+ action.status = 'completed';
831
+ healedCount++;
832
+
833
+ // Update incident status
834
+ const incident = this.activeIncidents.get(action.incidentId);
835
+ if (incident) {
836
+ incident.status = 'resolved';
837
+ incident.resolvedAt = new Date().toISOString();
838
+ incident.resolutionMethod = action.type;
839
+ }
840
+ }
841
+ } catch (error) {
842
+ this.logger.error(`Failed to auto-heal action ${action.id}`, error);
843
+ action.status = 'failed';
844
+ }
845
+ }
846
+ }
847
+
848
+ return healedCount;
849
+ }
850
+
851
+ private async executeHealingSteps(action: HealingAction): Promise<HealingResult> {
852
+ const metricsBefor = await this.captureMetrics();
853
+ const sideEffects: string[] = [];
854
+
855
+ try {
856
+ for (const step of action.executionSteps) {
857
+ step.status = 'executing';
858
+
859
+ // Execute step based on action
860
+ switch (step.action) {
861
+ case 'Gracefully stop service':
862
+ await this.stopService(step.target);
863
+ step.output = 'Service stopped successfully';
864
+ break;
865
+ case 'Clear temporary data':
866
+ await this.clearTempData(step.target);
867
+ step.output = 'Temporary data cleared';
868
+ break;
869
+ case 'Start service':
870
+ await this.startService(step.target);
871
+ step.output = 'Service started successfully';
872
+ break;
873
+ default:
874
+ // Simulate other healing actions
875
+ await new Promise(resolve => setTimeout(resolve, 1000));
876
+ step.output = `${step.action} completed`;
877
+ }
878
+
879
+ step.status = 'completed';
880
+ step.duration = 1000; // Simulated duration
881
+ }
882
+
883
+ const metricsAfter = await this.captureMetrics();
884
+
885
+ return {
886
+ success: true,
887
+ message: 'Healing completed successfully',
888
+ metricsAfter: {
889
+ availability: metricsAfter.availability,
890
+ performance: metricsAfter.performance,
891
+ errorRate: metricsAfter.errorRate
892
+ },
893
+ sideEffects,
894
+ verificationPassed: true
895
+ };
896
+
897
+ } catch (error) {
898
+ return {
899
+ success: false,
900
+ message: `Healing failed: ${error instanceof Error ? error.message : String(error)}`,
901
+ metricsAfter: metricsBefor,
902
+ sideEffects,
903
+ verificationPassed: false
904
+ };
905
+ }
906
+ }
907
+
908
+ private async generateRecoveryStrategies(patterns: ErrorPattern[]): Promise<RecoveryStrategy[]> {
909
+ const strategies: RecoveryStrategy[] = Array.from(this.recoveryStrategies.values());
910
+
911
+ // Generate pattern-specific strategies
912
+ for (const pattern of patterns) {
913
+ if (pattern.autoHealable) {
914
+ const customStrategy: RecoveryStrategy = {
915
+ id: `strat_${pattern.id}`,
916
+ name: `Auto-heal ${pattern.name}`,
917
+ description: `Automated recovery for ${pattern.description}`,
918
+ applicableTo: pattern.signature.errorTypes,
919
+ steps: this.generateCustomSteps(pattern),
920
+ estimatedTime: pattern.avgResolutionTime,
921
+ successRate: pattern.successRate,
922
+ requirements: [],
923
+ risks: []
924
+ };
925
+
926
+ strategies.push(customStrategy);
927
+ }
928
+ }
929
+
930
+ return strategies;
931
+ }
932
+
933
+ private async collectSystemMetrics(): Promise<SystemMetrics> {
934
+ // Collect real-time system metrics
935
+ return {
936
+ availability: {
937
+ current: 99.5,
938
+ target: 99.9,
939
+ trend: 'stable'
940
+ },
941
+ performance: {
942
+ responseTime: 250, // ms
943
+ throughput: 1000, // requests/sec
944
+ errorRate: 0.5, // percentage
945
+ trend: 'improving'
946
+ },
947
+ reliability: {
948
+ mtbf: 720, // hours
949
+ mttr: 15, // minutes
950
+ failureRate: 0.14 // failures per day
951
+ },
952
+ capacity: {
953
+ cpu: 45, // percentage
954
+ memory: 60,
955
+ storage: 35,
956
+ network: 20
957
+ }
958
+ };
959
+ }
960
+
961
+ private async generateHealingRecommendations(
962
+ incidents: HealthIncident[],
963
+ patterns: ErrorPattern[],
964
+ metrics: SystemMetrics
965
+ ): Promise<HealingRecommendation[]> {
966
+ const recommendations: HealingRecommendation[] = [];
967
+
968
+ // Redundancy recommendations
969
+ if (metrics.availability.current < metrics.availability.target) {
970
+ recommendations.push({
971
+ id: `rec_${Date.now()}_1`,
972
+ category: 'redundancy',
973
+ priority: 'high',
974
+ title: 'Implement Service Redundancy',
975
+ description: 'Add redundant instances to improve availability',
976
+ benefit: 'Increase availability to target 99.9%',
977
+ effort: 'moderate',
978
+ preventedIncidents: Math.round(incidents.filter(i => i.type === 'availability').length * 0.8),
979
+ roi: 250
980
+ });
981
+ }
982
+
983
+ // Monitoring recommendations
984
+ if (patterns.some(p => p.autoHealable && p.successRate < 80)) {
985
+ recommendations.push({
986
+ id: `rec_${Date.now()}_2`,
987
+ category: 'monitoring',
988
+ priority: 'medium',
989
+ title: 'Enhanced Monitoring Coverage',
990
+ description: 'Improve monitoring to detect issues earlier',
991
+ benefit: 'Reduce MTTR by 50%',
992
+ effort: 'minimal',
993
+ preventedIncidents: Math.round(incidents.length * 0.3),
994
+ roi: 400
995
+ });
996
+ }
997
+
998
+ // Automation recommendations
999
+ const manualActions = incidents.filter(i =>
1000
+ !patterns.find(p => p.signature.errorTypes.includes(i.type))?.autoHealable
1001
+ );
1002
+ if (manualActions.length > 0) {
1003
+ recommendations.push({
1004
+ id: `rec_${Date.now()}_3`,
1005
+ category: 'automation',
1006
+ priority: 'medium',
1007
+ title: 'Automate Manual Recovery Processes',
1008
+ description: `Automate recovery for ${manualActions.length} manual processes`,
1009
+ benefit: 'Reduce recovery time by 80%',
1010
+ effort: 'significant',
1011
+ preventedIncidents: manualActions.length,
1012
+ roi: 300
1013
+ });
1014
+ }
1015
+
1016
+ return recommendations;
1017
+ }
1018
+
1019
+ private calculateHealthScore(metrics: SystemMetrics, incidents: HealthIncident[]): number {
1020
+ let score = 100;
1021
+
1022
+ // Availability impact (40% weight)
1023
+ const availabilityScore = (metrics.availability.current / metrics.availability.target) * 40;
1024
+ score = Math.min(score, availabilityScore + 60);
1025
+
1026
+ // Performance impact (30% weight)
1027
+ const performanceScore = Math.max(0, 30 - (metrics.performance.errorRate * 6));
1028
+ score = Math.min(score, availabilityScore + performanceScore + 30);
1029
+
1030
+ // Active incidents impact (30% weight)
1031
+ const activeIncidents = incidents.filter(i => i.status === 'active');
1032
+ const incidentImpact = activeIncidents.reduce((sum, i) => {
1033
+ const severityWeight = { critical: 10, high: 5, medium: 2, low: 1 };
1034
+ return sum + severityWeight[i.severity];
1035
+ }, 0);
1036
+ const incidentScore = Math.max(0, 30 - incidentImpact);
1037
+
1038
+ return Math.round(availabilityScore + performanceScore + incidentScore);
1039
+ }
1040
+
1041
+ private async handleCriticalIncidents(incidents: HealthIncident[]): Promise<void> {
1042
+ this.logger.error(`🚨 Handling ${incidents.length} critical incidents`);
1043
+
1044
+ for (const incident of incidents) {
1045
+ // Create emergency healing action
1046
+ const emergencyAction: HealingAction = {
1047
+ id: `emergency_${Date.now()}`,
1048
+ incidentId: incident.id,
1049
+ type: 'restart',
1050
+ title: `Emergency: ${incident.title}`,
1051
+ description: 'Emergency healing for critical incident',
1052
+ status: 'executing',
1053
+ automated: true,
1054
+ executionSteps: [
1055
+ {
1056
+ order: 1,
1057
+ action: 'Isolate affected component',
1058
+ target: incident.impact.services[0] || 'System',
1059
+ parameters: {},
1060
+ status: 'pending'
1061
+ },
1062
+ {
1063
+ order: 2,
1064
+ action: 'Apply emergency fix',
1065
+ target: incident.impact.services[0] || 'System',
1066
+ parameters: {},
1067
+ status: 'pending'
1068
+ }
1069
+ ]
1070
+ };
1071
+
1072
+ await this.executeHealingSteps(emergencyAction);
1073
+ }
1074
+ }
1075
+
1076
+ private async executePreventiveActions(predictions: HealthPrediction[]): Promise<void> {
1077
+ for (const prediction of predictions) {
1078
+ if (prediction.probability > 0.8 && prediction.impact === 'critical') {
1079
+ for (const action of prediction.preventiveActions) {
1080
+ if (action.priority === 'immediate' && action.automatable) {
1081
+ this.logger.info(`Executing preventive action: ${action.action}`);
1082
+ // Execute preventive action
1083
+ await this.executePreventiveAction(action);
1084
+ }
1085
+ }
1086
+ }
1087
+ }
1088
+ }
1089
+
1090
+ private async healSelf(error: any): Promise<void> {
1091
+ this.logger.warn('🏥 Self-healing the healing system', error);
1092
+
1093
+ // Restart monitoring
1094
+ this.monitoringActive = false;
1095
+ await new Promise(resolve => setTimeout(resolve, 5000));
1096
+ this.monitoringActive = true;
1097
+
1098
+ // Clear error state
1099
+ this.activeIncidents.clear();
1100
+
1101
+ // Reinitialize
1102
+ this.startHealthMonitoring();
1103
+ }
1104
+
1105
+ private startHealthMonitoring(): void {
1106
+ if (!this.monitoringActive) return;
1107
+
1108
+ // Monitor system health continuously
1109
+ setInterval(async () => {
1110
+ try {
1111
+ await this.checkSystemHealth();
1112
+ } catch (error) {
1113
+ this.logger.error('Error in health monitoring', error);
1114
+ }
1115
+ }, 60000); // Every minute
1116
+ }
1117
+
1118
+ private async checkSystemHealth(): Promise<void> {
1119
+ // Quick health check
1120
+ const metrics = await this.collectSystemMetrics();
1121
+
1122
+ if (metrics.availability.current < 95) {
1123
+ // Create availability incident
1124
+ const incident: HealthIncident = {
1125
+ id: `inc_auto_${Date.now()}`,
1126
+ type: 'availability',
1127
+ severity: 'high',
1128
+ title: 'Low system availability detected',
1129
+ description: `Availability dropped to ${metrics.availability.current}%`,
1130
+ detectedAt: new Date().toISOString(),
1131
+ status: 'active',
1132
+ impact: {
1133
+ users: 1000,
1134
+ services: ['All'],
1135
+ availability: metrics.availability.current,
1136
+ performance: 0,
1137
+ dataLoss: false,
1138
+ duration: 0
1139
+ },
1140
+ healingAttempts: 0
1141
+ };
1142
+
1143
+ this.activeIncidents.set(incident.id, incident);
1144
+ }
1145
+ }
1146
+
1147
+ // Utility methods
1148
+ private getLatestHealingProfile(): HealingProfile | null {
1149
+ const profiles = Array.from(this.healingProfiles.values());
1150
+ if (profiles.length === 0) return null;
1151
+
1152
+ return profiles.sort((a, b) =>
1153
+ new Date(b.assessmentDate).getTime() -
1154
+ new Date(a.assessmentDate).getTime()
1155
+ )[0];
1156
+ }
1157
+
1158
+ private async generateDashboard(profile: HealingProfile): Promise<any> {
1159
+ return {
1160
+ systemHealth: profile.healthScore >= 90 ? 'Healthy' :
1161
+ profile.healthScore >= 70 ? 'Degraded' : 'Critical',
1162
+ healthScore: profile.healthScore,
1163
+ activeIncidents: profile.incidents.filter(i => i.status === 'active'),
1164
+ recentHealing: profile.healingActions.slice(0, 5),
1165
+ systemMetrics: profile.systemMetrics,
1166
+ predictions: profile.predictions.filter(p => p.probability > 0.6),
1167
+ recommendations: profile.recommendations.slice(0, 3)
1168
+ };
1169
+ }
1170
+
1171
+ private generateWarnings(profile: HealingProfile): string[] {
1172
+ const warnings: string[] = [];
1173
+
1174
+ const criticalIncidents = profile.incidents.filter(i => i.severity === 'critical' && i.status === 'active');
1175
+ if (criticalIncidents.length > 0) {
1176
+ warnings.push(`${criticalIncidents.length} critical incidents require immediate attention`);
1177
+ }
1178
+
1179
+ if (profile.systemMetrics.availability.current < 99) {
1180
+ warnings.push('System availability below target threshold');
1181
+ }
1182
+
1183
+ return warnings;
1184
+ }
1185
+
1186
+ private async checkErrorLogs(): Promise<any[]> {
1187
+ // Simulate error log checking
1188
+ return [];
1189
+ }
1190
+
1191
+ private async checkPerformanceMetrics(): Promise<any[]> {
1192
+ // Simulate performance checking
1193
+ return [];
1194
+ }
1195
+
1196
+ private async checkAvailability(): Promise<any[]> {
1197
+ // Simulate availability checking
1198
+ return [];
1199
+ }
1200
+
1201
+ private determineSeverity(error: any): 'critical' | 'high' | 'medium' | 'low' {
1202
+ if (error.message.includes('CRITICAL') || error.message.includes('FATAL')) return 'critical';
1203
+ if (error.message.includes('ERROR')) return 'high';
1204
+ if (error.message.includes('WARNING')) return 'medium';
1205
+ return 'low';
1206
+ }
1207
+
1208
+ private async getRelatedLogs(incident: HealthIncident): Promise<any[]> {
1209
+ return [];
1210
+ }
1211
+
1212
+ private async getSystemStateAt(timestamp: string): Promise<any> {
1213
+ return {};
1214
+ }
1215
+
1216
+ private categorizeRootCause(incident: HealthIncident, logs: any[]): 'code' | 'configuration' | 'resource' | 'external' | 'data' | 'network' {
1217
+ // Simple categorization logic
1218
+ if (incident.type === 'performance') return 'resource';
1219
+ if (incident.type === 'availability') return 'network';
1220
+ return 'code';
1221
+ }
1222
+
1223
+ private calculateConfidence(logs: any[], state: any): number {
1224
+ // Simple confidence calculation
1225
+ return 0.75 + (logs.length * 0.05);
1226
+ }
1227
+
1228
+ private generateRootCauseDescription(incident: HealthIncident, category: string, logs: any[]): string {
1229
+ return `${category} issue detected: ${incident.description}`;
1230
+ }
1231
+
1232
+ private async findRelatedIncidents(incident: HealthIncident): Promise<string[]> {
1233
+ return [];
1234
+ }
1235
+
1236
+ private groupIncidentsBySimilarity(incidents: HealthIncident[]): HealthIncident[][] {
1237
+ // Simple grouping by type
1238
+ const groups: Record<string, HealthIncident[]> = {};
1239
+
1240
+ for (const incident of incidents) {
1241
+ const key = `${incident.type}_${incident.severity}`;
1242
+ if (!groups[key]) groups[key] = [];
1243
+ groups[key].push(incident);
1244
+ }
1245
+
1246
+ return Object.values(groups);
1247
+ }
1248
+
1249
+ private generatePatternName(group: HealthIncident[]): string {
1250
+ return `${group[0].type} pattern #${Date.now()}`;
1251
+ }
1252
+
1253
+ private generatePatternDescription(group: HealthIncident[]): string {
1254
+ return `Recurring ${group[0].type} issue affecting ${group[0].impact.services.join(', ')}`;
1255
+ }
1256
+
1257
+ private extractKeywords(group: HealthIncident[]): string[] {
1258
+ const keywords = new Set<string>();
1259
+ for (const incident of group) {
1260
+ incident.title.split(' ').forEach(word => keywords.add(word.toLowerCase()));
1261
+ }
1262
+ return Array.from(keywords);
1263
+ }
1264
+
1265
+ private determineFrequency(group: HealthIncident[]): 'sporadic' | 'recurring' | 'persistent' {
1266
+ if (group.length > 10) return 'persistent';
1267
+ if (group.length > 3) return 'recurring';
1268
+ return 'sporadic';
1269
+ }
1270
+
1271
+ private findCorrelations(group: HealthIncident[]): string[] {
1272
+ return [];
1273
+ }
1274
+
1275
+ private calculateAvgResolutionTime(group: HealthIncident[]): number {
1276
+ const resolved = group.filter(i => i.resolvedAt);
1277
+ if (resolved.length === 0) return 300000; // 5 minutes default
1278
+
1279
+ const times = resolved.map(i =>
1280
+ new Date(i.resolvedAt!).getTime() - new Date(i.detectedAt).getTime()
1281
+ );
1282
+
1283
+ return times.reduce((a, b) => a + b, 0) / times.length;
1284
+ }
1285
+
1286
+ private calculateSuccessRate(group: HealthIncident[]): number {
1287
+ const resolved = group.filter(i => i.status === 'resolved').length;
1288
+ return group.length > 0 ? (resolved / group.length) * 100 : 0;
1289
+ }
1290
+
1291
+ private getRecommendedActions(group: HealthIncident[]): string[] {
1292
+ const actions: string[] = [];
1293
+
1294
+ if (group[0].type === 'error') actions.push('Apply error handling patch');
1295
+ if (group[0].type === 'performance') actions.push('Optimize resource allocation');
1296
+ if (group[0].type === 'availability') actions.push('Implement redundancy');
1297
+
1298
+ return actions;
1299
+ }
1300
+
1301
+ private isAutoHealable(group: HealthIncident[]): boolean {
1302
+ // Check if pattern can be auto-healed
1303
+ return group[0].type !== 'security' && this.calculateSuccessRate(group) > 70;
1304
+ }
1305
+
1306
+ private async analyzeTrends(incidents: HealthIncident[], patterns: ErrorPattern[]): Promise<any> {
1307
+ return {};
1308
+ }
1309
+
1310
+ private async predictCapacityIssues(): Promise<any[]> {
1311
+ return [
1312
+ {
1313
+ component: 'Memory',
1314
+ probability: 0.75,
1315
+ timeframe: '7 days',
1316
+ impact: 'high',
1317
+ confidence: 0.85
1318
+ }
1319
+ ];
1320
+ }
1321
+
1322
+ private predictNextOccurrence(pattern: ErrorPattern): { probability: number; timeframe: string } {
1323
+ // Simple prediction based on frequency
1324
+ if ((pattern as any).frequency === 'persistent') {
1325
+ return { probability: 0.9, timeframe: '1 hour' };
1326
+ }
1327
+ if ((pattern as any).frequency === 'recurring') {
1328
+ return { probability: 0.7, timeframe: '24 hours' };
1329
+ }
1330
+ return { probability: 0.3, timeframe: '7 days' };
1331
+ }
1332
+
1333
+ private findBestStrategy(incident: HealthIncident): RecoveryStrategy | null {
1334
+ for (const strategy of this.recoveryStrategies.values()) {
1335
+ if (strategy.applicableTo.includes(incident.type)) {
1336
+ return strategy;
1337
+ }
1338
+ }
1339
+ return null;
1340
+ }
1341
+
1342
+ private determineActionType(incident: HealthIncident, strategy: RecoveryStrategy): HealingAction['type'] {
1343
+ if (strategy.id === 'restart_service') return 'restart';
1344
+ if (strategy.id === 'rollback_deployment') return 'rollback';
1345
+ if (strategy.id === 'scale_resources') return 'scale';
1346
+ return 'patch';
1347
+ }
1348
+
1349
+ private async captureMetrics(): Promise<any> {
1350
+ const metrics = await this.collectSystemMetrics();
1351
+ return {
1352
+ availability: metrics.availability.current,
1353
+ performance: metrics.performance.responseTime,
1354
+ errorRate: metrics.performance.errorRate
1355
+ };
1356
+ }
1357
+
1358
+ private async stopService(target: string): Promise<void> {
1359
+ this.logger.info(`Stopping service: ${target}`);
1360
+ await new Promise(resolve => setTimeout(resolve, 2000));
1361
+ }
1362
+
1363
+ private async clearTempData(target: string): Promise<void> {
1364
+ this.logger.info(`Clearing temp data for: ${target}`);
1365
+ await new Promise(resolve => setTimeout(resolve, 1000));
1366
+ }
1367
+
1368
+ private async startService(target: string): Promise<void> {
1369
+ this.logger.info(`Starting service: ${target}`);
1370
+ await new Promise(resolve => setTimeout(resolve, 3000));
1371
+ }
1372
+
1373
+ private generateCustomSteps(pattern: ErrorPattern): RecoveryStep[] {
1374
+ return pattern.recommendedActions.map((action, index) => ({
1375
+ order: index + 1,
1376
+ action,
1377
+ automated: pattern.autoHealable,
1378
+ timeout: 60000,
1379
+ verification: 'Action completed successfully'
1380
+ }));
1381
+ }
1382
+
1383
+ private async getHealingAction(actionId: string): Promise<HealingAction | null> {
1384
+ for (const profile of this.healingProfiles.values()) {
1385
+ const action = profile.healingActions.find(a => a.id === actionId);
1386
+ if (action) return action;
1387
+ }
1388
+ return null;
1389
+ }
1390
+
1391
+ private async verifyHealingSafety(action: HealingAction): Promise<{ safe: boolean; reason?: string }> {
1392
+ // Verify it's safe to execute healing
1393
+ if (action.type === 'rollback' && !action.rollbackPlan) {
1394
+ return { safe: false, reason: 'No rollback plan available' };
1395
+ }
1396
+ return { safe: true };
1397
+ }
1398
+
1399
+ private async monitorHealingProgress(action: HealingAction, result: HealingResult): Promise<void> {
1400
+ this.logger.info(`Monitoring healing progress for action ${action.id}`);
1401
+ // Monitor the healing impact
1402
+ }
1403
+
1404
+ private async rollbackHealing(action: HealingAction): Promise<void> {
1405
+ this.logger.warn(`Rolling back healing action ${action.id}`);
1406
+ // Implement rollback logic
1407
+ }
1408
+
1409
+ private async executePreventiveAction(action: PreventiveAction): Promise<void> {
1410
+ this.logger.info(`Executing preventive action: ${action.action}`);
1411
+ // Execute the preventive action
1412
+ }
1413
+ }
1414
+
1415
+ // Learning engine for pattern recognition
1416
+ class LearningEngine {
1417
+ private memory: MemorySystem;
1418
+
1419
+ constructor(memory: MemorySystem) {
1420
+ this.memory = memory;
1421
+ }
1422
+
1423
+ async learn(incidents: HealthIncident[], actions: HealingAction[]): Promise<void> {
1424
+ // Store patterns for future recognition
1425
+ const learningData = {
1426
+ incidents,
1427
+ actions,
1428
+ timestamp: new Date().toISOString()
1429
+ };
1430
+
1431
+ await this.memory.store('healing_patterns', learningData, 2592000000); // 30 days
1432
+ }
1433
+ }
1434
+
1435
+ export default SelfHealingSystem;