moai-adk 0.8.0__py3-none-any.whl → 1.1.0__py3-none-any.whl

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 (881) hide show
  1. moai_adk/__init__.py +2 -6
  2. moai_adk/__main__.py +267 -21
  3. moai_adk/astgrep/__init__.py +37 -0
  4. moai_adk/astgrep/analyzer.py +522 -0
  5. moai_adk/astgrep/models.py +124 -0
  6. moai_adk/astgrep/rules.py +179 -0
  7. moai_adk/cli/__init__.py +6 -2
  8. moai_adk/cli/commands/__init__.py +1 -4
  9. moai_adk/cli/commands/analyze.py +125 -0
  10. moai_adk/cli/commands/doctor.py +24 -6
  11. moai_adk/cli/commands/init.py +437 -57
  12. moai_adk/cli/commands/language.py +254 -0
  13. moai_adk/cli/commands/rank.py +449 -0
  14. moai_adk/cli/commands/status.py +15 -14
  15. moai_adk/cli/commands/switch.py +325 -0
  16. moai_adk/cli/commands/update.py +2195 -93
  17. moai_adk/cli/main.py +3 -2
  18. moai_adk/cli/prompts/init_prompts.py +457 -108
  19. moai_adk/cli/prompts/translations/__init__.py +573 -0
  20. moai_adk/cli/spec_status.py +263 -0
  21. moai_adk/cli/ui/__init__.py +44 -0
  22. moai_adk/cli/ui/progress.py +422 -0
  23. moai_adk/cli/ui/prompts.py +448 -0
  24. moai_adk/cli/ui/theme.py +129 -0
  25. moai_adk/cli/worktree/__init__.py +27 -0
  26. moai_adk/cli/worktree/__main__.py +31 -0
  27. moai_adk/cli/worktree/cli.py +788 -0
  28. moai_adk/cli/worktree/exceptions.py +89 -0
  29. moai_adk/cli/worktree/manager.py +648 -0
  30. moai_adk/cli/worktree/models.py +65 -0
  31. moai_adk/cli/worktree/registry.py +422 -0
  32. moai_adk/core/PHASE2_OPTIMIZATIONS.md +467 -0
  33. moai_adk/core/__init__.py +0 -1
  34. moai_adk/core/analysis/__init__.py +9 -0
  35. moai_adk/core/analysis/session_analyzer.py +400 -0
  36. moai_adk/core/claude_integration.py +393 -0
  37. moai_adk/core/command_helpers.py +270 -0
  38. moai_adk/core/comprehensive_monitoring_system.py +1183 -0
  39. moai_adk/core/config/__init__.py +6 -0
  40. moai_adk/core/config/migration.py +148 -17
  41. moai_adk/core/config/unified.py +617 -0
  42. moai_adk/core/context_manager.py +273 -0
  43. moai_adk/core/credentials.py +264 -0
  44. moai_adk/core/diagnostics/slash_commands.py +0 -1
  45. moai_adk/core/enterprise_features.py +1404 -0
  46. moai_adk/core/error_recovery_system.py +1920 -0
  47. moai_adk/core/event_driven_hook_system.py +1371 -0
  48. moai_adk/core/git/__init__.py +8 -1
  49. moai_adk/core/git/branch.py +0 -1
  50. moai_adk/core/git/branch_manager.py +2 -10
  51. moai_adk/core/git/checkpoint.py +1 -7
  52. moai_adk/core/git/commit.py +0 -1
  53. moai_adk/core/git/conflict_detector.py +422 -0
  54. moai_adk/core/git/event_detector.py +16 -7
  55. moai_adk/core/git/manager.py +91 -2
  56. moai_adk/core/input_validation_middleware.py +1006 -0
  57. moai_adk/core/integration/__init__.py +22 -0
  58. moai_adk/core/integration/engine.py +157 -0
  59. moai_adk/core/integration/integration_tester.py +226 -0
  60. moai_adk/core/integration/models.py +88 -0
  61. moai_adk/core/integration/utils.py +211 -0
  62. moai_adk/core/issue_creator.py +305 -0
  63. moai_adk/core/jit_context_loader.py +956 -0
  64. moai_adk/core/jit_enhanced_hook_manager.py +1987 -0
  65. moai_adk/core/language_config.py +202 -0
  66. moai_adk/core/language_config_resolver.py +578 -0
  67. moai_adk/core/language_validator.py +543 -0
  68. moai_adk/core/mcp/setup.py +116 -0
  69. moai_adk/core/merge/__init__.py +9 -0
  70. moai_adk/core/merge/analyzer.py +666 -0
  71. moai_adk/core/migration/__init__.py +18 -0
  72. moai_adk/core/migration/alfred_to_moai_migrator.py +389 -0
  73. moai_adk/core/migration/backup_manager.py +327 -0
  74. moai_adk/core/migration/custom_element_scanner.py +358 -0
  75. moai_adk/core/migration/file_migrator.py +381 -0
  76. moai_adk/core/migration/interactive_checkbox_ui.py +499 -0
  77. moai_adk/core/migration/selective_restorer.py +470 -0
  78. moai_adk/core/migration/template_utils.py +74 -0
  79. moai_adk/core/migration/user_selection_ui.py +338 -0
  80. moai_adk/core/migration/version_detector.py +243 -0
  81. moai_adk/core/migration/version_migrator.py +263 -0
  82. moai_adk/core/model_allocator.py +241 -0
  83. moai_adk/core/performance/__init__.py +6 -0
  84. moai_adk/core/performance/cache_system.py +316 -0
  85. moai_adk/core/performance/parallel_processor.py +116 -0
  86. moai_adk/core/phase_optimized_hook_scheduler.py +879 -0
  87. moai_adk/core/project/__init__.py +0 -1
  88. moai_adk/core/project/backup_utils.py +13 -8
  89. moai_adk/core/project/checker.py +2 -4
  90. moai_adk/core/project/detector.py +189 -22
  91. moai_adk/core/project/initializer.py +177 -29
  92. moai_adk/core/project/phase_executor.py +482 -48
  93. moai_adk/core/project/validator.py +22 -32
  94. moai_adk/core/quality/__init__.py +1 -1
  95. moai_adk/core/quality/trust_checker.py +66 -110
  96. moai_adk/core/quality/validators/__init__.py +1 -1
  97. moai_adk/core/quality/validators/base_validator.py +1 -1
  98. moai_adk/core/realtime_monitoring_dashboard.py +1724 -0
  99. moai_adk/core/robust_json_parser.py +611 -0
  100. moai_adk/core/rollback_manager.py +953 -0
  101. moai_adk/core/session_manager.py +651 -0
  102. moai_adk/core/skill_loading_system.py +579 -0
  103. moai_adk/core/spec_status_manager.py +478 -0
  104. moai_adk/core/template/__init__.py +0 -1
  105. moai_adk/core/template/backup.py +168 -21
  106. moai_adk/core/template/config.py +141 -45
  107. moai_adk/core/template/languages.py +0 -1
  108. moai_adk/core/template/merger.py +107 -32
  109. moai_adk/core/template/processor.py +1075 -74
  110. moai_adk/core/template_engine.py +319 -0
  111. moai_adk/core/template_variable_synchronizer.py +431 -0
  112. moai_adk/core/unified_permission_manager.py +745 -0
  113. moai_adk/core/user_behavior_analytics.py +851 -0
  114. moai_adk/core/version_sync.py +477 -0
  115. moai_adk/foundation/__init__.py +37 -0
  116. moai_adk/foundation/backend.py +1027 -0
  117. moai_adk/foundation/database.py +1115 -0
  118. moai_adk/foundation/devops.py +1585 -0
  119. moai_adk/foundation/ears.py +431 -0
  120. moai_adk/foundation/frontend.py +870 -0
  121. moai_adk/foundation/git/__init__.py +376 -0
  122. moai_adk/foundation/git/commit_templates.py +557 -0
  123. moai_adk/foundation/langs.py +484 -0
  124. moai_adk/foundation/ml_ops.py +1162 -0
  125. moai_adk/foundation/testing.py +1524 -0
  126. moai_adk/foundation/trust/trust_principles.py +676 -0
  127. moai_adk/foundation/trust/validation_checklist.py +1573 -0
  128. moai_adk/loop/__init__.py +54 -0
  129. moai_adk/loop/controller.py +305 -0
  130. moai_adk/loop/feedback.py +230 -0
  131. moai_adk/loop/state.py +209 -0
  132. moai_adk/loop/storage.py +220 -0
  133. moai_adk/lsp/__init__.py +70 -0
  134. moai_adk/lsp/client.py +320 -0
  135. moai_adk/lsp/models.py +261 -0
  136. moai_adk/lsp/protocol.py +404 -0
  137. moai_adk/lsp/server_manager.py +248 -0
  138. moai_adk/project/__init__.py +0 -0
  139. moai_adk/project/configuration.py +1091 -0
  140. moai_adk/project/documentation.py +566 -0
  141. moai_adk/project/schema.py +447 -0
  142. moai_adk/py.typed +0 -0
  143. moai_adk/ralph/__init__.py +37 -0
  144. moai_adk/ralph/engine.py +307 -0
  145. moai_adk/rank/__init__.py +21 -0
  146. moai_adk/rank/auth.py +425 -0
  147. moai_adk/rank/client.py +557 -0
  148. moai_adk/rank/config.py +147 -0
  149. moai_adk/rank/hook.py +1503 -0
  150. moai_adk/rank/py.typed +0 -0
  151. moai_adk/statusline/__init__.py +41 -0
  152. moai_adk/statusline/alfred_detector.py +105 -0
  153. moai_adk/statusline/config.py +376 -0
  154. moai_adk/statusline/enhanced_output_style_detector.py +372 -0
  155. moai_adk/statusline/git_collector.py +190 -0
  156. moai_adk/statusline/main.py +341 -0
  157. moai_adk/statusline/memory_collector.py +268 -0
  158. moai_adk/statusline/metrics_tracker.py +78 -0
  159. moai_adk/statusline/renderer.py +359 -0
  160. moai_adk/statusline/update_checker.py +129 -0
  161. moai_adk/statusline/version_reader.py +741 -0
  162. moai_adk/tag_system/__init__.py +48 -0
  163. moai_adk/tag_system/atomic_ops.py +117 -0
  164. moai_adk/tag_system/linkage.py +335 -0
  165. moai_adk/tag_system/parser.py +176 -0
  166. moai_adk/tag_system/validator.py +200 -0
  167. moai_adk/templates/.claude/agents/moai/builder-agent.md +490 -0
  168. moai_adk/templates/.claude/agents/moai/builder-command.md +1218 -0
  169. moai_adk/templates/.claude/agents/moai/builder-plugin.md +763 -0
  170. moai_adk/templates/.claude/agents/moai/builder-skill.md +682 -0
  171. moai_adk/templates/.claude/agents/moai/expert-backend.md +963 -0
  172. moai_adk/templates/.claude/agents/moai/expert-debug.md +407 -0
  173. moai_adk/templates/.claude/agents/moai/expert-devops.md +722 -0
  174. moai_adk/templates/.claude/agents/moai/expert-frontend.md +748 -0
  175. moai_adk/templates/.claude/agents/moai/expert-performance.md +661 -0
  176. moai_adk/templates/.claude/agents/moai/expert-refactoring.md +228 -0
  177. moai_adk/templates/.claude/agents/moai/expert-security.md +525 -0
  178. moai_adk/templates/.claude/agents/moai/expert-testing.md +737 -0
  179. moai_adk/templates/.claude/agents/moai/manager-claude-code.md +438 -0
  180. moai_adk/templates/.claude/agents/moai/manager-docs.md +578 -0
  181. moai_adk/templates/.claude/agents/moai/manager-git.md +1092 -0
  182. moai_adk/templates/.claude/agents/moai/manager-project.md +971 -0
  183. moai_adk/templates/.claude/agents/moai/manager-quality.md +641 -0
  184. moai_adk/templates/.claude/agents/moai/manager-spec.md +815 -0
  185. moai_adk/templates/.claude/agents/moai/manager-strategy.md +811 -0
  186. moai_adk/templates/.claude/agents/moai/manager-tdd.md +797 -0
  187. moai_adk/templates/.claude/commands/moai/0-project.md +438 -0
  188. moai_adk/templates/.claude/commands/moai/1-plan.md +1447 -0
  189. moai_adk/templates/.claude/commands/moai/2-run.md +850 -0
  190. moai_adk/templates/.claude/commands/moai/3-sync.md +1398 -0
  191. moai_adk/templates/.claude/commands/moai/9-feedback.md +330 -0
  192. moai_adk/templates/.claude/commands/moai/alfred.md +339 -0
  193. moai_adk/templates/.claude/commands/moai/cancel-loop.md +163 -0
  194. moai_adk/templates/.claude/commands/moai/fix.md +264 -0
  195. moai_adk/templates/.claude/commands/moai/loop.md +363 -0
  196. moai_adk/templates/.claude/hooks/__init__.py +8 -0
  197. moai_adk/templates/.claude/hooks/moai/__init__.py +8 -0
  198. moai_adk/templates/.claude/hooks/moai/lib/README.md +143 -0
  199. moai_adk/templates/.claude/hooks/moai/lib/__init__.py +41 -0
  200. moai_adk/templates/.claude/hooks/moai/lib/alfred_detector.py +105 -0
  201. moai_adk/templates/.claude/hooks/moai/lib/atomic_write.py +122 -0
  202. moai_adk/templates/.claude/hooks/{alfred/core → moai/lib}/checkpoint.py +13 -37
  203. moai_adk/templates/.claude/hooks/moai/lib/common.py +161 -0
  204. moai_adk/templates/.claude/hooks/moai/lib/config.py +376 -0
  205. moai_adk/templates/.claude/hooks/moai/lib/config_manager.py +442 -0
  206. moai_adk/templates/.claude/hooks/moai/lib/config_validator.py +639 -0
  207. moai_adk/templates/.claude/hooks/moai/lib/enhanced_output_style_detector.py +372 -0
  208. moai_adk/templates/.claude/hooks/moai/lib/example_config.json +104 -0
  209. moai_adk/templates/.claude/hooks/moai/lib/exceptions.py +171 -0
  210. moai_adk/templates/.claude/hooks/moai/lib/file_utils.py +95 -0
  211. moai_adk/templates/.claude/hooks/moai/lib/git_collector.py +190 -0
  212. moai_adk/templates/.claude/hooks/moai/lib/git_operations_manager.py +592 -0
  213. moai_adk/templates/.claude/hooks/moai/lib/language_detector.py +298 -0
  214. moai_adk/templates/.claude/hooks/moai/lib/language_validator.py +417 -0
  215. moai_adk/templates/.claude/hooks/moai/lib/main.py +341 -0
  216. moai_adk/templates/.claude/hooks/moai/lib/memory_collector.py +268 -0
  217. moai_adk/templates/.claude/hooks/moai/lib/metrics_tracker.py +78 -0
  218. moai_adk/templates/.claude/hooks/moai/lib/models.py +104 -0
  219. moai_adk/templates/.claude/hooks/moai/lib/path_utils.py +219 -0
  220. moai_adk/templates/.claude/hooks/moai/lib/project.py +777 -0
  221. moai_adk/templates/.claude/hooks/moai/lib/renderer.py +359 -0
  222. moai_adk/templates/.claude/hooks/moai/lib/tag_linkage.py +333 -0
  223. moai_adk/templates/.claude/hooks/moai/lib/tag_parser.py +176 -0
  224. moai_adk/templates/.claude/hooks/moai/lib/tag_validator.py +200 -0
  225. moai_adk/templates/.claude/hooks/moai/lib/test_hooks_improvements.py +443 -0
  226. moai_adk/templates/.claude/hooks/moai/lib/timeout.py +160 -0
  227. moai_adk/templates/.claude/hooks/moai/lib/tool_registry.py +896 -0
  228. moai_adk/templates/.claude/hooks/moai/lib/unified_timeout_manager.py +542 -0
  229. moai_adk/templates/.claude/hooks/moai/lib/update_checker.py +129 -0
  230. moai_adk/templates/.claude/hooks/moai/lib/version_reader.py +741 -0
  231. moai_adk/templates/.claude/hooks/moai/post_tool__ast_grep_scan.py +276 -0
  232. moai_adk/templates/.claude/hooks/moai/post_tool__code_formatter.py +255 -0
  233. moai_adk/templates/.claude/hooks/moai/post_tool__coverage_guard.py +325 -0
  234. moai_adk/templates/.claude/hooks/moai/post_tool__linter.py +315 -0
  235. moai_adk/templates/.claude/hooks/moai/post_tool__lsp_diagnostic.py +508 -0
  236. moai_adk/templates/.claude/hooks/moai/pre_commit__tag_validator.py +287 -0
  237. moai_adk/templates/.claude/hooks/moai/pre_tool__security_guard.py +268 -0
  238. moai_adk/templates/.claude/hooks/moai/pre_tool__tdd_enforcer.py +208 -0
  239. moai_adk/templates/.claude/hooks/moai/session_end__auto_cleanup.py +894 -0
  240. moai_adk/templates/.claude/hooks/moai/session_end__rank_submit.py +69 -0
  241. moai_adk/templates/.claude/hooks/moai/session_start__show_project_info.py +1170 -0
  242. moai_adk/templates/.claude/hooks/moai/shared/utils/announcement_translator.py +206 -0
  243. moai_adk/templates/.claude/hooks/moai/stop__loop_controller.py +621 -0
  244. moai_adk/templates/.claude/output-styles/moai/alfred.md +758 -0
  245. moai_adk/templates/.claude/output-styles/moai/r2d2.md +643 -0
  246. moai_adk/templates/.claude/output-styles/moai/yoda.md +359 -0
  247. moai_adk/templates/.claude/settings.json +177 -72
  248. moai_adk/templates/.claude/skills/moai-docs-generation/SKILL.md +303 -0
  249. moai_adk/templates/.claude/skills/moai-docs-generation/examples.md +252 -0
  250. moai_adk/templates/.claude/skills/moai-docs-generation/modules/README.md +56 -0
  251. moai_adk/templates/.claude/skills/moai-docs-generation/modules/api-documentation.md +120 -0
  252. moai_adk/templates/.claude/skills/moai-docs-generation/modules/code-documentation.md +152 -0
  253. moai_adk/templates/.claude/skills/moai-docs-generation/modules/multi-format-output.md +185 -0
  254. moai_adk/templates/.claude/skills/moai-docs-generation/modules/user-guides.md +207 -0
  255. moai_adk/templates/.claude/skills/moai-docs-generation/reference.md +234 -0
  256. moai_adk/templates/.claude/skills/moai-domain-backend/SKILL.md +132 -281
  257. moai_adk/templates/.claude/skills/moai-domain-backend/examples.md +610 -1525
  258. moai_adk/templates/.claude/skills/moai-domain-backend/reference.md +423 -619
  259. moai_adk/templates/.claude/skills/moai-domain-database/SKILL.md +133 -77
  260. moai_adk/templates/.claude/skills/moai-domain-database/examples.md +817 -16
  261. moai_adk/templates/.claude/skills/moai-domain-database/modules/README.md +53 -0
  262. moai_adk/templates/.claude/skills/moai-domain-database/modules/mongodb.md +231 -0
  263. moai_adk/templates/.claude/skills/moai-domain-database/modules/postgresql.md +169 -0
  264. moai_adk/templates/.claude/skills/moai-domain-database/modules/redis.md +262 -0
  265. moai_adk/templates/.claude/skills/moai-domain-database/reference.md +532 -17
  266. moai_adk/templates/.claude/skills/moai-domain-frontend/SKILL.md +91 -78
  267. moai_adk/templates/.claude/skills/moai-domain-frontend/examples.md +955 -16
  268. moai_adk/templates/.claude/skills/moai-domain-frontend/modules/component-architecture.md +723 -0
  269. moai_adk/templates/.claude/skills/moai-domain-frontend/modules/nextjs16-patterns.md +713 -0
  270. moai_adk/templates/.claude/skills/moai-domain-frontend/modules/performance-optimization.md +694 -0
  271. moai_adk/templates/.claude/skills/moai-domain-frontend/modules/react19-patterns.md +591 -0
  272. moai_adk/templates/.claude/skills/moai-domain-frontend/modules/state-management.md +680 -0
  273. moai_adk/templates/.claude/skills/moai-domain-frontend/modules/vue35-patterns.md +802 -0
  274. moai_adk/templates/.claude/skills/moai-domain-frontend/reference.md +651 -18
  275. moai_adk/templates/.claude/skills/moai-domain-uiux/SKILL.md +234 -0
  276. moai_adk/templates/.claude/skills/moai-domain-uiux/examples.md +560 -0
  277. moai_adk/templates/.claude/skills/moai-domain-uiux/modules/accessibility-wcag.md +260 -0
  278. moai_adk/templates/.claude/skills/moai-domain-uiux/modules/component-architecture.md +228 -0
  279. moai_adk/templates/.claude/skills/moai-domain-uiux/modules/icon-libraries.md +401 -0
  280. moai_adk/templates/.claude/skills/moai-domain-uiux/modules/theming-system.md +373 -0
  281. moai_adk/templates/.claude/skills/moai-domain-uiux/reference.md +243 -0
  282. moai_adk/templates/.claude/skills/moai-formats-data/SKILL.md +189 -0
  283. moai_adk/templates/.claude/skills/moai-formats-data/examples.md +804 -0
  284. moai_adk/templates/.claude/skills/moai-formats-data/modules/README.md +327 -0
  285. moai_adk/templates/.claude/skills/moai-formats-data/modules/SKILL-MODULARIZATION-TEMPLATE.md +278 -0
  286. moai_adk/templates/.claude/skills/moai-formats-data/modules/caching-performance.md +459 -0
  287. moai_adk/templates/.claude/skills/moai-formats-data/modules/data-validation.md +485 -0
  288. moai_adk/templates/.claude/skills/moai-formats-data/modules/json-optimization.md +374 -0
  289. moai_adk/templates/.claude/skills/moai-formats-data/modules/toon-encoding.md +308 -0
  290. moai_adk/templates/.claude/skills/moai-formats-data/reference.md +585 -0
  291. moai_adk/templates/.claude/skills/moai-foundation-claude/SKILL.md +225 -0
  292. moai_adk/templates/.claude/skills/moai-foundation-claude/examples.md +732 -0
  293. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/advanced-agent-patterns.md +370 -0
  294. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/best-practices-checklist.md +616 -0
  295. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-cli-reference-official.md +420 -0
  296. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-custom-slash-commands-official.md +739 -0
  297. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-devcontainers-official.md +381 -0
  298. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-discover-plugins-official.md +379 -0
  299. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-headless-official.md +378 -0
  300. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-hooks-official.md +670 -0
  301. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-iam-official.md +635 -0
  302. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-memory-official.md +543 -0
  303. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-plugin-marketplaces-official.md +308 -0
  304. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-plugins-official.md +640 -0
  305. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-sandboxing-official.md +282 -0
  306. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-settings-official.md +663 -0
  307. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-skills-official.md +467 -0
  308. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-statusline-official.md +293 -0
  309. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/claude-code-sub-agents-official.md +420 -0
  310. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/complete-configuration-guide.md +175 -0
  311. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/skill-examples.md +1674 -0
  312. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/skill-formatting-guide.md +729 -0
  313. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/sub-agents/sub-agent-examples.md +1513 -0
  314. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/sub-agents/sub-agent-formatting-guide.md +1086 -0
  315. moai_adk/templates/.claude/skills/moai-foundation-claude/reference/sub-agents/sub-agent-integration-patterns.md +1100 -0
  316. moai_adk/templates/.claude/skills/moai-foundation-claude/reference.md +209 -0
  317. moai_adk/templates/.claude/skills/moai-foundation-context/SKILL.md +221 -0
  318. moai_adk/templates/.claude/skills/moai-foundation-context/examples.md +1048 -0
  319. moai_adk/templates/.claude/skills/moai-foundation-context/reference.md +246 -0
  320. moai_adk/templates/.claude/skills/moai-foundation-core/SKILL.md +242 -0
  321. moai_adk/templates/.claude/skills/moai-foundation-core/examples.md +358 -0
  322. moai_adk/templates/.claude/skills/moai-foundation-core/modules/README.md +296 -0
  323. moai_adk/templates/.claude/skills/moai-foundation-core/modules/agents-reference.md +359 -0
  324. moai_adk/templates/.claude/skills/moai-foundation-core/modules/commands-reference.md +432 -0
  325. moai_adk/templates/.claude/skills/moai-foundation-core/modules/delegation-advanced.md +279 -0
  326. moai_adk/templates/.claude/skills/moai-foundation-core/modules/delegation-implementation.md +267 -0
  327. moai_adk/templates/.claude/skills/moai-foundation-core/modules/delegation-patterns.md +228 -0
  328. moai_adk/templates/.claude/skills/moai-foundation-core/modules/execution-rules.md +687 -0
  329. moai_adk/templates/.claude/skills/moai-foundation-core/modules/modular-system.md +665 -0
  330. moai_adk/templates/.claude/skills/moai-foundation-core/modules/patterns.md +22 -0
  331. moai_adk/templates/.claude/skills/moai-foundation-core/modules/progressive-disclosure.md +649 -0
  332. moai_adk/templates/.claude/skills/moai-foundation-core/modules/spec-ears-format.md +200 -0
  333. moai_adk/templates/.claude/skills/moai-foundation-core/modules/spec-first-tdd.md +171 -0
  334. moai_adk/templates/.claude/skills/moai-foundation-core/modules/spec-tdd-implementation.md +275 -0
  335. moai_adk/templates/.claude/skills/moai-foundation-core/modules/token-optimization.md +708 -0
  336. moai_adk/templates/.claude/skills/moai-foundation-core/modules/trust-5-framework.md +239 -0
  337. moai_adk/templates/.claude/skills/moai-foundation-core/modules/trust-5-implementation.md +244 -0
  338. moai_adk/templates/.claude/skills/moai-foundation-core/modules/trust-5-validation.md +219 -0
  339. moai_adk/templates/.claude/skills/moai-foundation-core/reference.md +478 -0
  340. moai_adk/templates/.claude/skills/moai-foundation-philosopher/SKILL.md +311 -0
  341. moai_adk/templates/.claude/skills/moai-foundation-philosopher/examples.md +228 -0
  342. moai_adk/templates/.claude/skills/moai-foundation-philosopher/modules/assumption-matrix.md +80 -0
  343. moai_adk/templates/.claude/skills/moai-foundation-philosopher/modules/cognitive-bias.md +199 -0
  344. moai_adk/templates/.claude/skills/moai-foundation-philosopher/modules/first-principles.md +140 -0
  345. moai_adk/templates/.claude/skills/moai-foundation-philosopher/modules/trade-off-analysis.md +154 -0
  346. moai_adk/templates/.claude/skills/moai-foundation-philosopher/reference.md +157 -0
  347. moai_adk/templates/.claude/skills/moai-foundation-quality/SKILL.md +180 -0
  348. moai_adk/templates/.claude/skills/moai-foundation-quality/examples.md +1232 -0
  349. moai_adk/templates/.claude/skills/moai-foundation-quality/modules/best-practices.md +261 -0
  350. moai_adk/templates/.claude/skills/moai-foundation-quality/modules/integration-patterns.md +194 -0
  351. moai_adk/templates/.claude/skills/moai-foundation-quality/modules/proactive-analysis.md +229 -0
  352. moai_adk/templates/.claude/skills/moai-foundation-quality/modules/trust5-validation.md +169 -0
  353. moai_adk/templates/.claude/skills/moai-foundation-quality/reference.md +1266 -0
  354. moai_adk/templates/.claude/skills/moai-foundation-quality/scripts/quality-gate.sh +668 -0
  355. moai_adk/templates/.claude/skills/moai-foundation-quality/templates/github-actions-quality.yml +481 -0
  356. moai_adk/templates/.claude/skills/moai-foundation-quality/templates/quality-config.yaml +519 -0
  357. moai_adk/templates/.claude/skills/moai-framework-electron/SKILL.md +288 -0
  358. moai_adk/templates/.claude/skills/moai-framework-electron/examples.md +2082 -0
  359. moai_adk/templates/.claude/skills/moai-framework-electron/reference.md +1649 -0
  360. moai_adk/templates/.claude/skills/moai-lang-cpp/SKILL.md +96 -77
  361. moai_adk/templates/.claude/skills/moai-lang-cpp/examples.md +1226 -16
  362. moai_adk/templates/.claude/skills/moai-lang-cpp/modules/advanced-patterns.md +401 -0
  363. moai_adk/templates/.claude/skills/moai-lang-cpp/reference.md +1119 -14
  364. moai_adk/templates/.claude/skills/moai-lang-csharp/SKILL.md +80 -79
  365. moai_adk/templates/.claude/skills/moai-lang-csharp/examples.md +572 -16
  366. moai_adk/templates/.claude/skills/moai-lang-csharp/modules/aspnet-core.md +627 -0
  367. moai_adk/templates/.claude/skills/moai-lang-csharp/modules/blazor-components.md +767 -0
  368. moai_adk/templates/.claude/skills/moai-lang-csharp/modules/cqrs-validation.md +626 -0
  369. moai_adk/templates/.claude/skills/moai-lang-csharp/modules/csharp12-features.md +580 -0
  370. moai_adk/templates/.claude/skills/moai-lang-csharp/modules/efcore-patterns.md +622 -0
  371. moai_adk/templates/.claude/skills/moai-lang-csharp/reference.md +388 -15
  372. moai_adk/templates/.claude/skills/moai-lang-elixir/SKILL.md +135 -0
  373. moai_adk/templates/.claude/skills/moai-lang-elixir/examples.md +1171 -0
  374. moai_adk/templates/.claude/skills/moai-lang-elixir/modules/advanced-patterns.md +531 -0
  375. moai_adk/templates/.claude/skills/moai-lang-elixir/reference.md +889 -0
  376. moai_adk/templates/.claude/skills/moai-lang-flutter/SKILL.md +104 -0
  377. moai_adk/templates/.claude/skills/moai-lang-flutter/examples.md +1090 -0
  378. moai_adk/templates/.claude/skills/moai-lang-flutter/reference.md +686 -0
  379. moai_adk/templates/.claude/skills/moai-lang-go/SKILL.md +153 -80
  380. moai_adk/templates/.claude/skills/moai-lang-go/examples.md +906 -16
  381. moai_adk/templates/.claude/skills/moai-lang-go/reference.md +721 -15
  382. moai_adk/templates/.claude/skills/moai-lang-java/SKILL.md +117 -80
  383. moai_adk/templates/.claude/skills/moai-lang-java/examples.md +851 -16
  384. moai_adk/templates/.claude/skills/moai-lang-java/reference.md +278 -18
  385. moai_adk/templates/.claude/skills/moai-lang-javascript/SKILL.md +133 -79
  386. moai_adk/templates/.claude/skills/moai-lang-javascript/examples.md +960 -16
  387. moai_adk/templates/.claude/skills/moai-lang-javascript/reference.md +1528 -17
  388. moai_adk/templates/.claude/skills/moai-lang-kotlin/SKILL.md +100 -79
  389. moai_adk/templates/.claude/skills/moai-lang-kotlin/examples.md +993 -16
  390. moai_adk/templates/.claude/skills/moai-lang-kotlin/reference.md +549 -18
  391. moai_adk/templates/.claude/skills/moai-lang-php/SKILL.md +135 -76
  392. moai_adk/templates/.claude/skills/moai-lang-php/examples.md +1595 -16
  393. moai_adk/templates/.claude/skills/moai-lang-php/modules/advanced-patterns.md +538 -0
  394. moai_adk/templates/.claude/skills/moai-lang-php/reference.md +1309 -16
  395. moai_adk/templates/.claude/skills/moai-lang-python/SKILL.md +141 -341
  396. moai_adk/templates/.claude/skills/moai-lang-python/examples.md +849 -496
  397. moai_adk/templates/.claude/skills/moai-lang-python/reference.md +731 -243
  398. moai_adk/templates/.claude/skills/moai-lang-r/SKILL.md +134 -76
  399. moai_adk/templates/.claude/skills/moai-lang-r/examples.md +1141 -16
  400. moai_adk/templates/.claude/skills/moai-lang-r/modules/advanced-patterns.md +489 -0
  401. moai_adk/templates/.claude/skills/moai-lang-r/reference.md +1074 -17
  402. moai_adk/templates/.claude/skills/moai-lang-ruby/SKILL.md +136 -77
  403. moai_adk/templates/.claude/skills/moai-lang-ruby/examples.md +1093 -16
  404. moai_adk/templates/.claude/skills/moai-lang-ruby/modules/advanced-patterns.md +309 -0
  405. moai_adk/templates/.claude/skills/moai-lang-ruby/modules/testing-patterns.md +306 -0
  406. moai_adk/templates/.claude/skills/moai-lang-ruby/reference.md +1010 -17
  407. moai_adk/templates/.claude/skills/moai-lang-rust/SKILL.md +112 -78
  408. moai_adk/templates/.claude/skills/moai-lang-rust/examples.md +646 -16
  409. moai_adk/templates/.claude/skills/moai-lang-rust/reference.md +491 -18
  410. moai_adk/templates/.claude/skills/moai-lang-scala/SKILL.md +113 -75
  411. moai_adk/templates/.claude/skills/moai-lang-scala/examples.md +620 -16
  412. moai_adk/templates/.claude/skills/moai-lang-scala/modules/akka-actors.md +479 -0
  413. moai_adk/templates/.claude/skills/moai-lang-scala/modules/cats-effect.md +489 -0
  414. moai_adk/templates/.claude/skills/moai-lang-scala/modules/functional-programming.md +460 -0
  415. moai_adk/templates/.claude/skills/moai-lang-scala/modules/spark-data.md +498 -0
  416. moai_adk/templates/.claude/skills/moai-lang-scala/modules/zio-patterns.md +541 -0
  417. moai_adk/templates/.claude/skills/moai-lang-scala/reference.md +410 -17
  418. moai_adk/templates/.claude/skills/moai-lang-swift/SKILL.md +88 -83
  419. moai_adk/templates/.claude/skills/moai-lang-swift/examples.md +905 -16
  420. moai_adk/templates/.claude/skills/moai-lang-swift/modules/combine-reactive.md +256 -0
  421. moai_adk/templates/.claude/skills/moai-lang-swift/modules/concurrency.md +270 -0
  422. moai_adk/templates/.claude/skills/moai-lang-swift/modules/swift6-features.md +265 -0
  423. moai_adk/templates/.claude/skills/moai-lang-swift/modules/swiftui-patterns.md +314 -0
  424. moai_adk/templates/.claude/skills/moai-lang-swift/reference.md +659 -17
  425. moai_adk/templates/.claude/skills/moai-lang-typescript/SKILL.md +115 -82
  426. moai_adk/templates/.claude/skills/moai-lang-typescript/examples.md +1076 -16
  427. moai_adk/templates/.claude/skills/moai-lang-typescript/reference.md +718 -21
  428. moai_adk/templates/.claude/skills/moai-library-mermaid/SKILL.md +145 -0
  429. moai_adk/templates/.claude/skills/moai-library-mermaid/examples.md +270 -0
  430. moai_adk/templates/.claude/skills/moai-library-mermaid/modules/advanced-patterns.md +465 -0
  431. moai_adk/templates/.claude/skills/moai-library-mermaid/modules/optimization.md +440 -0
  432. moai_adk/templates/.claude/skills/moai-library-mermaid/reference.md +228 -0
  433. moai_adk/templates/.claude/skills/moai-library-nextra/SKILL.md +143 -0
  434. moai_adk/templates/.claude/skills/moai-library-nextra/examples.md +592 -0
  435. moai_adk/templates/.claude/skills/moai-library-nextra/modules/advanced-deployment-patterns.md +182 -0
  436. moai_adk/templates/.claude/skills/moai-library-nextra/modules/advanced-patterns.md +336 -0
  437. moai_adk/templates/.claude/skills/moai-library-nextra/modules/configuration.md +350 -0
  438. moai_adk/templates/.claude/skills/moai-library-nextra/modules/content-architecture-optimization.md +162 -0
  439. moai_adk/templates/.claude/skills/moai-library-nextra/modules/deployment.md +52 -0
  440. moai_adk/templates/.claude/skills/moai-library-nextra/modules/framework-core-configuration.md +186 -0
  441. moai_adk/templates/.claude/skills/moai-library-nextra/modules/i18n-setup.md +55 -0
  442. moai_adk/templates/.claude/skills/moai-library-nextra/modules/mdx-components.md +52 -0
  443. moai_adk/templates/.claude/skills/moai-library-nextra/modules/optimization.md +303 -0
  444. moai_adk/templates/.claude/skills/moai-library-nextra/reference.md +379 -0
  445. moai_adk/templates/.claude/skills/moai-library-shadcn/SKILL.md +175 -0
  446. moai_adk/templates/.claude/skills/moai-library-shadcn/examples.md +575 -0
  447. moai_adk/templates/.claude/skills/moai-library-shadcn/modules/advanced-patterns.md +394 -0
  448. moai_adk/templates/.claude/skills/moai-library-shadcn/modules/optimization.md +278 -0
  449. moai_adk/templates/.claude/skills/moai-library-shadcn/modules/shadcn-components.md +457 -0
  450. moai_adk/templates/.claude/skills/moai-library-shadcn/modules/shadcn-theming.md +373 -0
  451. moai_adk/templates/.claude/skills/moai-library-shadcn/reference.md +74 -0
  452. moai_adk/templates/.claude/skills/moai-platform-auth0/SKILL.md +284 -0
  453. moai_adk/templates/.claude/skills/moai-platform-auth0/examples.md +2446 -0
  454. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/adaptive-mfa.md +233 -0
  455. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/akamai-integration.md +214 -0
  456. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/application-credentials.md +280 -0
  457. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/attack-protection-log-events.md +224 -0
  458. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/attack-protection-overview.md +140 -0
  459. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/bot-detection.md +144 -0
  460. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/breached-password-detection.md +187 -0
  461. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/brute-force-protection.md +189 -0
  462. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/certifications.md +282 -0
  463. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/compliance-overview.md +263 -0
  464. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/continuous-session-protection.md +307 -0
  465. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/customize-mfa.md +177 -0
  466. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/dpop-implementation.md +283 -0
  467. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/fapi-implementation.md +259 -0
  468. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/gdpr-compliance.md +313 -0
  469. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/guardian-configuration.md +269 -0
  470. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/highly-regulated-identity.md +272 -0
  471. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/jwt-fundamentals.md +248 -0
  472. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/mdl-verification.md +210 -0
  473. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/mfa-api-management.md +278 -0
  474. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/mfa-factors.md +226 -0
  475. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/mfa-overview.md +174 -0
  476. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/mtls-sender-constraining.md +316 -0
  477. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/ropg-flow-mfa.md +216 -0
  478. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/security-center.md +325 -0
  479. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/security-guidance.md +277 -0
  480. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/state-parameters.md +177 -0
  481. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/step-up-authentication.md +251 -0
  482. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/suspicious-ip-throttling.md +240 -0
  483. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/tenant-access-control.md +179 -0
  484. moai_adk/templates/.claude/skills/moai-platform-auth0/modules/webauthn-fido.md +235 -0
  485. moai_adk/templates/.claude/skills/moai-platform-auth0/reference.md +224 -0
  486. moai_adk/templates/.claude/skills/moai-platform-clerk/SKILL.md +135 -0
  487. moai_adk/templates/.claude/skills/moai-platform-clerk/examples.md +1426 -0
  488. moai_adk/templates/.claude/skills/moai-platform-clerk/modules/advanced-patterns.md +417 -0
  489. moai_adk/templates/.claude/skills/moai-platform-clerk/reference.md +273 -0
  490. moai_adk/templates/.claude/skills/moai-platform-convex/SKILL.md +158 -0
  491. moai_adk/templates/.claude/skills/moai-platform-convex/examples.md +506 -0
  492. moai_adk/templates/.claude/skills/moai-platform-convex/modules/auth-integration.md +421 -0
  493. moai_adk/templates/.claude/skills/moai-platform-convex/modules/file-storage.md +474 -0
  494. moai_adk/templates/.claude/skills/moai-platform-convex/modules/reactive-queries.md +302 -0
  495. moai_adk/templates/.claude/skills/moai-platform-convex/modules/server-functions.md +452 -0
  496. moai_adk/templates/.claude/skills/moai-platform-convex/reference.md +385 -0
  497. moai_adk/templates/.claude/skills/moai-platform-firebase-auth/SKILL.md +166 -0
  498. moai_adk/templates/.claude/skills/moai-platform-firebase-auth/examples.md +514 -0
  499. moai_adk/templates/.claude/skills/moai-platform-firebase-auth/modules/custom-claims.md +374 -0
  500. moai_adk/templates/.claude/skills/moai-platform-firebase-auth/modules/phone-auth.md +372 -0
  501. moai_adk/templates/.claude/skills/moai-platform-firebase-auth/modules/social-auth.md +339 -0
  502. moai_adk/templates/.claude/skills/moai-platform-firebase-auth/reference.md +382 -0
  503. moai_adk/templates/.claude/skills/moai-platform-firestore/SKILL.md +127 -0
  504. moai_adk/templates/.claude/skills/moai-platform-firestore/examples.md +445 -0
  505. moai_adk/templates/.claude/skills/moai-platform-firestore/modules/offline-cache.md +392 -0
  506. moai_adk/templates/.claude/skills/moai-platform-firestore/modules/realtime-listeners.md +441 -0
  507. moai_adk/templates/.claude/skills/moai-platform-firestore/modules/security-rules.md +352 -0
  508. moai_adk/templates/.claude/skills/moai-platform-firestore/modules/transactions.md +452 -0
  509. moai_adk/templates/.claude/skills/moai-platform-firestore/reference.md +322 -0
  510. moai_adk/templates/.claude/skills/moai-platform-neon/SKILL.md +156 -0
  511. moai_adk/templates/.claude/skills/moai-platform-neon/examples.md +470 -0
  512. moai_adk/templates/.claude/skills/moai-platform-neon/modules/auto-scaling.md +349 -0
  513. moai_adk/templates/.claude/skills/moai-platform-neon/modules/branching-workflows.md +354 -0
  514. moai_adk/templates/.claude/skills/moai-platform-neon/modules/connection-pooling.md +412 -0
  515. moai_adk/templates/.claude/skills/moai-platform-neon/modules/pitr-backups.md +458 -0
  516. moai_adk/templates/.claude/skills/moai-platform-neon/reference.md +272 -0
  517. moai_adk/templates/.claude/skills/moai-platform-railway/SKILL.md +146 -0
  518. moai_adk/templates/.claude/skills/moai-platform-railway/examples.md +539 -0
  519. moai_adk/templates/.claude/skills/moai-platform-railway/modules/docker-deployment.md +261 -0
  520. moai_adk/templates/.claude/skills/moai-platform-railway/modules/multi-service.md +291 -0
  521. moai_adk/templates/.claude/skills/moai-platform-railway/modules/networking-domains.md +338 -0
  522. moai_adk/templates/.claude/skills/moai-platform-railway/modules/volumes-storage.md +353 -0
  523. moai_adk/templates/.claude/skills/moai-platform-railway/reference.md +374 -0
  524. moai_adk/templates/.claude/skills/moai-platform-supabase/SKILL.md +141 -0
  525. moai_adk/templates/.claude/skills/moai-platform-supabase/examples.md +502 -0
  526. moai_adk/templates/.claude/skills/moai-platform-supabase/modules/auth-integration.md +384 -0
  527. moai_adk/templates/.claude/skills/moai-platform-supabase/modules/edge-functions.md +371 -0
  528. moai_adk/templates/.claude/skills/moai-platform-supabase/modules/postgresql-pgvector.md +231 -0
  529. moai_adk/templates/.claude/skills/moai-platform-supabase/modules/realtime-presence.md +354 -0
  530. moai_adk/templates/.claude/skills/moai-platform-supabase/modules/row-level-security.md +286 -0
  531. moai_adk/templates/.claude/skills/moai-platform-supabase/modules/storage-cdn.md +319 -0
  532. moai_adk/templates/.claude/skills/moai-platform-supabase/modules/typescript-patterns.md +453 -0
  533. moai_adk/templates/.claude/skills/moai-platform-supabase/reference.md +284 -0
  534. moai_adk/templates/.claude/skills/moai-platform-vercel/SKILL.md +132 -0
  535. moai_adk/templates/.claude/skills/moai-platform-vercel/examples.md +502 -0
  536. moai_adk/templates/.claude/skills/moai-platform-vercel/modules/analytics-speed.md +348 -0
  537. moai_adk/templates/.claude/skills/moai-platform-vercel/modules/deployment-config.md +344 -0
  538. moai_adk/templates/.claude/skills/moai-platform-vercel/modules/edge-functions.md +222 -0
  539. moai_adk/templates/.claude/skills/moai-platform-vercel/modules/isr-caching.md +306 -0
  540. moai_adk/templates/.claude/skills/moai-platform-vercel/modules/kv-storage.md +399 -0
  541. moai_adk/templates/.claude/skills/moai-platform-vercel/reference.md +360 -0
  542. moai_adk/templates/.claude/skills/moai-tool-ast-grep/SKILL.md +193 -0
  543. moai_adk/templates/.claude/skills/moai-tool-ast-grep/examples.md +1099 -0
  544. moai_adk/templates/.claude/skills/moai-tool-ast-grep/modules/language-specific.md +307 -0
  545. moai_adk/templates/.claude/skills/moai-tool-ast-grep/modules/pattern-syntax.md +237 -0
  546. moai_adk/templates/.claude/skills/moai-tool-ast-grep/modules/refactoring-patterns.md +260 -0
  547. moai_adk/templates/.claude/skills/moai-tool-ast-grep/modules/security-rules.md +239 -0
  548. moai_adk/templates/.claude/skills/moai-tool-ast-grep/reference.md +288 -0
  549. moai_adk/templates/.claude/skills/moai-tool-ast-grep/rules/languages/go.yml +90 -0
  550. moai_adk/templates/.claude/skills/moai-tool-ast-grep/rules/languages/python.yml +101 -0
  551. moai_adk/templates/.claude/skills/moai-tool-ast-grep/rules/languages/typescript.yml +83 -0
  552. moai_adk/templates/.claude/skills/moai-tool-ast-grep/rules/quality/complexity-check.yml +94 -0
  553. moai_adk/templates/.claude/skills/moai-tool-ast-grep/rules/quality/deprecated-apis.yml +84 -0
  554. moai_adk/templates/.claude/skills/moai-tool-ast-grep/rules/security/secrets-detection.yml +89 -0
  555. moai_adk/templates/.claude/skills/moai-tool-ast-grep/rules/security/sql-injection.yml +45 -0
  556. moai_adk/templates/.claude/skills/moai-tool-ast-grep/rules/security/xss-prevention.yml +50 -0
  557. moai_adk/templates/.claude/skills/moai-tool-ast-grep/rules/sgconfig.yml +54 -0
  558. moai_adk/templates/.claude/skills/moai-workflow-jit-docs/SKILL.md +251 -0
  559. moai_adk/templates/.claude/skills/moai-workflow-jit-docs/examples.md +544 -0
  560. moai_adk/templates/.claude/skills/moai-workflow-jit-docs/modules/advanced-patterns.md +379 -0
  561. moai_adk/templates/.claude/skills/moai-workflow-jit-docs/modules/optimization.md +286 -0
  562. moai_adk/templates/.claude/skills/moai-workflow-jit-docs/reference.md +307 -0
  563. moai_adk/templates/.claude/skills/moai-workflow-loop/SKILL.md +197 -0
  564. moai_adk/templates/.claude/skills/moai-workflow-loop/examples.md +1063 -0
  565. moai_adk/templates/.claude/skills/moai-workflow-loop/reference.md +1414 -0
  566. moai_adk/templates/.claude/skills/moai-workflow-project/README.md +190 -0
  567. moai_adk/templates/.claude/skills/moai-workflow-project/SKILL.md +287 -0
  568. moai_adk/templates/.claude/skills/moai-workflow-project/examples.md +547 -0
  569. moai_adk/templates/.claude/skills/moai-workflow-project/reference.md +275 -0
  570. moai_adk/templates/.claude/skills/moai-workflow-project/schemas/config-schema.json +316 -0
  571. moai_adk/templates/.claude/skills/moai-workflow-project/schemas/tab_schema.json +1434 -0
  572. moai_adk/templates/.claude/skills/moai-workflow-project/templates/config-template.json +71 -0
  573. moai_adk/templates/.claude/skills/moai-workflow-project/templates/doc-templates/product-template.md +44 -0
  574. moai_adk/templates/.claude/skills/moai-workflow-project/templates/doc-templates/structure-template.md +48 -0
  575. moai_adk/templates/.claude/skills/moai-workflow-project/templates/doc-templates/tech-template.md +92 -0
  576. moai_adk/templates/.claude/skills/moai-workflow-project/templates/question-templates/config-manager-setup.json +109 -0
  577. moai_adk/templates/.claude/skills/moai-workflow-project/templates/question-templates/language-initializer.json +228 -0
  578. moai_adk/templates/.claude/skills/moai-workflow-project/templates/question-templates/menu-project-config.json +130 -0
  579. moai_adk/templates/.claude/skills/moai-workflow-project/templates/question-templates/project-batch-questions.json +97 -0
  580. moai_adk/templates/.claude/skills/moai-workflow-project/templates/question-templates/spec-workflow-setup.json +150 -0
  581. moai_adk/templates/.claude/skills/moai-workflow-spec/SKILL.md +337 -0
  582. moai_adk/templates/.claude/skills/moai-workflow-spec/examples.md +900 -0
  583. moai_adk/templates/.claude/skills/moai-workflow-spec/modules/advanced-patterns.md +237 -0
  584. moai_adk/templates/.claude/skills/moai-workflow-spec/reference.md +704 -0
  585. moai_adk/templates/.claude/skills/moai-workflow-templates/SKILL.md +270 -0
  586. moai_adk/templates/.claude/skills/moai-workflow-templates/examples.md +552 -0
  587. moai_adk/templates/.claude/skills/moai-workflow-templates/modules/code-templates.md +124 -0
  588. moai_adk/templates/.claude/skills/moai-workflow-templates/modules/feedback-templates.md +100 -0
  589. moai_adk/templates/.claude/skills/moai-workflow-templates/modules/template-optimizer.md +138 -0
  590. moai_adk/templates/.claude/skills/moai-workflow-templates/reference.md +346 -0
  591. moai_adk/templates/.claude/skills/moai-workflow-testing/LICENSE.txt +202 -0
  592. moai_adk/templates/.claude/skills/moai-workflow-testing/SKILL.md +269 -0
  593. moai_adk/templates/.claude/skills/moai-workflow-testing/examples/ai-powered-testing.py +294 -0
  594. moai_adk/templates/.claude/skills/moai-workflow-testing/examples/console_logging.py +35 -0
  595. moai_adk/templates/.claude/skills/moai-workflow-testing/examples/element_discovery.py +40 -0
  596. moai_adk/templates/.claude/skills/moai-workflow-testing/examples/static_html_automation.py +34 -0
  597. moai_adk/templates/.claude/skills/moai-workflow-testing/examples.md +672 -0
  598. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/README.md +269 -0
  599. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/advanced-patterns.md +576 -0
  600. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/ai-debugging.md +302 -0
  601. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/automated-code-review/context7-integration.md +286 -0
  602. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/automated-code-review/review-workflows.md +500 -0
  603. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/automated-code-review/trust5-framework/relevance-analysis.md +154 -0
  604. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/automated-code-review/trust5-framework/safety-analysis.md +148 -0
  605. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/automated-code-review/trust5-framework/scoring-algorithms.md +196 -0
  606. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/automated-code-review/trust5-framework/timeliness-analysis.md +168 -0
  607. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/automated-code-review/trust5-framework/truthfulness-analysis.md +136 -0
  608. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/automated-code-review/trust5-framework/usability-analysis.md +153 -0
  609. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/automated-code-review/trust5-framework.md +257 -0
  610. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/automated-code-review.md +263 -0
  611. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/code-review/analysis-patterns.md +340 -0
  612. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/code-review/core-classes.md +299 -0
  613. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/code-review/tool-integration.md +380 -0
  614. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/debugging/debugging-workflows.md +451 -0
  615. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/debugging/error-analysis.md +442 -0
  616. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/optimization.md +505 -0
  617. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/performance/optimization-patterns.md +473 -0
  618. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/performance/profiling-techniques.md +481 -0
  619. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/performance-optimization/ai-optimization.md +241 -0
  620. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/performance-optimization/bottleneck-detection.md +397 -0
  621. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/performance-optimization/optimization-plan.md +315 -0
  622. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/performance-optimization/profiler-core.md +277 -0
  623. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/performance-optimization/real-time-monitoring.md +187 -0
  624. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/performance-optimization.md +327 -0
  625. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/quality-metrics.md +415 -0
  626. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/refactoring/ai-workflows.md +620 -0
  627. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/refactoring/patterns.md +692 -0
  628. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/security-analysis.md +429 -0
  629. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/smart-refactoring.md +313 -0
  630. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/static-analysis.md +438 -0
  631. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/tdd/core-classes.md +397 -0
  632. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/tdd-context7/advanced-features.md +494 -0
  633. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/tdd-context7/red-green-refactor.md +316 -0
  634. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/tdd-context7/test-generation.md +471 -0
  635. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/tdd-context7/test-patterns.md +371 -0
  636. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/tdd-context7.md +265 -0
  637. moai_adk/templates/.claude/skills/moai-workflow-testing/modules/trust5-validation.md +428 -0
  638. moai_adk/templates/.claude/skills/moai-workflow-testing/reference/playwright-best-practices.md +57 -0
  639. moai_adk/templates/.claude/skills/moai-workflow-testing/reference.md +440 -0
  640. moai_adk/templates/.claude/skills/moai-workflow-testing/scripts/with_server.py +218 -0
  641. moai_adk/templates/.claude/skills/moai-workflow-testing/templates/alfred-integration.md +376 -0
  642. moai_adk/templates/.claude/skills/moai-workflow-testing/workflows/enterprise-testing-workflow.py +571 -0
  643. moai_adk/templates/.claude/skills/moai-workflow-worktree/SKILL.md +228 -0
  644. moai_adk/templates/.claude/skills/moai-workflow-worktree/examples.md +606 -0
  645. moai_adk/templates/.claude/skills/moai-workflow-worktree/modules/integration-patterns.md +149 -0
  646. moai_adk/templates/.claude/skills/moai-workflow-worktree/modules/moai-adk-integration.md +245 -0
  647. moai_adk/templates/.claude/skills/moai-workflow-worktree/modules/parallel-advanced.md +310 -0
  648. moai_adk/templates/.claude/skills/moai-workflow-worktree/modules/parallel-development.md +202 -0
  649. moai_adk/templates/.claude/skills/moai-workflow-worktree/modules/parallel-workflows.md +302 -0
  650. moai_adk/templates/.claude/skills/moai-workflow-worktree/modules/registry-architecture.md +271 -0
  651. moai_adk/templates/.claude/skills/moai-workflow-worktree/modules/resource-optimization.md +300 -0
  652. moai_adk/templates/.claude/skills/moai-workflow-worktree/modules/tools-integration.md +280 -0
  653. moai_adk/templates/.claude/skills/moai-workflow-worktree/modules/troubleshooting.md +397 -0
  654. moai_adk/templates/.claude/skills/moai-workflow-worktree/modules/worktree-commands.md +296 -0
  655. moai_adk/templates/.claude/skills/moai-workflow-worktree/modules/worktree-management.md +217 -0
  656. moai_adk/templates/.claude/skills/moai-workflow-worktree/reference.md +357 -0
  657. moai_adk/templates/.git-hooks/pre-commit +128 -0
  658. moai_adk/templates/.git-hooks/pre-push +468 -0
  659. moai_adk/templates/.github/workflows/ci-universal.yml +1314 -0
  660. moai_adk/templates/.github/workflows/security-secrets-check.yml +179 -0
  661. moai_adk/templates/.github/workflows/spec-issue-sync.yml +206 -36
  662. moai_adk/templates/.gitignore +152 -13
  663. moai_adk/templates/.lsp.json +152 -0
  664. moai_adk/templates/.mcp.json +13 -0
  665. moai_adk/templates/.moai/announcements/en.json +18 -0
  666. moai_adk/templates/.moai/announcements/ja.json +18 -0
  667. moai_adk/templates/.moai/announcements/ko.json +18 -0
  668. moai_adk/templates/.moai/announcements/zh.json +18 -0
  669. moai_adk/templates/.moai/config/config.yaml +64 -0
  670. moai_adk/templates/.moai/config/multilingual-triggers.yaml +213 -0
  671. moai_adk/templates/.moai/config/sections/git-strategy.yaml +116 -0
  672. moai_adk/templates/.moai/config/sections/language.yaml +11 -0
  673. moai_adk/templates/.moai/config/sections/llm.yaml +41 -0
  674. moai_adk/templates/.moai/config/sections/pricing.yaml +30 -0
  675. moai_adk/templates/.moai/config/sections/project.yaml +13 -0
  676. moai_adk/templates/.moai/config/sections/quality.yaml +55 -0
  677. moai_adk/templates/.moai/config/sections/ralph.yaml +55 -0
  678. moai_adk/templates/.moai/config/sections/system.yaml +59 -0
  679. moai_adk/templates/.moai/config/sections/user.yaml +5 -0
  680. moai_adk/templates/.moai/config/statusline-config.yaml +92 -0
  681. moai_adk/templates/.moai/llm-configs/glm.json +22 -0
  682. moai_adk/templates/CLAUDE.ja.md +343 -0
  683. moai_adk/templates/CLAUDE.ko.md +343 -0
  684. moai_adk/templates/CLAUDE.md +274 -246
  685. moai_adk/templates/CLAUDE.zh.md +343 -0
  686. moai_adk/utils/__init__.py +24 -2
  687. moai_adk/utils/banner.py +9 -13
  688. moai_adk/utils/common.py +331 -0
  689. moai_adk/utils/link_validator.py +241 -0
  690. moai_adk/utils/logger.py +4 -9
  691. moai_adk/utils/safe_file_reader.py +206 -0
  692. moai_adk/utils/timeout.py +160 -0
  693. moai_adk/utils/toon_utils.py +256 -0
  694. moai_adk/version.py +22 -0
  695. moai_adk-1.1.0.dist-info/METADATA +2443 -0
  696. moai_adk-1.1.0.dist-info/RECORD +701 -0
  697. {moai_adk-0.8.0.dist-info → moai_adk-1.1.0.dist-info}/WHEEL +1 -1
  698. moai_adk-1.1.0.dist-info/entry_points.txt +5 -0
  699. moai_adk-1.1.0.dist-info/licenses/LICENSE +99 -0
  700. moai_adk/cli/commands/backup.py +0 -80
  701. moai_adk/templates/.claude/agents/alfred/cc-manager.md +0 -293
  702. moai_adk/templates/.claude/agents/alfred/debug-helper.md +0 -196
  703. moai_adk/templates/.claude/agents/alfred/doc-syncer.md +0 -207
  704. moai_adk/templates/.claude/agents/alfred/git-manager.md +0 -375
  705. moai_adk/templates/.claude/agents/alfred/implementation-planner.md +0 -343
  706. moai_adk/templates/.claude/agents/alfred/project-manager.md +0 -246
  707. moai_adk/templates/.claude/agents/alfred/quality-gate.md +0 -320
  708. moai_adk/templates/.claude/agents/alfred/skill-factory.md +0 -837
  709. moai_adk/templates/.claude/agents/alfred/spec-builder.md +0 -272
  710. moai_adk/templates/.claude/agents/alfred/tag-agent.md +0 -265
  711. moai_adk/templates/.claude/agents/alfred/tdd-implementer.md +0 -311
  712. moai_adk/templates/.claude/agents/alfred/trust-checker.md +0 -352
  713. moai_adk/templates/.claude/commands/alfred/0-project.md +0 -1184
  714. moai_adk/templates/.claude/commands/alfred/1-plan.md +0 -665
  715. moai_adk/templates/.claude/commands/alfred/2-run.md +0 -488
  716. moai_adk/templates/.claude/commands/alfred/3-sync.md +0 -623
  717. moai_adk/templates/.claude/hooks/alfred/HOOK_SCHEMA_VALIDATION.md +0 -313
  718. moai_adk/templates/.claude/hooks/alfred/README.md +0 -230
  719. moai_adk/templates/.claude/hooks/alfred/alfred_hooks.py +0 -174
  720. moai_adk/templates/.claude/hooks/alfred/core/__init__.py +0 -170
  721. moai_adk/templates/.claude/hooks/alfred/core/context.py +0 -67
  722. moai_adk/templates/.claude/hooks/alfred/core/project.py +0 -416
  723. moai_adk/templates/.claude/hooks/alfred/core/tags.py +0 -198
  724. moai_adk/templates/.claude/hooks/alfred/handlers/__init__.py +0 -21
  725. moai_adk/templates/.claude/hooks/alfred/handlers/notification.py +0 -25
  726. moai_adk/templates/.claude/hooks/alfred/handlers/session.py +0 -161
  727. moai_adk/templates/.claude/hooks/alfred/handlers/tool.py +0 -90
  728. moai_adk/templates/.claude/hooks/alfred/handlers/user.py +0 -42
  729. moai_adk/templates/.claude/hooks/alfred/test_hook_output.py +0 -175
  730. moai_adk/templates/.claude/output-styles/alfred/agentic-coding.md +0 -640
  731. moai_adk/templates/.claude/output-styles/alfred/moai-adk-learning.md +0 -696
  732. moai_adk/templates/.claude/output-styles/alfred/study-with-alfred.md +0 -474
  733. moai_adk/templates/.claude/skills/moai-alfred-ears-authoring/SKILL.md +0 -113
  734. moai_adk/templates/.claude/skills/moai-alfred-ears-authoring/examples.md +0 -29
  735. moai_adk/templates/.claude/skills/moai-alfred-ears-authoring/reference.md +0 -28
  736. moai_adk/templates/.claude/skills/moai-alfred-git-workflow/SKILL.md +0 -122
  737. moai_adk/templates/.claude/skills/moai-alfred-git-workflow/examples.md +0 -29
  738. moai_adk/templates/.claude/skills/moai-alfred-git-workflow/reference.md +0 -29
  739. moai_adk/templates/.claude/skills/moai-alfred-interactive-questions/SKILL.md +0 -237
  740. moai_adk/templates/.claude/skills/moai-alfred-interactive-questions/examples.md +0 -615
  741. moai_adk/templates/.claude/skills/moai-alfred-interactive-questions/reference.md +0 -653
  742. moai_adk/templates/.claude/skills/moai-alfred-language-detection/SKILL.md +0 -113
  743. moai_adk/templates/.claude/skills/moai-alfred-language-detection/examples.md +0 -29
  744. moai_adk/templates/.claude/skills/moai-alfred-language-detection/reference.md +0 -28
  745. moai_adk/templates/.claude/skills/moai-alfred-spec-metadata-validation/SKILL.md +0 -113
  746. moai_adk/templates/.claude/skills/moai-alfred-spec-metadata-validation/examples.md +0 -29
  747. moai_adk/templates/.claude/skills/moai-alfred-spec-metadata-validation/reference.md +0 -28
  748. moai_adk/templates/.claude/skills/moai-alfred-tag-scanning/SKILL.md +0 -113
  749. moai_adk/templates/.claude/skills/moai-alfred-tag-scanning/examples.md +0 -29
  750. moai_adk/templates/.claude/skills/moai-alfred-tag-scanning/reference.md +0 -28
  751. moai_adk/templates/.claude/skills/moai-alfred-trust-validation/SKILL.md +0 -113
  752. moai_adk/templates/.claude/skills/moai-alfred-trust-validation/examples.md +0 -29
  753. moai_adk/templates/.claude/skills/moai-alfred-trust-validation/reference.md +0 -28
  754. moai_adk/templates/.claude/skills/moai-cc-agents/SKILL.md +0 -269
  755. moai_adk/templates/.claude/skills/moai-cc-agents/templates/agent-template.md +0 -32
  756. moai_adk/templates/.claude/skills/moai-cc-claude-md/SKILL.md +0 -298
  757. moai_adk/templates/.claude/skills/moai-cc-claude-md/templates/CLAUDE-template.md +0 -26
  758. moai_adk/templates/.claude/skills/moai-cc-commands/SKILL.md +0 -307
  759. moai_adk/templates/.claude/skills/moai-cc-commands/templates/command-template.md +0 -21
  760. moai_adk/templates/.claude/skills/moai-cc-hooks/SKILL.md +0 -252
  761. moai_adk/templates/.claude/skills/moai-cc-hooks/scripts/pre-bash-check.sh +0 -19
  762. moai_adk/templates/.claude/skills/moai-cc-hooks/scripts/preserve-permissions.sh +0 -19
  763. moai_adk/templates/.claude/skills/moai-cc-hooks/scripts/validate-bash-command.py +0 -24
  764. moai_adk/templates/.claude/skills/moai-cc-mcp-plugins/SKILL.md +0 -199
  765. moai_adk/templates/.claude/skills/moai-cc-mcp-plugins/templates/settings-mcp-template.json +0 -39
  766. moai_adk/templates/.claude/skills/moai-cc-memory/SKILL.md +0 -316
  767. moai_adk/templates/.claude/skills/moai-cc-memory/templates/session-summary-template.md +0 -18
  768. moai_adk/templates/.claude/skills/moai-cc-settings/SKILL.md +0 -263
  769. moai_adk/templates/.claude/skills/moai-cc-settings/templates/settings-complete-template.json +0 -30
  770. moai_adk/templates/.claude/skills/moai-cc-skills/SKILL.md +0 -291
  771. moai_adk/templates/.claude/skills/moai-cc-skills/templates/SKILL-template.md +0 -15
  772. moai_adk/templates/.claude/skills/moai-domain-cli-tool/SKILL.md +0 -123
  773. moai_adk/templates/.claude/skills/moai-domain-cli-tool/examples.md +0 -29
  774. moai_adk/templates/.claude/skills/moai-domain-cli-tool/reference.md +0 -30
  775. moai_adk/templates/.claude/skills/moai-domain-data-science/SKILL.md +0 -123
  776. moai_adk/templates/.claude/skills/moai-domain-data-science/examples.md +0 -29
  777. moai_adk/templates/.claude/skills/moai-domain-data-science/reference.md +0 -30
  778. moai_adk/templates/.claude/skills/moai-domain-devops/SKILL.md +0 -124
  779. moai_adk/templates/.claude/skills/moai-domain-devops/examples.md +0 -29
  780. moai_adk/templates/.claude/skills/moai-domain-devops/reference.md +0 -31
  781. moai_adk/templates/.claude/skills/moai-domain-ml/SKILL.md +0 -123
  782. moai_adk/templates/.claude/skills/moai-domain-ml/examples.md +0 -29
  783. moai_adk/templates/.claude/skills/moai-domain-ml/reference.md +0 -30
  784. moai_adk/templates/.claude/skills/moai-domain-mobile-app/SKILL.md +0 -123
  785. moai_adk/templates/.claude/skills/moai-domain-mobile-app/examples.md +0 -29
  786. moai_adk/templates/.claude/skills/moai-domain-mobile-app/reference.md +0 -30
  787. moai_adk/templates/.claude/skills/moai-domain-security/SKILL.md +0 -123
  788. moai_adk/templates/.claude/skills/moai-domain-security/examples.md +0 -29
  789. moai_adk/templates/.claude/skills/moai-domain-security/reference.md +0 -30
  790. moai_adk/templates/.claude/skills/moai-domain-web-api/SKILL.md +0 -123
  791. moai_adk/templates/.claude/skills/moai-domain-web-api/examples.md +0 -29
  792. moai_adk/templates/.claude/skills/moai-domain-web-api/reference.md +0 -30
  793. moai_adk/templates/.claude/skills/moai-essentials-debug/SKILL.md +0 -303
  794. moai_adk/templates/.claude/skills/moai-essentials-debug/examples.md +0 -1064
  795. moai_adk/templates/.claude/skills/moai-essentials-debug/reference.md +0 -1047
  796. moai_adk/templates/.claude/skills/moai-essentials-perf/SKILL.md +0 -113
  797. moai_adk/templates/.claude/skills/moai-essentials-perf/examples.md +0 -29
  798. moai_adk/templates/.claude/skills/moai-essentials-perf/reference.md +0 -28
  799. moai_adk/templates/.claude/skills/moai-essentials-refactor/SKILL.md +0 -113
  800. moai_adk/templates/.claude/skills/moai-essentials-refactor/examples.md +0 -29
  801. moai_adk/templates/.claude/skills/moai-essentials-refactor/reference.md +0 -28
  802. moai_adk/templates/.claude/skills/moai-essentials-review/SKILL.md +0 -113
  803. moai_adk/templates/.claude/skills/moai-essentials-review/examples.md +0 -29
  804. moai_adk/templates/.claude/skills/moai-essentials-review/reference.md +0 -28
  805. moai_adk/templates/.claude/skills/moai-foundation-ears/SKILL.md +0 -113
  806. moai_adk/templates/.claude/skills/moai-foundation-ears/examples.md +0 -29
  807. moai_adk/templates/.claude/skills/moai-foundation-ears/reference.md +0 -28
  808. moai_adk/templates/.claude/skills/moai-foundation-git/SKILL.md +0 -122
  809. moai_adk/templates/.claude/skills/moai-foundation-git/examples.md +0 -29
  810. moai_adk/templates/.claude/skills/moai-foundation-git/reference.md +0 -29
  811. moai_adk/templates/.claude/skills/moai-foundation-langs/SKILL.md +0 -113
  812. moai_adk/templates/.claude/skills/moai-foundation-langs/examples.md +0 -29
  813. moai_adk/templates/.claude/skills/moai-foundation-langs/reference.md +0 -28
  814. moai_adk/templates/.claude/skills/moai-foundation-specs/SKILL.md +0 -113
  815. moai_adk/templates/.claude/skills/moai-foundation-specs/examples.md +0 -29
  816. moai_adk/templates/.claude/skills/moai-foundation-specs/reference.md +0 -28
  817. moai_adk/templates/.claude/skills/moai-foundation-tags/SKILL.md +0 -113
  818. moai_adk/templates/.claude/skills/moai-foundation-tags/examples.md +0 -29
  819. moai_adk/templates/.claude/skills/moai-foundation-tags/reference.md +0 -28
  820. moai_adk/templates/.claude/skills/moai-foundation-trust/SKILL.md +0 -307
  821. moai_adk/templates/.claude/skills/moai-foundation-trust/examples.md +0 -0
  822. moai_adk/templates/.claude/skills/moai-foundation-trust/reference.md +0 -1099
  823. moai_adk/templates/.claude/skills/moai-lang-c/SKILL.md +0 -124
  824. moai_adk/templates/.claude/skills/moai-lang-c/examples.md +0 -29
  825. moai_adk/templates/.claude/skills/moai-lang-c/reference.md +0 -31
  826. moai_adk/templates/.claude/skills/moai-lang-dart/SKILL.md +0 -123
  827. moai_adk/templates/.claude/skills/moai-lang-dart/examples.md +0 -29
  828. moai_adk/templates/.claude/skills/moai-lang-dart/reference.md +0 -30
  829. moai_adk/templates/.claude/skills/moai-lang-shell/SKILL.md +0 -123
  830. moai_adk/templates/.claude/skills/moai-lang-shell/examples.md +0 -29
  831. moai_adk/templates/.claude/skills/moai-lang-shell/reference.md +0 -30
  832. moai_adk/templates/.claude/skills/moai-lang-sql/SKILL.md +0 -124
  833. moai_adk/templates/.claude/skills/moai-lang-sql/examples.md +0 -29
  834. moai_adk/templates/.claude/skills/moai-lang-sql/reference.md +0 -31
  835. moai_adk/templates/.claude/skills/moai-skill-factory/CHECKLIST.md +0 -482
  836. moai_adk/templates/.claude/skills/moai-skill-factory/EXAMPLES.md +0 -278
  837. moai_adk/templates/.claude/skills/moai-skill-factory/INTERACTIVE-DISCOVERY.md +0 -524
  838. moai_adk/templates/.claude/skills/moai-skill-factory/METADATA.md +0 -477
  839. moai_adk/templates/.claude/skills/moai-skill-factory/PARALLEL-ANALYSIS-REPORT.md +0 -429
  840. moai_adk/templates/.claude/skills/moai-skill-factory/PYTHON-VERSION-MATRIX.md +0 -391
  841. moai_adk/templates/.claude/skills/moai-skill-factory/SKILL-FACTORY-WORKFLOW.md +0 -431
  842. moai_adk/templates/.claude/skills/moai-skill-factory/SKILL-UPDATE-ADVISOR.md +0 -577
  843. moai_adk/templates/.claude/skills/moai-skill-factory/SKILL.md +0 -271
  844. moai_adk/templates/.claude/skills/moai-skill-factory/STEP-BY-STEP-GUIDE.md +0 -466
  845. moai_adk/templates/.claude/skills/moai-skill-factory/STRUCTURE.md +0 -583
  846. moai_adk/templates/.claude/skills/moai-skill-factory/WEB-RESEARCH.md +0 -526
  847. moai_adk/templates/.claude/skills/moai-skill-factory/reference.md +0 -465
  848. moai_adk/templates/.claude/skills/moai-skill-factory/scripts/generate-structure.sh +0 -328
  849. moai_adk/templates/.claude/skills/moai-skill-factory/scripts/validate-skill.sh +0 -312
  850. moai_adk/templates/.claude/skills/moai-skill-factory/templates/SKILL_TEMPLATE.md +0 -245
  851. moai_adk/templates/.claude/skills/moai-skill-factory/templates/examples-template.md +0 -285
  852. moai_adk/templates/.claude/skills/moai-skill-factory/templates/reference-template.md +0 -278
  853. moai_adk/templates/.claude/skills/moai-skill-factory/templates/scripts-template.sh +0 -303
  854. moai_adk/templates/.claude/skills/moai-spec-authoring/README.md +0 -137
  855. moai_adk/templates/.claude/skills/moai-spec-authoring/SKILL.md +0 -218
  856. moai_adk/templates/.claude/skills/moai-spec-authoring/examples/validate-spec.sh +0 -161
  857. moai_adk/templates/.claude/skills/moai-spec-authoring/examples.md +0 -541
  858. moai_adk/templates/.claude/skills/moai-spec-authoring/reference.md +0 -622
  859. moai_adk/templates/.github/ISSUE_TEMPLATE/spec.yml +0 -176
  860. moai_adk/templates/.github/PULL_REQUEST_TEMPLATE.md +0 -69
  861. moai_adk/templates/.github/workflows/moai-gitflow.yml +0 -256
  862. moai_adk/templates/.moai/config.json +0 -96
  863. moai_adk/templates/.moai/memory/CLAUDE-AGENTS-GUIDE.md +0 -208
  864. moai_adk/templates/.moai/memory/CLAUDE-PRACTICES.md +0 -369
  865. moai_adk/templates/.moai/memory/CLAUDE-RULES.md +0 -539
  866. moai_adk/templates/.moai/memory/CONFIG-SCHEMA.md +0 -444
  867. moai_adk/templates/.moai/memory/DEVELOPMENT-GUIDE.md +0 -344
  868. moai_adk/templates/.moai/memory/GITFLOW-PROTECTION-POLICY.md +0 -220
  869. moai_adk/templates/.moai/memory/SKILLS-DESCRIPTION-POLICY.md +0 -218
  870. moai_adk/templates/.moai/memory/SPEC-METADATA.md +0 -356
  871. moai_adk/templates/.moai/memory/config-schema.md +0 -444
  872. moai_adk/templates/.moai/memory/gitflow-protection-policy.md +0 -220
  873. moai_adk/templates/.moai/memory/spec-metadata.md +0 -356
  874. moai_adk/templates/.moai/project/product.md +0 -161
  875. moai_adk/templates/.moai/project/structure.md +0 -156
  876. moai_adk/templates/.moai/project/tech.md +0 -227
  877. moai_adk/templates/__init__.py +0 -2
  878. moai_adk-0.8.0.dist-info/METADATA +0 -1722
  879. moai_adk-0.8.0.dist-info/RECORD +0 -282
  880. moai_adk-0.8.0.dist-info/entry_points.txt +0 -2
  881. moai_adk-0.8.0.dist-info/licenses/LICENSE +0 -21
@@ -0,0 +1,1920 @@
1
+ """
2
+ Comprehensive Error Recovery System - Phase 3 Enterprise Edition
3
+
4
+ Advanced enterprise-grade error recovery with automatic healing, data consistency checks,
5
+ rollback capabilities, state persistence, and self-healing mechanisms.
6
+
7
+ Phase 3 Features:
8
+ - Event-driven error recovery architecture
9
+ - Automatic system recovery from all failure modes
10
+ - Data consistency checks and repair mechanisms
11
+ - Comprehensive rollback and state persistence
12
+ - Self-healing capabilities with circuit breakers
13
+ - Dead letter queue handling for failed operations
14
+ - Multi-strategy recovery with exponential backoff
15
+ - Disaster recovery and business continuity
16
+ - Real-time failure mode analysis and prediction
17
+
18
+ Legacy Features:
19
+ - Error detection and classification
20
+ - Recovery procedures and fallback mechanisms
21
+ - Integration with research hooks, agents, and skills
22
+ - Documentation of error handling procedures
23
+ - Troubleshooting guides and automated recovery
24
+ - Multi-level error handling (critical, warning, info)
25
+ - Manual recovery procedures
26
+ - Error logging and tracking
27
+ - System health monitoring
28
+ - Emergency recovery procedures
29
+ """
30
+
31
+ import asyncio
32
+ import hashlib
33
+ import json
34
+ import logging
35
+ import os
36
+ import sys
37
+ import tempfile
38
+ import threading
39
+ import time
40
+ import traceback
41
+ import uuid
42
+ from collections import defaultdict, deque
43
+ from dataclasses import asdict, dataclass, field
44
+ from datetime import datetime, timedelta, timezone
45
+ from enum import Enum
46
+ from pathlib import Path
47
+ from typing import Any, Callable, Dict, List, Optional
48
+
49
+ # Configure comprehensive logging
50
+ logging.basicConfig(
51
+ level=logging.INFO,
52
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
53
+ handlers=[
54
+ logging.FileHandler(Path(tempfile.gettempdir()) / "moai_error_recovery.log"),
55
+ logging.StreamHandler(sys.stdout),
56
+ ],
57
+ )
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+
62
+ class ErrorSeverity(Enum):
63
+ """Error severity levels"""
64
+
65
+ CRITICAL = "critical" # System failure, immediate attention required
66
+ HIGH = "high" # Major functionality impacted
67
+ MEDIUM = "medium" # Partial functionality impacted
68
+ LOW = "low" # Minor issue, can be deferred
69
+ INFO = "info" # Informational message
70
+
71
+
72
+ class ErrorCategory(Enum):
73
+ """Error categories for classification"""
74
+
75
+ SYSTEM = "system" # System-level errors
76
+ CONFIGURATION = "configuration" # Configuration errors
77
+ RESEARCH = "research" # Research workflow errors
78
+ INTEGRATION = "integration" # Integration errors
79
+ COMMUNICATION = "communication" # Agent/communication errors
80
+ VALIDATION = "validation" # Validation errors
81
+ PERFORMANCE = "performance" # Performance issues
82
+ RESOURCE = "resource" # Resource exhaustion
83
+ NETWORK = "network" # Network-related errors
84
+ USER_INPUT = "user_input" # User input errors
85
+
86
+
87
+ # Phase 3: Advanced Error Recovery Enums
88
+
89
+
90
+ class FailureMode(Enum):
91
+ """Types of failure modes in the system"""
92
+
93
+ HOOK_EXECUTION_FAILURE = "hook_execution_failure"
94
+ RESOURCE_EXHAUSTION = "resource_exhaustion"
95
+ DATA_CORRUPTION = "data_corruption"
96
+ NETWORK_FAILURE = "network_failure"
97
+ SYSTEM_OVERLOAD = "system_overload"
98
+ CONFIGURATION_ERROR = "configuration_error"
99
+ TIMEOUT_FAILURE = "timeout_failure"
100
+ MEMORY_LEAK = "memory_leak"
101
+ DEADLOCK = "deadlock"
102
+ AUTHENTICATION_FAILURE = "authentication_failure"
103
+ VALIDATION_FAILURE = "validation_failure"
104
+ EXTERNAL_SERVICE_FAILURE = "external_service_failure"
105
+ STORAGE_FAILURE = "storage_failure"
106
+ CONCURRENCY_ISSUE = "concurrency_issue"
107
+ CIRCUIT_BREAKER_TRIPPED = "circuit_breaker_tripped"
108
+ CASCADE_FAILURE = "cascade_failure"
109
+
110
+
111
+ class RecoveryStrategy(Enum):
112
+ """Recovery strategies for different failure modes"""
113
+
114
+ RETRY_WITH_BACKOFF = "retry_with_backoff"
115
+ CIRCUIT_BREAKER = "circuit_breaker"
116
+ ROLLBACK = "rollback"
117
+ FAILOVER = "failover"
118
+ DEGRADE_SERVICE = "degrade_service"
119
+ RESTART_COMPONENT = "restart_component"
120
+ DATA_REPAIR = "data_repair"
121
+ CLEAR_CACHE = "clear_cache"
122
+ SCALE_RESOURCES = "scale_resources"
123
+ NOTIFY_ADMIN = "notify_admin"
124
+ QUARANTINE = "quarantine"
125
+ IGNORE = "ignore"
126
+ ISOLATE_COMPONENT = "isolate_component"
127
+ EMERGENCY_STOP = "emergency_stop"
128
+
129
+
130
+ class ConsistencyLevel(Enum):
131
+ """Data consistency levels"""
132
+
133
+ STRONG = "strong" # Immediate consistency
134
+ EVENTUAL = "eventual" # Eventually consistent
135
+ WEAK = "weak" # Weak consistency
136
+ CUSTOM = "custom" # Custom consistency rules
137
+
138
+
139
+ class RecoveryStatus(Enum):
140
+ """Recovery operation status"""
141
+
142
+ PENDING = "pending"
143
+ IN_PROGRESS = "in_progress"
144
+ COMPLETED = "completed"
145
+ FAILED = "failed"
146
+ CANCELLED = "cancelled"
147
+ ROLLED_BACK = "rolled_back"
148
+
149
+
150
+ @dataclass
151
+ class ErrorReport:
152
+ """Comprehensive error report structure"""
153
+
154
+ id: str
155
+ timestamp: datetime
156
+ severity: ErrorSeverity
157
+ category: ErrorCategory
158
+ message: str
159
+ details: Dict[str, Any]
160
+ stack_trace: Optional[str]
161
+ context: Dict[str, Any]
162
+ recovery_attempted: bool = False
163
+ recovery_successful: bool = False
164
+ resolution_message: Optional[str] = None
165
+
166
+
167
+ @dataclass
168
+ class RecoveryAction:
169
+ """Recovery action definition"""
170
+
171
+ name: str
172
+ description: str
173
+ action_type: str # "automatic", "manual", "assisted"
174
+ severity_filter: List[ErrorSeverity]
175
+ category_filter: List[ErrorCategory]
176
+ handler: Callable
177
+ timeout: Optional[float] = None
178
+ max_attempts: int = 3
179
+ success_criteria: Optional[str] = None
180
+
181
+
182
+ @dataclass
183
+ class RecoveryResult:
184
+ """Result of recovery action"""
185
+
186
+ success: bool
187
+ action_name: str
188
+ message: str
189
+ duration: float
190
+ details: Dict[str, Any] = None
191
+ next_actions: List[str] = None
192
+
193
+
194
+ # Phase 3: Advanced Error Recovery Dataclasses
195
+
196
+
197
+ @dataclass
198
+ class FailureEvent:
199
+ """Represents a failure event in the system"""
200
+
201
+ failure_id: str
202
+ failure_mode: FailureMode
203
+ timestamp: datetime
204
+ component: str
205
+ description: str
206
+ severity: str # "low", "medium", "high", "critical"
207
+ context: Dict[str, Any] = field(default_factory=dict)
208
+ error_details: Optional[Dict[str, Any]] = None
209
+ affected_operations: List[str] = field(default_factory=list)
210
+ auto_recovery_eligible: bool = True
211
+ retry_count: int = 0
212
+ metadata: Dict[str, Any] = field(default_factory=dict)
213
+ parent_failure_id: Optional[str] = None # For cascade failures
214
+ root_cause: Optional[str] = None
215
+
216
+ def to_dict(self) -> Dict[str, Any]:
217
+ """Convert to dictionary for serialization"""
218
+ return {
219
+ "failure_id": self.failure_id,
220
+ "failure_mode": self.failure_mode.value,
221
+ "timestamp": self.timestamp.isoformat(),
222
+ "component": self.component,
223
+ "description": self.description,
224
+ "severity": self.severity,
225
+ "context": self.context,
226
+ "error_details": self.error_details,
227
+ "affected_operations": self.affected_operations,
228
+ "auto_recovery_eligible": self.auto_recovery_eligible,
229
+ "retry_count": self.retry_count,
230
+ "metadata": self.metadata,
231
+ "parent_failure_id": self.parent_failure_id,
232
+ "root_cause": self.root_cause,
233
+ }
234
+
235
+ @classmethod
236
+ def from_dict(cls, data: Dict[str, Any]) -> "FailureEvent":
237
+ """Create from dictionary"""
238
+ return cls(
239
+ failure_id=data["failure_id"],
240
+ failure_mode=FailureMode(data["failure_mode"]),
241
+ timestamp=datetime.fromisoformat(data["timestamp"]),
242
+ component=data["component"],
243
+ description=data["description"],
244
+ severity=data["severity"],
245
+ context=data.get("context", {}),
246
+ error_details=data.get("error_details"),
247
+ affected_operations=data.get("affected_operations", []),
248
+ auto_recovery_eligible=data.get("auto_recovery_eligible", True),
249
+ retry_count=data.get("retry_count", 0),
250
+ metadata=data.get("metadata", {}),
251
+ parent_failure_id=data.get("parent_failure_id"),
252
+ root_cause=data.get("root_cause"),
253
+ )
254
+
255
+
256
+ @dataclass
257
+ class AdvancedRecoveryAction:
258
+ """Advanced recovery action with enhanced capabilities"""
259
+
260
+ action_id: str
261
+ failure_id: str
262
+ strategy: RecoveryStrategy
263
+ timestamp: datetime
264
+ status: RecoveryStatus = RecoveryStatus.PENDING
265
+ description: str = ""
266
+ parameters: Dict[str, Any] = field(default_factory=dict)
267
+ execution_log: List[str] = field(default_factory=list)
268
+ rollback_available: bool = True
269
+ timeout_seconds: float = 300.0
270
+ retry_attempts: int = 0
271
+ max_retries: int = 3
272
+ rollback_action_id: Optional[str] = None
273
+ dependencies: List[str] = field(default_factory=list) # Other actions this depends on
274
+ priority: int = 5 # 1-10, lower number = higher priority
275
+
276
+ def to_dict(self) -> Dict[str, Any]:
277
+ """Convert to dictionary for serialization"""
278
+ return {
279
+ "action_id": self.action_id,
280
+ "failure_id": self.failure_id,
281
+ "strategy": self.strategy.value,
282
+ "timestamp": self.timestamp.isoformat(),
283
+ "status": self.status.value,
284
+ "description": self.description,
285
+ "parameters": self.parameters,
286
+ "execution_log": self.execution_log,
287
+ "rollback_available": self.rollback_available,
288
+ "timeout_seconds": self.timeout_seconds,
289
+ "retry_attempts": self.retry_attempts,
290
+ "max_retries": self.max_retries,
291
+ "rollback_action_id": self.rollback_action_id,
292
+ "dependencies": self.dependencies,
293
+ "priority": self.priority,
294
+ }
295
+
296
+
297
+ @dataclass
298
+ class SystemSnapshot:
299
+ """Represents a system state snapshot for rollback"""
300
+
301
+ snapshot_id: str
302
+ timestamp: datetime
303
+ component_states: Dict[str, Dict[str, Any]]
304
+ configuration_hash: str
305
+ data_checksums: Dict[str, str]
306
+ metadata: Dict[str, Any] = field(default_factory=dict)
307
+ parent_snapshot_id: Optional[str] = None
308
+ is_rollback_point: bool = False
309
+ description: str = ""
310
+ consistency_level: ConsistencyLevel = ConsistencyLevel.EVENTUAL
311
+
312
+ def to_dict(self) -> Dict[str, Any]:
313
+ """Convert to dictionary for serialization"""
314
+ return {
315
+ "snapshot_id": self.snapshot_id,
316
+ "timestamp": self.timestamp.isoformat(),
317
+ "component_states": self.component_states,
318
+ "configuration_hash": self.configuration_hash,
319
+ "data_checksums": self.data_checksums,
320
+ "metadata": self.metadata,
321
+ "parent_snapshot_id": self.parent_snapshot_id,
322
+ "is_rollback_point": self.is_rollback_point,
323
+ "description": self.description,
324
+ "consistency_level": self.consistency_level.value,
325
+ }
326
+
327
+
328
+ class ErrorRecoverySystem:
329
+ """Comprehensive error handling and recovery system"""
330
+
331
+ def __init__(self, project_root: Path = None):
332
+ self.project_root = project_root or Path.cwd()
333
+ self.error_log_dir = self.project_root / ".moai" / "error_logs"
334
+ self.error_log_dir.mkdir(parents=True, exist_ok=True)
335
+
336
+ # Error tracking
337
+ self.active_errors: Dict[str, ErrorReport] = {}
338
+ self.error_history: List[ErrorReport] = []
339
+ self.recovery_actions: Dict[str, RecoveryAction] = {}
340
+ self.error_stats: Dict[str, Any] = {
341
+ "total_errors": 0,
342
+ "by_severity": {},
343
+ "by_category": {},
344
+ "recovery_success_rate": 0.0,
345
+ }
346
+
347
+ # System health monitoring
348
+ self.system_health = {
349
+ "status": "healthy",
350
+ "last_check": datetime.now(timezone.utc),
351
+ "issues": [],
352
+ "metrics": {},
353
+ }
354
+
355
+ # Initialize recovery actions
356
+ self._initialize_recovery_actions()
357
+
358
+ # Phase 3: Advanced recovery system initialization
359
+ self._initialize_phase3_components()
360
+
361
+ # Background monitoring thread
362
+ self.monitoring_active = True
363
+ self.monitor_thread = threading.Thread(target=self._background_monitoring, daemon=True)
364
+ self.monitor_thread.start()
365
+
366
+ logger.info("Error Recovery System initialized with Phase 3 enterprise features")
367
+
368
+ def handle_error(
369
+ self,
370
+ error: Exception,
371
+ context: Dict[str, Any] = None,
372
+ severity: ErrorSeverity = ErrorSeverity.MEDIUM,
373
+ category: ErrorCategory = ErrorCategory.SYSTEM,
374
+ ) -> ErrorReport:
375
+ """
376
+ Handle an error with comprehensive logging and recovery
377
+
378
+ Args:
379
+ error: Exception that occurred
380
+ context: Additional context information
381
+ severity: Error severity level
382
+ category: Error category
383
+
384
+ Returns:
385
+ ErrorReport with handling details
386
+ """
387
+ error_id = self._generate_error_id()
388
+ timestamp = datetime.now(timezone.utc)
389
+
390
+ # Create error report
391
+ error_report = ErrorReport(
392
+ id=error_id,
393
+ timestamp=timestamp,
394
+ severity=severity,
395
+ category=category,
396
+ message=str(error),
397
+ details={
398
+ "exception_type": type(error).__name__,
399
+ "exception_module": type(error).__module__,
400
+ "error_code": getattr(error, "code", None),
401
+ },
402
+ stack_trace=traceback.format_exc(),
403
+ context=context or {},
404
+ recovery_attempted=False,
405
+ recovery_successful=False,
406
+ )
407
+
408
+ # Log error
409
+ self._log_error(error_report)
410
+
411
+ # Update statistics
412
+ self._update_error_stats(error_report)
413
+
414
+ # Store error
415
+ self.active_errors[error_id] = error_report
416
+ self.error_history.append(error_report)
417
+
418
+ # Attempt automatic recovery
419
+ if severity in [ErrorSeverity.CRITICAL, ErrorSeverity.HIGH]:
420
+ recovery_result = self._attempt_automatic_recovery(error_report)
421
+ error_report.recovery_attempted = True
422
+ error_report.recovery_successful = recovery_result.success
423
+ error_report.resolution_message = recovery_result.message
424
+
425
+ if recovery_result.success:
426
+ logger.info(f"Automatic recovery successful for error {error_id}")
427
+ self.active_errors.pop(error_id, None)
428
+ else:
429
+ logger.warning(f"Automatic recovery failed for error {error_id}: {recovery_result.message}")
430
+
431
+ # Update system health
432
+ self._update_system_health()
433
+
434
+ return error_report
435
+
436
+ def register_recovery_action(self, action: RecoveryAction):
437
+ """
438
+ Register a new recovery action
439
+
440
+ Args:
441
+ action: RecoveryAction definition
442
+ """
443
+ self.recovery_actions[action.name] = action
444
+ logger.info(f"Registered recovery action: {action.name}")
445
+
446
+ def attempt_manual_recovery(
447
+ self, error_id: str, action_name: str, parameters: Dict[str, Any] = None
448
+ ) -> RecoveryResult:
449
+ """
450
+ Attempt manual recovery for a specific error
451
+
452
+ Args:
453
+ error_id: ID of error to recover
454
+ action_name: Name of recovery action to attempt
455
+ parameters: Additional parameters for recovery
456
+
457
+ Returns:
458
+ RecoveryResult with operation details
459
+ """
460
+ if error_id not in self.active_errors:
461
+ return RecoveryResult(
462
+ success=False,
463
+ action_name=action_name,
464
+ message=f"Error {error_id} not found in active errors",
465
+ duration=0.0,
466
+ )
467
+
468
+ if action_name not in self.recovery_actions:
469
+ return RecoveryResult(
470
+ success=False,
471
+ action_name=action_name,
472
+ message=f"Recovery action {action_name} not found",
473
+ duration=0.0,
474
+ )
475
+
476
+ error_report = self.active_errors[error_id]
477
+ recovery_action = self.recovery_actions[action_name]
478
+
479
+ logger.info(f"Attempting manual recovery {action_name} for error {error_id}")
480
+
481
+ try:
482
+ start_time = time.time()
483
+
484
+ # Execute recovery action
485
+ result = recovery_action.handler(error_report, parameters or {})
486
+
487
+ duration = time.time() - start_time
488
+
489
+ if result:
490
+ recovery_result = RecoveryResult(
491
+ success=True,
492
+ action_name=action_name,
493
+ message="Manual recovery completed successfully",
494
+ duration=duration,
495
+ details={"result": result},
496
+ )
497
+
498
+ # Update error report
499
+ error_report.recovery_successful = True
500
+ error_report.resolution_message = recovery_result.message
501
+
502
+ # Remove from active errors
503
+ self.active_errors.pop(error_id, None)
504
+
505
+ else:
506
+ recovery_result = RecoveryResult(
507
+ success=False,
508
+ action_name=action_name,
509
+ message="Manual recovery returned unsuccessful result",
510
+ duration=duration,
511
+ )
512
+
513
+ except Exception as e:
514
+ duration = time.time() - start_time
515
+ recovery_result = RecoveryResult(
516
+ success=False,
517
+ action_name=action_name,
518
+ message=f"Manual recovery failed: {str(e)}",
519
+ duration=duration,
520
+ details={"exception": str(e)},
521
+ )
522
+
523
+ return recovery_result
524
+
525
+ def get_system_health(self) -> Dict[str, Any]:
526
+ """
527
+ Get current system health status
528
+
529
+ Returns:
530
+ System health information
531
+ """
532
+ self._update_system_health()
533
+
534
+ last_check: datetime = self.system_health["last_check"] # type: ignore[assignment]
535
+ error_stats: Dict[str, Any] = self.error_stats # type: ignore[assignment]
536
+ issues: List[str] = self.system_health["issues"] # type: ignore[assignment]
537
+ metrics: Dict[str, Any] = self.system_health["metrics"] # type: ignore[assignment]
538
+
539
+ return {
540
+ "status": self.system_health["status"],
541
+ "last_check": last_check.isoformat(),
542
+ "active_errors": len(self.active_errors),
543
+ "total_errors": len(self.error_history),
544
+ "error_stats": error_stats.copy(),
545
+ "issues": issues.copy(),
546
+ "metrics": metrics.copy(),
547
+ "recovery_actions_available": len(self.recovery_actions),
548
+ }
549
+
550
+ def get_error_summary(self, limit: int = 50) -> Dict[str, Any]:
551
+ """
552
+ Get summary of recent errors
553
+
554
+ Args:
555
+ limit: Maximum number of errors to include
556
+
557
+ Returns:
558
+ Error summary information
559
+ """
560
+ recent_errors = self.error_history[-limit:]
561
+
562
+ # Categorize errors
563
+ by_severity: Dict[str, List[str]] = {}
564
+ by_category: Dict[str, List[str]] = {}
565
+
566
+ for error in recent_errors:
567
+ # By severity
568
+ severity = error.severity.value
569
+ if severity not in by_severity:
570
+ by_severity[severity] = []
571
+ by_severity[severity].append(error.id)
572
+
573
+ # By category
574
+ category = error.category.value
575
+ if category not in by_category:
576
+ by_category[category] = []
577
+ by_category[category].append(error.id)
578
+
579
+ # Common error patterns
580
+ error_patterns = self._identify_error_patterns(recent_errors)
581
+
582
+ return {
583
+ "total_recent_errors": len(recent_errors),
584
+ "active_errors": len(self.active_errors),
585
+ "by_severity": {k: len(v) for k, v in by_severity.items()},
586
+ "by_category": {k: len(v) for k, v in by_category.items()},
587
+ "common_patterns": error_patterns,
588
+ "recovery_rate": self._calculate_recovery_rate(recent_errors),
589
+ "recent_errors": [
590
+ {
591
+ "id": error.id,
592
+ "timestamp": error.timestamp.isoformat(),
593
+ "severity": error.severity.value,
594
+ "category": error.category.value,
595
+ "message": error.message,
596
+ "recovered": error.recovery_successful,
597
+ }
598
+ for error in recent_errors[-10:] # Last 10 errors
599
+ ],
600
+ }
601
+
602
+ def generate_troubleshooting_guide(self) -> Dict[str, Any]:
603
+ """
604
+ Generate troubleshooting guide based on error history
605
+
606
+ Returns:
607
+ Troubleshooting guide with solutions
608
+ """
609
+ common_issues: List[Dict[str, Any]] = []
610
+ recovery_procedures: Dict[str, Dict[str, Any]] = {}
611
+ prevention_tips: List[str] = []
612
+ emergency_procedures: List[Dict[str, str]] = []
613
+
614
+ guide = {
615
+ "generated_at": datetime.now(timezone.utc).isoformat(),
616
+ "common_issues": common_issues,
617
+ "recovery_procedures": recovery_procedures,
618
+ "prevention_tips": prevention_tips,
619
+ "emergency_procedures": emergency_procedures,
620
+ }
621
+
622
+ # Analyze common issues
623
+ error_patterns = self._identify_error_patterns(self.error_history)
624
+ for pattern, frequency in error_patterns.items():
625
+ if frequency > 2: # Issues that occurred more than twice
626
+ common_issues.append(
627
+ {
628
+ "pattern": pattern,
629
+ "frequency": frequency,
630
+ "severity": self._get_pattern_severity(pattern),
631
+ "solutions": self._get_solutions_for_pattern(pattern),
632
+ }
633
+ )
634
+
635
+ # Generate recovery procedures
636
+ for action_name, action in self.recovery_actions.items():
637
+ recovery_procedures[action_name] = {
638
+ "description": action.description,
639
+ "type": action.action_type,
640
+ "for_severities": [s.value for s in action.severity_filter],
641
+ "for_categories": [c.value for c in action.category_filter],
642
+ }
643
+
644
+ # Prevention tips
645
+ prevention_tips.extend(self._generate_prevention_tips())
646
+
647
+ # Emergency procedures
648
+ emergency_procedures.extend(self._generate_emergency_procedures())
649
+
650
+ return guide
651
+
652
+ def cleanup_old_errors(self, days_to_keep: int = 30) -> Dict[str, Any]:
653
+ """
654
+ Clean up old error records
655
+
656
+ Args:
657
+ days_to_keep: Number of days to keep error records
658
+
659
+ Returns:
660
+ Cleanup operation results
661
+ """
662
+ cutoff_date = datetime.now(timezone.utc) - timedelta(days=days_to_keep)
663
+
664
+ old_errors = [e for e in self.error_history if e.timestamp < cutoff_date]
665
+ removed_count = len(old_errors)
666
+
667
+ # Keep only recent errors
668
+ self.error_history = [e for e in self.error_history if e.timestamp >= cutoff_date]
669
+
670
+ # Save updated error history
671
+ self._save_error_history()
672
+
673
+ logger.info(f"Cleaned up {removed_count} old error records")
674
+
675
+ return {
676
+ "removed_count": removed_count,
677
+ "remaining_count": len(self.error_history),
678
+ "cutoff_date": cutoff_date.isoformat(),
679
+ }
680
+
681
+ def _initialize_recovery_actions(self):
682
+ """Initialize default recovery actions"""
683
+ # System recovery actions
684
+ self.register_recovery_action(
685
+ RecoveryAction(
686
+ name="restart_research_engines",
687
+ description="Restart research engines and clear caches",
688
+ action_type="automatic",
689
+ severity_filter=[ErrorSeverity.HIGH, ErrorSeverity.CRITICAL],
690
+ category_filter=[ErrorCategory.RESEARCH, ErrorCategory.SYSTEM],
691
+ handler=self._restart_research_engines,
692
+ timeout=30.0,
693
+ )
694
+ )
695
+
696
+ self.register_recovery_action(
697
+ RecoveryAction(
698
+ name="restore_config_backup",
699
+ description="Restore configuration from last known good backup",
700
+ action_type="automatic",
701
+ severity_filter=[ErrorSeverity.CRITICAL],
702
+ category_filter=[ErrorCategory.CONFIGURATION],
703
+ handler=self._restore_config_backup,
704
+ timeout=15.0,
705
+ )
706
+ )
707
+
708
+ self.register_recovery_action(
709
+ RecoveryAction(
710
+ name="clear_agent_cache",
711
+ description="Clear agent communication cache and reset connections",
712
+ action_type="automatic",
713
+ severity_filter=[ErrorSeverity.MEDIUM, ErrorSeverity.HIGH],
714
+ category_filter=[ErrorCategory.COMMUNICATION],
715
+ handler=self._clear_agent_cache,
716
+ timeout=10.0,
717
+ )
718
+ )
719
+
720
+ self.register_recovery_action(
721
+ RecoveryAction(
722
+ name="validate_research_integrity",
723
+ description="Validate research component integrity and repair if needed",
724
+ action_type="assisted",
725
+ severity_filter=[ErrorSeverity.HIGH],
726
+ category_filter=[ErrorCategory.RESEARCH, ErrorCategory.VALIDATION],
727
+ handler=self._validate_research_integrity,
728
+ timeout=60.0,
729
+ )
730
+ )
731
+
732
+ self.register_recovery_action(
733
+ RecoveryAction(
734
+ name="rollback_last_changes",
735
+ description="Rollback last research integration changes",
736
+ action_type="manual",
737
+ severity_filter=[ErrorSeverity.CRITICAL],
738
+ category_filter=[ErrorCategory.INTEGRATION, ErrorCategory.RESEARCH],
739
+ handler=self._rollback_last_changes,
740
+ timeout=45.0,
741
+ )
742
+ )
743
+
744
+ self.register_recovery_action(
745
+ RecoveryAction(
746
+ name="reset_system_state",
747
+ description="Reset system to known good state",
748
+ action_type="manual",
749
+ severity_filter=[ErrorSeverity.CRITICAL],
750
+ category_filter=[ErrorCategory.SYSTEM],
751
+ handler=self._reset_system_state,
752
+ timeout=120.0,
753
+ )
754
+ )
755
+
756
+ # Performance recovery actions
757
+ self.register_recovery_action(
758
+ RecoveryAction(
759
+ name="optimize_performance",
760
+ description="Optimize system performance and clear bottlenecks",
761
+ action_type="automatic",
762
+ severity_filter=[ErrorSeverity.MEDIUM],
763
+ category_filter=[ErrorCategory.PERFORMANCE],
764
+ handler=self._optimize_performance,
765
+ timeout=30.0,
766
+ )
767
+ )
768
+
769
+ # Resource recovery actions
770
+ self.register_recovery_action(
771
+ RecoveryAction(
772
+ name="free_resources",
773
+ description="Free up system resources and memory",
774
+ action_type="automatic",
775
+ severity_filter=[ErrorSeverity.MEDIUM, ErrorSeverity.HIGH],
776
+ category_filter=[ErrorCategory.RESOURCE],
777
+ handler=self._free_resources,
778
+ timeout=20.0,
779
+ )
780
+ )
781
+
782
+ def _attempt_automatic_recovery(self, error_report: ErrorReport) -> RecoveryResult:
783
+ """Attempt automatic recovery for an error"""
784
+ suitable_actions = []
785
+
786
+ # Find suitable recovery actions
787
+ for action_name, action in self.recovery_actions.items():
788
+ if (
789
+ action.action_type == "automatic"
790
+ and error_report.severity in action.severity_filter
791
+ and error_report.category in action.category_filter
792
+ ):
793
+ suitable_actions.append(action)
794
+
795
+ # Try actions in order of priority
796
+ for action in suitable_actions:
797
+ try:
798
+ logger.info(f"Attempting automatic recovery: {action.name}")
799
+
800
+ start_time = time.time()
801
+ result = action.handler(error_report, {})
802
+ duration = time.time() - start_time
803
+
804
+ if result:
805
+ return RecoveryResult(
806
+ success=True,
807
+ action_name=action.name,
808
+ message=f"Automatic recovery successful: {action.name}",
809
+ duration=duration,
810
+ details={"result": result},
811
+ )
812
+
813
+ except Exception as e:
814
+ logger.warning(f"Recovery action {action.name} failed: {str(e)}")
815
+ continue
816
+
817
+ return RecoveryResult(
818
+ success=False,
819
+ action_name="none",
820
+ message="No suitable automatic recovery action succeeded",
821
+ duration=0.0,
822
+ )
823
+
824
+ def _restart_research_engines(self, error_report: ErrorReport, parameters: Dict[str, Any]) -> bool:
825
+ """Restart research engines and clear caches"""
826
+ try:
827
+ logger.info("Restarting research engines...")
828
+
829
+ # Clear research engine caches
830
+ cache_dirs = [
831
+ self.project_root / ".moai" / "cache",
832
+ self.project_root / ".claude" / "cache",
833
+ ]
834
+
835
+ for cache_dir in cache_dirs:
836
+ if cache_dir.exists():
837
+ import shutil
838
+
839
+ shutil.rmtree(cache_dir)
840
+ cache_dir.mkdir(parents=True, exist_ok=True)
841
+
842
+ # Reset research engine state
843
+ research_state_file = self.project_root / ".moai" / "research_state.json"
844
+ if research_state_file.exists():
845
+ research_state_file.unlink()
846
+
847
+ # Reinitialize research components
848
+ self._reinitialize_research_components()
849
+
850
+ logger.info("Research engines restarted successfully")
851
+ return True
852
+
853
+ except Exception as e:
854
+ logger.error(f"Failed to restart research engines: {str(e)}")
855
+ return False
856
+
857
+ def _restore_config_backup(self, error_report: ErrorReport, parameters: Dict[str, Any]) -> bool:
858
+ """Restore configuration from backup.
859
+
860
+ Supports both YAML and JSON configuration formats with backward
861
+ compatibility for legacy JSON-only backups.
862
+ """
863
+ try:
864
+ logger.info("Restoring configuration from backup...")
865
+
866
+ backup_dir = self.project_root / ".moai" / "config_backups"
867
+ if not backup_dir.exists():
868
+ logger.warning("No configuration backup directory found")
869
+ return False
870
+
871
+ # Find most recent backup - check both YAML and JSON formats
872
+ yaml_backups = list(backup_dir.glob("config_*.yaml"))
873
+ json_backups = list(backup_dir.glob("config_*.json"))
874
+ backup_files = yaml_backups + json_backups
875
+
876
+ if not backup_files:
877
+ logger.warning("No configuration backups found")
878
+ return False
879
+
880
+ latest_backup = max(backup_files, key=lambda f: f.stat().st_mtime)
881
+ is_yaml_backup = latest_backup.suffix in (".yaml", ".yml")
882
+
883
+ # Determine target config file based on backup format
884
+ if is_yaml_backup:
885
+ config_file = self.project_root / ".moai" / "config" / "config.yaml"
886
+ else:
887
+ # Legacy JSON backup - check if project uses YAML now
888
+ yaml_config = self.project_root / ".moai" / "config" / "config.yaml"
889
+ if yaml_config.exists():
890
+ config_file = yaml_config
891
+ else:
892
+ config_file = self.project_root / ".moai" / "config" / "config.json"
893
+
894
+ # Restore configuration
895
+ import shutil
896
+
897
+ shutil.copy2(latest_backup, config_file)
898
+
899
+ logger.info(f"Configuration restored from {latest_backup}")
900
+ return True
901
+
902
+ except Exception as e:
903
+ logger.error(f"Failed to restore configuration: {str(e)}")
904
+ return False
905
+
906
+ def _clear_agent_cache(self, error_report: ErrorReport, parameters: Dict[str, Any]) -> bool:
907
+ """Clear agent communication cache"""
908
+ try:
909
+ logger.info("Clearing agent cache...")
910
+
911
+ # Clear agent state files
912
+ agent_state_dir = self.project_root / ".moai" / "agent_state"
913
+ if agent_state_dir.exists():
914
+ import shutil
915
+
916
+ shutil.rmtree(agent_state_dir)
917
+ agent_state_dir.mkdir(parents=True, exist_ok=True)
918
+
919
+ # Reset communication channels
920
+ comm_cache_dir = self.project_root / ".moai" / "comm_cache"
921
+ if comm_cache_dir.exists():
922
+ import shutil
923
+
924
+ shutil.rmtree(comm_cache_dir)
925
+ comm_cache_dir.mkdir(parents=True, exist_ok=True)
926
+
927
+ logger.info("Agent cache cleared successfully")
928
+ return True
929
+
930
+ except Exception as e:
931
+ logger.error(f"Failed to clear agent cache: {str(e)}")
932
+ return False
933
+
934
+ def _validate_research_integrity(self, error_report: ErrorReport, parameters: Dict[str, Any]) -> Dict[str, Any]:
935
+ """Validate research component integrity"""
936
+ issues_found: List[str] = []
937
+ repairs_made: List[str] = []
938
+
939
+ validation_results = {
940
+ "skills_valid": True,
941
+ "agents_valid": True,
942
+ "commands_valid": True,
943
+ "hooks_valid": True,
944
+ "issues_found": issues_found,
945
+ "repairs_made": repairs_made,
946
+ }
947
+
948
+ try:
949
+ logger.info("Validating research integrity...")
950
+
951
+ # Validate skills
952
+ skills_dir = self.project_root / ".claude" / "skills"
953
+ if skills_dir.exists():
954
+ for skill_file in skills_dir.glob("*.md"):
955
+ if not self._validate_skill_file(skill_file):
956
+ validation_results["skills_valid"] = False
957
+ issues_found.append(f"Invalid skill file: {skill_file}")
958
+
959
+ # Attempt repair
960
+ if self._repair_skill_file(skill_file):
961
+ repairs_made.append(f"Repaired: {skill_file}")
962
+
963
+ # Validate agents
964
+ agents_dir = self.project_root / ".claude" / "agents" / "alfred"
965
+ if agents_dir.exists():
966
+ for agent_file in agents_dir.glob("*.md"):
967
+ if not self._validate_agent_file(agent_file):
968
+ validation_results["agents_valid"] = False
969
+ issues_found.append(f"Invalid agent file: {agent_file}")
970
+
971
+ # Validate commands
972
+ commands_dir = self.project_root / ".claude" / "commands" / "alfred"
973
+ if commands_dir.exists():
974
+ for command_file in commands_dir.glob("*.md"):
975
+ if not self._validate_command_file(command_file):
976
+ validation_results["commands_valid"] = False
977
+ issues_found.append(f"Invalid command file: {command_file}")
978
+
979
+ logger.info(
980
+ f"Research integrity validation completed. Issues: {len(issues_found)}, Repairs: {len(repairs_made)}"
981
+ )
982
+
983
+ except Exception as e:
984
+ logger.error(f"Research integrity validation failed: {str(e)}")
985
+ validation_results["validation_error"] = str(e)
986
+
987
+ return validation_results
988
+
989
+ def _rollback_last_changes(self, error_report: ErrorReport, parameters: Dict[str, Any]) -> bool:
990
+ """Rollback last research integration changes"""
991
+ try:
992
+ logger.info("Rolling back last research changes...")
993
+
994
+ # Import rollback manager
995
+ sys.path.insert(0, str(self.project_root / "src"))
996
+ from moai_adk.core.rollback_manager import RollbackManager
997
+
998
+ rollback_manager = RollbackManager(self.project_root)
999
+
1000
+ # Find latest rollback point for research integration
1001
+ rollback_points = rollback_manager.list_rollback_points(limit=5)
1002
+ if not rollback_points:
1003
+ logger.warning("No rollback points available")
1004
+ return False
1005
+
1006
+ # Use the most recent rollback point
1007
+ latest_rollback = rollback_points[0]
1008
+ result = rollback_manager.rollback_to_point(latest_rollback["id"])
1009
+
1010
+ if result.success:
1011
+ logger.info(f"Successfully rolled back to {latest_rollback['id']}")
1012
+ return True
1013
+ else:
1014
+ logger.error(f"Rollback failed: {result.message}")
1015
+ return False
1016
+
1017
+ except Exception as e:
1018
+ logger.error(f"Rollback operation failed: {str(e)}")
1019
+ return False
1020
+
1021
+ def _reset_system_state(self, error_report: ErrorReport, parameters: Dict[str, Any]) -> bool:
1022
+ """Reset system to known good state"""
1023
+ try:
1024
+ logger.info("Resetting system to known good state...")
1025
+
1026
+ # Clear all caches
1027
+ cache_dirs = [
1028
+ self.project_root / ".moai" / "cache",
1029
+ self.project_root / ".claude" / "cache",
1030
+ self.project_root / ".moai" / "agent_state",
1031
+ self.project_root / ".moai" / "comm_cache",
1032
+ ]
1033
+
1034
+ for cache_dir in cache_dirs:
1035
+ if cache_dir.exists():
1036
+ import shutil
1037
+
1038
+ shutil.rmtree(cache_dir)
1039
+ cache_dir.mkdir(parents=True, exist_ok=True)
1040
+
1041
+ # Reset error state
1042
+ self.active_errors.clear()
1043
+
1044
+ # Reinitialize core components
1045
+ self._reinitialize_core_components()
1046
+
1047
+ logger.info("System state reset completed")
1048
+ return True
1049
+
1050
+ except Exception as e:
1051
+ logger.error(f"System state reset failed: {str(e)}")
1052
+ return False
1053
+
1054
+ def _optimize_performance(self, error_report: ErrorReport, parameters: Dict[str, Any]) -> bool:
1055
+ """Optimize system performance"""
1056
+ try:
1057
+ logger.info("Optimizing system performance...")
1058
+
1059
+ # Clear temporary files
1060
+ temp_dirs = [
1061
+ self.project_root / ".moai" / "temp",
1062
+ self.project_root / ".claude" / "temp",
1063
+ ]
1064
+
1065
+ for temp_dir in temp_dirs:
1066
+ if temp_dir.exists():
1067
+ import shutil
1068
+
1069
+ shutil.rmtree(temp_dir)
1070
+
1071
+ # Optimize database connections if applicable
1072
+ self._optimize_connections()
1073
+
1074
+ # Clear memory caches
1075
+ import gc
1076
+
1077
+ gc.collect()
1078
+
1079
+ logger.info("Performance optimization completed")
1080
+ return True
1081
+
1082
+ except Exception as e:
1083
+ logger.error(f"Performance optimization failed: {str(e)}")
1084
+ return False
1085
+
1086
+ def _free_resources(self, error_report: ErrorReport, parameters: Dict[str, Any]) -> bool:
1087
+ """Free up system resources"""
1088
+ try:
1089
+ logger.info("Freeing up system resources...")
1090
+
1091
+ # Clear memory caches
1092
+ import gc
1093
+
1094
+ gc.collect()
1095
+
1096
+ # Close any open file handles
1097
+ self._close_file_handles()
1098
+
1099
+ # Terminate any hanging processes
1100
+ self._terminate_hanging_processes()
1101
+
1102
+ logger.info("Resource cleanup completed")
1103
+ return True
1104
+
1105
+ except Exception as e:
1106
+ logger.error(f"Resource cleanup failed: {str(e)}")
1107
+ return False
1108
+
1109
+ def _generate_error_id(self) -> str:
1110
+ """Generate unique error ID"""
1111
+ timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
1112
+ random_suffix = hashlib.md5(os.urandom(4), usedforsecurity=False).hexdigest()[:6]
1113
+ return f"ERR_{timestamp}_{random_suffix}"
1114
+
1115
+ def _log_error(self, error_report: ErrorReport):
1116
+ """Log error to file and system"""
1117
+ # Log to file
1118
+ error_file = self.error_log_dir / f"error_{error_report.id}.json"
1119
+ try:
1120
+ with open(error_file, "w", encoding="utf-8") as f:
1121
+ json.dump(asdict(error_report), f, indent=2, default=str, ensure_ascii=False)
1122
+ except Exception as e:
1123
+ logger.error(f"Failed to log error to file: {str(e)}")
1124
+
1125
+ # Log to system
1126
+ log_level = {
1127
+ ErrorSeverity.CRITICAL: logging.CRITICAL,
1128
+ ErrorSeverity.HIGH: logging.ERROR,
1129
+ ErrorSeverity.MEDIUM: logging.WARNING,
1130
+ ErrorSeverity.LOW: logging.INFO,
1131
+ ErrorSeverity.INFO: logging.INFO,
1132
+ }.get(error_report.severity, logging.WARNING)
1133
+
1134
+ logger.log(log_level, f"Error {error_report.id}: {error_report.message}")
1135
+
1136
+ def _update_error_stats(self, error_report: ErrorReport):
1137
+ """Update error statistics"""
1138
+ self.error_stats["total_errors"] += 1
1139
+
1140
+ # By severity
1141
+ severity = error_report.severity.value
1142
+ if severity not in self.error_stats["by_severity"]:
1143
+ self.error_stats["by_severity"][severity] = 0
1144
+ self.error_stats["by_severity"][severity] += 1
1145
+
1146
+ # By category
1147
+ category = error_report.category.value
1148
+ if category not in self.error_stats["by_category"]:
1149
+ self.error_stats["by_category"][category] = 0
1150
+ self.error_stats["by_category"][category] += 1
1151
+
1152
+ def _update_system_health(self):
1153
+ """Update system health status"""
1154
+ current_time = datetime.now(timezone.utc)
1155
+
1156
+ # Determine system status
1157
+ critical_errors = [e for e in self.active_errors.values() if e.severity == ErrorSeverity.CRITICAL]
1158
+ high_errors = [e for e in self.active_errors.values() if e.severity == ErrorSeverity.HIGH]
1159
+
1160
+ if critical_errors:
1161
+ self.system_health["status"] = "critical"
1162
+ elif high_errors:
1163
+ self.system_health["status"] = "degraded"
1164
+ elif len(self.active_errors) > 5:
1165
+ self.system_health["status"] = "warning"
1166
+ else:
1167
+ self.system_health["status"] = "healthy"
1168
+
1169
+ # Update metrics
1170
+ self.system_health["last_check"] = current_time
1171
+ self.system_health["metrics"] = {
1172
+ "active_errors": len(self.active_errors),
1173
+ "total_errors": len(self.error_history),
1174
+ "recovery_success_rate": self._calculate_recovery_rate(self.error_history),
1175
+ }
1176
+
1177
+ # Identify issues
1178
+ self.system_health["issues"] = [
1179
+ {
1180
+ "type": "active_errors",
1181
+ "count": len(self.active_errors),
1182
+ "severity_distribution": {
1183
+ severity: len([e for e in self.active_errors.values() if e.severity.value == severity])
1184
+ for severity in set(e.severity.value for e in self.active_errors.values())
1185
+ },
1186
+ }
1187
+ ]
1188
+
1189
+ def _background_monitoring(self):
1190
+ """Background monitoring thread"""
1191
+ while self.monitoring_active:
1192
+ try:
1193
+ # Check system health every 30 seconds
1194
+ time.sleep(30)
1195
+ self._update_system_health()
1196
+
1197
+ # Check for error patterns that need attention
1198
+ self._check_error_patterns()
1199
+
1200
+ except Exception as e:
1201
+ logger.error(f"Background monitoring error: {str(e)}")
1202
+
1203
+ def _check_error_patterns(self):
1204
+ """Check for concerning error patterns"""
1205
+ recent_errors = [
1206
+ e for e in self.error_history if (datetime.now(timezone.utc) - e.timestamp).total_seconds() < 300
1207
+ ] # Last 5 minutes
1208
+
1209
+ # Check for error bursts
1210
+ if len(recent_errors) > 10:
1211
+ logger.warning(f"High error rate detected: {len(recent_errors)} errors in last 5 minutes")
1212
+
1213
+ # Check for repeated errors
1214
+ error_messages = [e.message for e in recent_errors]
1215
+ message_counts: Dict[str, int] = {}
1216
+ for msg in error_messages:
1217
+ message_counts[msg] = message_counts.get(msg, 0) + 1
1218
+
1219
+ repeated_errors = [msg for msg, count in message_counts.items() if count > 3]
1220
+ if repeated_errors:
1221
+ logger.warning(f"Repeated errors detected: {repeated_errors}")
1222
+
1223
+ def _calculate_recovery_rate(self, errors: List[ErrorReport]) -> float:
1224
+ """Calculate recovery success rate"""
1225
+ if not errors:
1226
+ return 0.0
1227
+
1228
+ recovered_errors = [e for e in errors if e.recovery_successful]
1229
+ return len(recovered_errors) / len(errors)
1230
+
1231
+ def _identify_error_patterns(self, errors: List[ErrorReport]) -> Dict[str, int]:
1232
+ """Identify common error patterns"""
1233
+ patterns: Dict[str, int] = {}
1234
+
1235
+ for error in errors:
1236
+ # Pattern by exception type
1237
+ pattern = f"{error.category.value}:{error.details.get('exception_type', 'unknown')}"
1238
+ patterns[pattern] = patterns.get(pattern, 0) + 1
1239
+
1240
+ return patterns
1241
+
1242
+ def _get_pattern_severity(self, pattern: str) -> str:
1243
+ """Get typical severity for an error pattern"""
1244
+ severity_map = {
1245
+ "research:Exception": "high",
1246
+ "system:Exception": "critical",
1247
+ "configuration:Exception": "high",
1248
+ "communication:Exception": "medium",
1249
+ "validation:Exception": "medium",
1250
+ }
1251
+
1252
+ for key, severity in severity_map.items():
1253
+ if key in pattern:
1254
+ return severity
1255
+
1256
+ return "medium"
1257
+
1258
+ def _get_solutions_for_pattern(self, pattern: str) -> List[str]:
1259
+ """Get common solutions for error pattern"""
1260
+ solutions = {
1261
+ "research:Exception": [
1262
+ "Restart research engines",
1263
+ "Clear research cache",
1264
+ "Validate research components",
1265
+ ],
1266
+ "system:Exception": [
1267
+ "Check system resources",
1268
+ "Restart system components",
1269
+ "Verify system configuration",
1270
+ ],
1271
+ "configuration:Exception": [
1272
+ "Restore configuration backup",
1273
+ "Validate configuration syntax",
1274
+ "Check configuration permissions",
1275
+ ],
1276
+ }
1277
+
1278
+ for key, sols in solutions.items():
1279
+ if key in pattern:
1280
+ return sols
1281
+
1282
+ return ["Contact system administrator", "Check system logs"]
1283
+
1284
+ def _generate_prevention_tips(self) -> List[str]:
1285
+ """Generate prevention tips based on error history"""
1286
+ tips = []
1287
+
1288
+ # Add tips based on common error categories
1289
+ category_counts: Dict[str, int] = {}
1290
+ for error in self.error_history:
1291
+ category = error.category.value
1292
+ category_counts[category] = category_counts.get(category, 0) + 1
1293
+
1294
+ if category_counts.get("configuration", 0) > 5:
1295
+ tips.append("Regularly validate configuration files before making changes")
1296
+
1297
+ if category_counts.get("research", 0) > 5:
1298
+ tips.append("Monitor research engine performance and clear caches regularly")
1299
+
1300
+ if category_counts.get("communication", 0) > 5:
1301
+ tips.append("Ensure stable network connections for agent communication")
1302
+
1303
+ return tips
1304
+
1305
+ def _generate_emergency_procedures(self) -> List[Dict[str, str]]:
1306
+ """Generate emergency recovery procedures"""
1307
+ return [
1308
+ {
1309
+ "condition": "System completely unresponsive",
1310
+ "procedure": "Use system_reset recovery action to restore to known good state",
1311
+ },
1312
+ {
1313
+ "condition": "Critical research engine failure",
1314
+ "procedure": "Rollback last research changes using rollback_last_changes action",
1315
+ },
1316
+ {
1317
+ "condition": "Configuration corruption",
1318
+ "procedure": "Restore configuration from backup using restore_config_backup action",
1319
+ },
1320
+ {
1321
+ "condition": "Multiple agent communication failures",
1322
+ "procedure": "Clear agent cache and restart communication channels",
1323
+ },
1324
+ ]
1325
+
1326
+ # Helper methods for component validation and repair
1327
+ def _validate_skill_file(self, skill_file: Path) -> bool:
1328
+ """Validate skill file format"""
1329
+ try:
1330
+ with open(skill_file, "r", encoding="utf-8") as f:
1331
+ content = f.read()
1332
+
1333
+ # Basic validation
1334
+ return "---" in content and len(content) > 100
1335
+ except (OSError, UnicodeDecodeError):
1336
+ return False
1337
+
1338
+ def _validate_agent_file(self, agent_file: Path) -> bool:
1339
+ """Validate agent file format"""
1340
+ try:
1341
+ with open(agent_file, "r", encoding="utf-8") as f:
1342
+ content = f.read()
1343
+
1344
+ return "role:" in content and len(content) > 200
1345
+ except (OSError, UnicodeDecodeError):
1346
+ return False
1347
+
1348
+ def _validate_command_file(self, command_file: Path) -> bool:
1349
+ """Validate command file format"""
1350
+ try:
1351
+ with open(command_file, "r", encoding="utf-8") as f:
1352
+ content = f.read()
1353
+
1354
+ return "name:" in content and "allowed-tools:" in content
1355
+ except (OSError, UnicodeDecodeError):
1356
+ return False
1357
+
1358
+ def _repair_skill_file(self, skill_file: Path) -> bool:
1359
+ """Attempt to repair skill file"""
1360
+ try:
1361
+ # Basic repair - ensure file has minimum required content
1362
+ with open(skill_file, "r", encoding="utf-8") as f:
1363
+ content = f.read()
1364
+
1365
+ if not content.startswith("---"):
1366
+ content = f"---\nname: {skill_file.stem}\ndescription: Repaired skill file\n---\n\n{content}"
1367
+
1368
+ with open(skill_file, "w", encoding="utf-8") as f:
1369
+ f.write(content)
1370
+
1371
+ return True
1372
+ except (OSError, UnicodeDecodeError):
1373
+ return False
1374
+
1375
+ def _reinitialize_research_components(self):
1376
+ """Reinitialize research components"""
1377
+ # Implementation would depend on specific research components
1378
+ pass
1379
+
1380
+ def _reinitialize_core_components(self):
1381
+ """Reinitialize core system components"""
1382
+ # Implementation would depend on specific core components
1383
+ pass
1384
+
1385
+ def _optimize_connections(self):
1386
+ """Optimize database/network connections"""
1387
+ # Implementation would depend on specific connection types
1388
+ pass
1389
+
1390
+ def _close_file_handles(self):
1391
+ """Close open file handles"""
1392
+ import gc
1393
+
1394
+ gc.collect() # Force garbage collection to close file handles
1395
+
1396
+ def _terminate_hanging_processes(self):
1397
+ """Terminate hanging processes"""
1398
+ # Implementation would identify and terminate hanging processes
1399
+ pass
1400
+
1401
+ def _save_error_history(self):
1402
+ """Save error history to file"""
1403
+ history_file = self.error_log_dir / "error_history.json"
1404
+ try:
1405
+ with open(history_file, "w") as f:
1406
+ json.dump([asdict(e) for e in self.error_history], f, indent=2, default=str)
1407
+ except Exception as e:
1408
+ logger.error(f"Failed to save error history: {str(e)}")
1409
+
1410
+ # Phase 3: Advanced Error Recovery Methods
1411
+
1412
+ def _initialize_phase3_components(self):
1413
+ """Initialize Phase 3 advanced recovery components"""
1414
+ # Phase 3 specific attributes
1415
+ self.advanced_failures: Dict[str, FailureEvent] = {}
1416
+ self.advanced_recovery_actions: Dict[str, AdvancedRecoveryAction] = {}
1417
+ self.system_snapshots: Dict[str, SystemSnapshot] = {}
1418
+ self.dead_letter_queue: deque = deque(maxlen=10000)
1419
+
1420
+ # Advanced recovery statistics
1421
+ self.advanced_recovery_stats = {
1422
+ "total_failures": 0,
1423
+ "auto_recoveries_attempted": 0,
1424
+ "auto_recoveries_successful": 0,
1425
+ "cascade_failures_detected": 0,
1426
+ "rollbacks_performed": 0,
1427
+ "snapshots_created": 0,
1428
+ "dead_letter_messages": 0,
1429
+ }
1430
+
1431
+ # Circuit breaker states for components
1432
+ self.circuit_breaker_states: Dict[str, Dict[str, Any]] = defaultdict(
1433
+ lambda: {
1434
+ "state": "CLOSED",
1435
+ "failure_count": 0,
1436
+ "last_failure_time": None,
1437
+ "success_threshold": 5,
1438
+ "failure_threshold": 3,
1439
+ "timeout_seconds": 60,
1440
+ }
1441
+ )
1442
+
1443
+ # Failure mode analyzers
1444
+ self.failure_analyzers = {
1445
+ FailureMode.CASCADE_FAILURE: self._analyze_cascade_failure,
1446
+ FailureMode.CIRCUIT_BREAKER_TRIPPED: self._analyze_circuit_breaker_trip,
1447
+ FailureMode.RESOURCE_EXHAUSTION: self._analyze_resource_exhaustion,
1448
+ }
1449
+
1450
+ logger.info("Phase 3 advanced recovery components initialized")
1451
+
1452
+ async def report_advanced_failure(
1453
+ self,
1454
+ failure_mode: FailureMode,
1455
+ component: str,
1456
+ description: str,
1457
+ severity: str = "medium",
1458
+ context: Optional[Dict[str, Any]] = None,
1459
+ error_details: Optional[Dict[str, Any]] = None,
1460
+ affected_operations: Optional[List[str]] = None,
1461
+ auto_recovery_eligible: bool = True,
1462
+ parent_failure_id: Optional[str] = None,
1463
+ ) -> str:
1464
+ """Report an advanced failure event with enhanced tracking"""
1465
+ failure_id = str(uuid.uuid4())
1466
+
1467
+ failure = FailureEvent(
1468
+ failure_id=failure_id,
1469
+ failure_mode=failure_mode,
1470
+ timestamp=datetime.now(timezone.utc),
1471
+ component=component,
1472
+ description=description,
1473
+ severity=severity,
1474
+ context=context or {},
1475
+ error_details=error_details,
1476
+ affected_operations=affected_operations or [],
1477
+ auto_recovery_eligible=auto_recovery_eligible,
1478
+ parent_failure_id=parent_failure_id,
1479
+ )
1480
+
1481
+ # Store failure
1482
+ self.advanced_failures[failure_id] = failure
1483
+ self.advanced_recovery_stats["total_failures"] += 1
1484
+
1485
+ # Analyze failure mode
1486
+ if failure_mode in self.failure_analyzers:
1487
+ await self.failure_analyzers[failure_mode](failure)
1488
+
1489
+ # Trigger advanced recovery if eligible
1490
+ if auto_recovery_eligible:
1491
+ await self._trigger_advanced_recovery(failure)
1492
+
1493
+ # Check for cascade failures
1494
+ await self._check_cascade_failures(failure)
1495
+
1496
+ logger.warning(f"Advanced failure reported: {failure_mode.value} in {component} - {description}")
1497
+ return failure_id
1498
+
1499
+ async def _trigger_advanced_recovery(self, failure: FailureEvent):
1500
+ """Trigger advanced recovery mechanisms"""
1501
+ try:
1502
+ strategy = self._determine_advanced_recovery_strategy(failure.failure_mode)
1503
+
1504
+ action = AdvancedRecoveryAction(
1505
+ action_id=str(uuid.uuid4()),
1506
+ failure_id=failure.failure_id,
1507
+ strategy=strategy,
1508
+ timestamp=datetime.now(timezone.utc),
1509
+ description=f"Advanced recovery for {failure.failure_mode.value}",
1510
+ parameters={"failure_context": failure.context},
1511
+ priority=self._calculate_recovery_priority(failure),
1512
+ )
1513
+
1514
+ self.advanced_recovery_actions[action.action_id] = action
1515
+ self.advanced_recovery_stats["auto_recoveries_attempted"] += 1
1516
+
1517
+ # Execute recovery action
1518
+ success = await self._execute_advanced_recovery_action(action)
1519
+
1520
+ if success:
1521
+ self.advanced_recovery_stats["auto_recoveries_successful"] += 1
1522
+ logger.info(f"Advanced recovery successful for failure {failure.failure_id}")
1523
+ else:
1524
+ # Add to dead letter queue for manual intervention
1525
+ self.dead_letter_queue.append(
1526
+ {
1527
+ "failure_id": failure.failure_id,
1528
+ "action_id": action.action_id,
1529
+ "timestamp": datetime.now(timezone.utc).isoformat(),
1530
+ "reason": "Advanced recovery failed",
1531
+ }
1532
+ )
1533
+ self.advanced_recovery_stats["dead_letter_messages"] += 1
1534
+
1535
+ except Exception as e:
1536
+ logger.error(f"Error triggering advanced recovery: {e}")
1537
+
1538
+ async def _execute_advanced_recovery_action(self, action: AdvancedRecoveryAction) -> bool:
1539
+ """Execute advanced recovery action with enhanced capabilities"""
1540
+ action.status = RecoveryStatus.IN_PROGRESS
1541
+ action.execution_log.append(f"Starting advanced recovery: {action.strategy.value}")
1542
+
1543
+ try:
1544
+ # Check dependencies
1545
+ for dep_action_id in action.dependencies:
1546
+ if dep_action_id in self.advanced_recovery_actions:
1547
+ dep_action = self.advanced_recovery_actions[dep_action_id]
1548
+ if dep_action.status != RecoveryStatus.COMPLETED:
1549
+ action.execution_log.append(f"Waiting for dependency: {dep_action_id}")
1550
+ return False
1551
+
1552
+ # Execute based on strategy
1553
+ if action.strategy == RecoveryStrategy.RETRY_WITH_BACKOFF:
1554
+ success = await self._execute_retry_with_backoff(action)
1555
+ elif action.strategy == RecoveryStrategy.CIRCUIT_BREAKER:
1556
+ success = await self._execute_circuit_breaker_action(action)
1557
+ elif action.strategy == RecoveryStrategy.ROLLBACK:
1558
+ success = await self._execute_rollback_action(action)
1559
+ elif action.strategy == RecoveryStrategy.QUARANTINE:
1560
+ success = await self._execute_quarantine_action(action)
1561
+ else:
1562
+ success = await self._execute_legacy_recovery_action(action)
1563
+
1564
+ if success:
1565
+ action.status = RecoveryStatus.COMPLETED
1566
+ action.execution_log.append("Advanced recovery completed successfully")
1567
+ else:
1568
+ action.status = RecoveryStatus.FAILED
1569
+ action.execution_log.append("Advanced recovery failed")
1570
+
1571
+ return success
1572
+
1573
+ except Exception as e:
1574
+ action.status = RecoveryStatus.FAILED
1575
+ action.execution_log.append(f"Advanced recovery error: {str(e)}")
1576
+ logger.error(f"Error executing advanced recovery action {action.action_id}: {e}")
1577
+ return False
1578
+
1579
+ async def _execute_retry_with_backoff(self, action: AdvancedRecoveryAction) -> bool:
1580
+ """Execute retry with exponential backoff"""
1581
+ self.advanced_failures[action.failure_id]
1582
+ base_delay = 1.0
1583
+ max_delay = 60.0
1584
+ backoff_factor = 2.0
1585
+
1586
+ for attempt in range(action.max_retries + 1):
1587
+ try:
1588
+ action.retry_attempts = attempt
1589
+ action.execution_log.append(f"Retry attempt {attempt + 1}/{action.max_retries + 1}")
1590
+
1591
+ # Simulate retry logic - in real implementation, this would call the failing function
1592
+ if attempt >= 2: # Simulate success after a few attempts
1593
+ action.execution_log.append("Retry successful")
1594
+ return True
1595
+ else:
1596
+ action.execution_log.append("Retry failed, will retry again")
1597
+
1598
+ # Wait with exponential backoff
1599
+ if attempt < action.max_retries:
1600
+ delay = min(base_delay * (backoff_factor**attempt), max_delay)
1601
+ await asyncio.sleep(delay)
1602
+
1603
+ except Exception as e:
1604
+ action.execution_log.append(f"Retry attempt {attempt + 1} error: {str(e)}")
1605
+
1606
+ action.execution_log.append("All retry attempts exhausted")
1607
+ return False
1608
+
1609
+ async def _execute_circuit_breaker_action(self, action: AdvancedRecoveryAction) -> bool:
1610
+ """Execute circuit breaker action"""
1611
+ failure = self.advanced_failures[action.failure_id]
1612
+ component = failure.component
1613
+
1614
+ # Update circuit breaker state
1615
+ cb_state = self.circuit_breaker_states[component]
1616
+ cb_state["state"] = "OPEN"
1617
+ cb_state["failure_count"] += 1
1618
+ cb_state["last_failure_time"] = datetime.now(timezone.utc).isoformat()
1619
+
1620
+ action.execution_log.append(f"Circuit breaker opened for component: {component}")
1621
+ return True
1622
+
1623
+ async def _execute_rollback_action(self, action: AdvancedRecoveryAction) -> bool:
1624
+ """Execute rollback action"""
1625
+ try:
1626
+ # Create a snapshot before rollback
1627
+ snapshot_id = await self._create_system_snapshot("pre_rollback_snapshot")
1628
+
1629
+ # Perform rollback logic
1630
+ action.execution_log.append("Creating rollback snapshot and performing rollback")
1631
+
1632
+ # In real implementation, this would restore system state from snapshot
1633
+ self.advanced_recovery_stats["rollbacks_performed"] += 1
1634
+
1635
+ action.rollback_action_id = snapshot_id
1636
+ return True
1637
+
1638
+ except Exception as e:
1639
+ action.execution_log.append(f"Rollback failed: {str(e)}")
1640
+ return False
1641
+
1642
+ async def _execute_quarantine_action(self, action: AdvancedRecoveryAction) -> bool:
1643
+ """Execute quarantine action"""
1644
+ failure = self.advanced_failures[action.failure_id]
1645
+ component = failure.component
1646
+
1647
+ action.execution_log.append(f"Quarantining component: {component}")
1648
+
1649
+ # In real implementation, this would isolate the component
1650
+ # For now, just log the action
1651
+ return True
1652
+
1653
+ async def _execute_legacy_recovery_action(self, action: AdvancedRecoveryAction) -> bool:
1654
+ """Execute legacy recovery action as fallback"""
1655
+ failure = self.advanced_failures[action.failure_id]
1656
+
1657
+ # Convert to legacy format and use existing recovery mechanisms
1658
+ legacy_action = self.recovery_actions.get("restart_research_engines")
1659
+ if not legacy_action:
1660
+ action.execution_log.append("No legacy recovery action available")
1661
+ return False
1662
+
1663
+ # Create legacy error report
1664
+ legacy_error = ErrorReport(
1665
+ id=failure.failure_id,
1666
+ timestamp=failure.timestamp,
1667
+ severity=getattr(ErrorSeverity, failure.severity.upper(), ErrorSeverity.MEDIUM),
1668
+ category=getattr(ErrorCategory, "SYSTEM", ErrorCategory.SYSTEM),
1669
+ message=failure.description,
1670
+ details=failure.error_details or {},
1671
+ stack_trace="",
1672
+ context=failure.context,
1673
+ )
1674
+
1675
+ try:
1676
+ result = legacy_action.handler(legacy_error, action.parameters)
1677
+ if result:
1678
+ action.execution_log.append("Legacy recovery action successful")
1679
+ return True
1680
+ else:
1681
+ action.execution_log.append("Legacy recovery action failed")
1682
+ return False
1683
+ except Exception as e:
1684
+ action.execution_log.append(f"Legacy recovery action error: {str(e)}")
1685
+ return False
1686
+
1687
+ def _determine_advanced_recovery_strategy(self, failure_mode: FailureMode) -> RecoveryStrategy:
1688
+ """Determine advanced recovery strategy based on failure mode"""
1689
+ strategy_map = {
1690
+ FailureMode.HOOK_EXECUTION_FAILURE: RecoveryStrategy.RETRY_WITH_BACKOFF,
1691
+ FailureMode.RESOURCE_EXHAUSTION: RecoveryStrategy.DEGRADE_SERVICE,
1692
+ FailureMode.DATA_CORRUPTION: RecoveryStrategy.ROLLBACK,
1693
+ FailureMode.NETWORK_FAILURE: RecoveryStrategy.RETRY_WITH_BACKOFF,
1694
+ FailureMode.SYSTEM_OVERLOAD: RecoveryStrategy.CIRCUIT_BREAKER,
1695
+ FailureMode.CIRCUIT_BREAKER_TRIPPED: RecoveryStrategy.CIRCUIT_BREAKER,
1696
+ FailureMode.CASCADE_FAILURE: RecoveryStrategy.EMERGENCY_STOP,
1697
+ FailureMode.TIMEOUT_FAILURE: RecoveryStrategy.RETRY_WITH_BACKOFF,
1698
+ FailureMode.MEMORY_LEAK: RecoveryStrategy.RESTART_COMPONENT,
1699
+ FailureMode.DEADLOCK: RecoveryStrategy.QUARANTINE,
1700
+ FailureMode.AUTHENTICATION_FAILURE: RecoveryStrategy.NOTIFY_ADMIN,
1701
+ FailureMode.VALIDATION_FAILURE: RecoveryStrategy.QUARANTINE,
1702
+ FailureMode.EXTERNAL_SERVICE_FAILURE: RecoveryStrategy.FAILOVER,
1703
+ FailureMode.STORAGE_FAILURE: RecoveryStrategy.ROLLBACK,
1704
+ FailureMode.CONCURRENCY_ISSUE: RecoveryStrategy.CIRCUIT_BREAKER,
1705
+ }
1706
+
1707
+ return strategy_map.get(failure_mode, RecoveryStrategy.RETRY_WITH_BACKOFF)
1708
+
1709
+ def _calculate_recovery_priority(self, failure: FailureEvent) -> int:
1710
+ """Calculate recovery priority based on failure characteristics"""
1711
+ base_priority = 5
1712
+
1713
+ # Adjust based on severity
1714
+ if failure.severity == "critical":
1715
+ base_priority -= 3
1716
+ elif failure.severity == "high":
1717
+ base_priority -= 2
1718
+ elif failure.severity == "medium":
1719
+ base_priority -= 1
1720
+
1721
+ # Adjust based on number of affected operations
1722
+ if len(failure.affected_operations) > 10:
1723
+ base_priority -= 2
1724
+ elif len(failure.affected_operations) > 5:
1725
+ base_priority -= 1
1726
+
1727
+ # Ensure priority is in valid range
1728
+ return max(1, min(10, base_priority))
1729
+
1730
+ async def _check_cascade_failures(self, failure: FailureEvent):
1731
+ """Check for cascade failure patterns"""
1732
+ # Check if this failure is related to other recent failures
1733
+ recent_failures = [
1734
+ f
1735
+ for f in self.advanced_failures.values()
1736
+ if (datetime.now(timezone.utc) - f.timestamp).total_seconds() < 300 # Last 5 minutes
1737
+ and f.failure_id != failure.failure_id
1738
+ ]
1739
+
1740
+ # Simple cascade detection: same component or related components
1741
+ related_failures = [
1742
+ f
1743
+ for f in recent_failures
1744
+ if f.component == failure.component or f.component in failure.context.get("related_components", [])
1745
+ ]
1746
+
1747
+ if len(related_failures) >= 3:
1748
+ self.advanced_recovery_stats["cascade_failures_detected"] += 1
1749
+ logger.warning(f"Cascade failure detected: {len(related_failures)} related failures")
1750
+
1751
+ # Trigger emergency recovery
1752
+ await self._trigger_emergency_recovery(failure, related_failures)
1753
+
1754
+ async def _trigger_emergency_recovery(self, failure: FailureEvent, related_failures: List[FailureEvent]):
1755
+ """Trigger emergency recovery for cascade failures"""
1756
+ emergency_action = AdvancedRecoveryAction(
1757
+ action_id=str(uuid.uuid4()),
1758
+ failure_id=failure.failure_id,
1759
+ strategy=RecoveryStrategy.EMERGENCY_STOP,
1760
+ timestamp=datetime.now(timezone.utc),
1761
+ description="Emergency recovery for cascade failure",
1762
+ parameters={"cascade_failures": [f.failure_id for f in related_failures]},
1763
+ priority=1, # Highest priority
1764
+ )
1765
+
1766
+ await self._execute_advanced_recovery_action(emergency_action)
1767
+
1768
+ async def _analyze_cascade_failure(self, failure: FailureEvent):
1769
+ """Analyze cascade failure patterns"""
1770
+ # Implementation would analyze failure patterns and correlations
1771
+ pass
1772
+
1773
+ async def _analyze_circuit_breaker_trip(self, failure: FailureEvent):
1774
+ """Analyze circuit breaker trip patterns"""
1775
+ # Implementation would analyze circuit breaker behavior
1776
+ pass
1777
+
1778
+ async def _analyze_resource_exhaustion(self, failure: FailureEvent):
1779
+ """Analyze resource exhaustion patterns"""
1780
+ # Implementation would analyze resource usage patterns
1781
+ pass
1782
+
1783
+ async def _create_system_snapshot(self, description: str = "", is_rollback_point: bool = False) -> str:
1784
+ """Create a system state snapshot"""
1785
+ snapshot_id = str(uuid.uuid4())
1786
+
1787
+ # Get current system state
1788
+ component_states = {
1789
+ "error_recovery_system": {
1790
+ "active_errors": len(self.active_errors),
1791
+ "advanced_failures": len(self.advanced_failures),
1792
+ "system_health": self.system_health["status"],
1793
+ },
1794
+ "circuit_breakers": dict(self.circuit_breaker_states),
1795
+ "recovery_stats": self.advanced_recovery_stats.copy(),
1796
+ }
1797
+
1798
+ # Calculate checksums
1799
+ config_str = json.dumps(component_states, sort_keys=True)
1800
+ config_hash = hashlib.sha256(config_str.encode()).hexdigest()
1801
+
1802
+ data_checksums = {
1803
+ "component_states": hashlib.sha256(config_str.encode()).hexdigest(),
1804
+ }
1805
+
1806
+ snapshot = SystemSnapshot(
1807
+ snapshot_id=snapshot_id,
1808
+ timestamp=datetime.now(timezone.utc),
1809
+ component_states=component_states,
1810
+ configuration_hash=config_hash,
1811
+ data_checksums=data_checksums,
1812
+ description=description,
1813
+ is_rollback_point=is_rollback_point,
1814
+ )
1815
+
1816
+ self.system_snapshots[snapshot_id] = snapshot
1817
+ self.advanced_recovery_stats["snapshots_created"] += 1
1818
+
1819
+ logger.info(f"Created system snapshot: {snapshot_id}")
1820
+ return snapshot_id
1821
+
1822
+ def get_advanced_system_status(self) -> Dict[str, Any]:
1823
+ """Get comprehensive advanced system status"""
1824
+ return {
1825
+ "status": "running",
1826
+ "phase3_features": "enabled",
1827
+ "advanced_recovery_statistics": self.advanced_recovery_stats,
1828
+ "active_advanced_failures": len(self.advanced_failures),
1829
+ "pending_advanced_actions": len(
1830
+ [
1831
+ a
1832
+ for a in self.advanced_recovery_actions.values()
1833
+ if a.status in [RecoveryStatus.PENDING, RecoveryStatus.IN_PROGRESS]
1834
+ ]
1835
+ ),
1836
+ "circuit_breaker_states": dict(self.circuit_breaker_states),
1837
+ "system_snapshots": len(self.system_snapshots),
1838
+ "dead_letter_queue_size": len(self.dead_letter_queue),
1839
+ "failure_mode_analyzers": list(self.failure_analyzers.keys()),
1840
+ }
1841
+
1842
+
1843
+ # Global error recovery system instance
1844
+ _error_recovery_system = None
1845
+
1846
+
1847
+ def get_error_recovery_system(project_root: Path = None) -> ErrorRecoverySystem:
1848
+ """Get or create global error recovery system instance"""
1849
+ global _error_recovery_system
1850
+ if _error_recovery_system is None:
1851
+ _error_recovery_system = ErrorRecoverySystem(project_root)
1852
+ return _error_recovery_system
1853
+
1854
+
1855
+ def handle_error(
1856
+ error: Exception,
1857
+ context: Dict[str, Any] = None,
1858
+ severity: ErrorSeverity = ErrorSeverity.MEDIUM,
1859
+ category: ErrorCategory = ErrorCategory.SYSTEM,
1860
+ ) -> ErrorReport:
1861
+ """Convenience function to handle errors using global system"""
1862
+ return get_error_recovery_system().handle_error(error, context, severity, category)
1863
+
1864
+
1865
+ # Decorator for automatic error handling
1866
+ def error_handler(
1867
+ severity: ErrorSeverity = ErrorSeverity.MEDIUM,
1868
+ category: ErrorCategory = ErrorCategory.SYSTEM,
1869
+ context: Dict[str, Any] = None,
1870
+ ):
1871
+ """Decorator for automatic error handling"""
1872
+
1873
+ def decorator(func):
1874
+ def wrapper(*args, **kwargs):
1875
+ try:
1876
+ return func(*args, **kwargs)
1877
+ except Exception as e:
1878
+ error_context = {
1879
+ "function": func.__name__,
1880
+ "module": func.__module__,
1881
+ "args": str(args)[:100], # Limit length
1882
+ "kwargs": str(kwargs)[:100],
1883
+ **(context or {}),
1884
+ }
1885
+ handle_error(e, error_context, severity, category)
1886
+ raise
1887
+
1888
+ return wrapper
1889
+
1890
+ return decorator
1891
+
1892
+
1893
+ if __name__ == "__main__":
1894
+ # Demo usage
1895
+ recovery_system = ErrorRecoverySystem()
1896
+
1897
+ print("Error Recovery System Demo")
1898
+ print("=" * 50)
1899
+
1900
+ # Simulate some errors
1901
+ try:
1902
+ raise ValueError("This is a test error for demonstration")
1903
+ except Exception as e:
1904
+ error_report = recovery_system.handle_error(
1905
+ e,
1906
+ context={"demo": True},
1907
+ severity=ErrorSeverity.MEDIUM,
1908
+ category=ErrorCategory.SYSTEM,
1909
+ )
1910
+ print(f"Handled error: {error_report.id}")
1911
+
1912
+ # Show system health
1913
+ health = recovery_system.get_system_health()
1914
+ print(f"System health: {health['status']}")
1915
+
1916
+ # Show error summary
1917
+ summary = recovery_system.get_error_summary()
1918
+ print(f"Total errors: {summary['total_recent_errors']}")
1919
+
1920
+ print("\nError Recovery System demo completed")